写个五子棋小游戏
时间: 2023-07-09 10:14:09 浏览: 122
好的,我可以给你提供一个简单的c#五子棋小游戏的示例代码,规则如下:
1. 两个玩家分别使用黑子和白子,轮流落子;
2. 落子时,玩家需要输入坐标,如“3,2”表示在第3行第2列落子;
3. 当一方连成五子时,游戏结束,显示胜利信息;
4. 如果棋盘填满仍未分出胜负,则宣布平局。
下面是示例代码:
```csharp
using System;
namespace Gomoku
{
class Program
{
static int[,] board = new int[15, 15]; // 棋盘,0表示空,1表示黑子,2表示白子
static int currentPlayer = 1; // 当前玩家,1表示黑子,2表示白子
static void Main(string[] args)
{
Console.WriteLine("欢迎来到五子棋游戏!");
DrawBoard();
while (true)
{
Console.WriteLine($"请 {GetPlayerName(currentPlayer)} 落子(输入坐标,如“3,2”):");
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
{
Console.WriteLine("无效输入!");
continue;
}
string[] parts = input.Split(',');
if (parts.Length != 2 || !int.TryParse(parts[0], out int row) || !int.TryParse(parts[1], out int col))
{
Console.WriteLine("无效输入!");
continue;
}
if (row < 1 || row > 15 || col < 1 || col > 15)
{
Console.WriteLine("坐标超出范围!");
continue;
}
if (board[row - 1, col - 1] != 0)
{
Console.WriteLine("该位置已有棋子,请重新输入!");
continue;
}
board[row - 1, col - 1] = currentPlayer;
DrawBoard();
if (CheckWin(row - 1, col - 1))
{
Console.WriteLine($"恭喜 {GetPlayerName(currentPlayer)} 获胜!");
break;
}
if (CheckDraw())
{
Console.WriteLine("平局!");
break;
}
currentPlayer = currentPlayer == 1 ? 2 : 1;
}
Console.WriteLine("按任意键结束游戏...");
Console.ReadKey();
}
static void DrawBoard()
{
Console.Clear();
Console.WriteLine(" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15");
for (int i = 0; i < 15; i++)
{
Console.Write($"{i + 1} ");
for (int j = 0; j < 15; j++)
{
switch (board[i, j])
{
case 0:
Console.Write("+ ");
break;
case 1:
Console.Write("● ");
break;
case 2:
Console.Write("○ ");
break;
}
}
Console.WriteLine();
}
}
static bool CheckWin(int row, int col)
{
int count = 1;
int x, y;
// 横向
x = col - 1;
y = row;
while (x >= 0 && board[y, x] == currentPlayer)
{
count++;
x--;
}
x = col + 1;
while (x < 15 && board[y, x] == currentPlayer)
{
count++;
x++;
}
if (count >= 5)
{
return true;
}
// 纵向
count = 1;
x = col;
y = row - 1;
while (y >= 0 && board[y, x] == currentPlayer)
{
count++;
y--;
}
y = row + 1;
while (y < 15 && board[y, x] == currentPlayer)
{
count++;
y++;
}
if (count >= 5)
{
return true;
}
// 左上到右下
count = 1;
x = col - 1;
y = row - 1;
while (x >= 0 && y >= 0 && board[y, x] == currentPlayer)
{
count++;
x--;
y--;
}
x = col + 1;
y = row + 1;
while (x < 15 && y < 15 && board[y, x] == currentPlayer)
{
count++;
x++;
y++;
}
if (count >= 5)
{
return true;
}
// 右上到左下
count = 1;
x = col + 1;
y = row - 1;
while (x < 15 && y >= 0 && board[y, x] == currentPlayer)
{
count++;
x++;
y--;
}
x = col - 1;
y = row + 1;
while (x >= 0 && y < 15 && board[y, x] == currentPlayer)
{
count++;
x--;
y++;
}
if (count >= 5)
{
return true;
}
return false;
}
static bool CheckDraw()
{
for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 15; j++)
{
if (board[i, j] == 0)
{
return false;
}
}
}
return true;
}
static string GetPlayerName(int player)
{
return player == 1 ? "黑子" : "白子";
}
}
}
```
希望这个示例代码可以帮助你了解如何使用c#编写一个简单的五子棋小游戏。
阅读全文