五子棋_csharp
时间: 2023-11-18 08:05:15 浏览: 39
以下是使用C#编写的五子棋游戏的示例代码:
```csharp
using System;
namespace Gomoku
{
class Program
{
static void Main(string[] args)
{
// 初始化棋盘
int[,] board = new int[15, 15];
for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 15; j++)
{
board[i, j] = 0;
}
}
// 游戏循环
int player = 1;
while (true)
{
// 打印棋盘
Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14");
for (int i = 0; i < 15; i++)
{
Console.Write(i + " ");
for (int j = 0; j < 15; j++)
{
if (board[i, j] == 0)
{
Console.Write("+ ");
}
else if (board[i, j] == 1)
{
Console.Write("O ");
}
else
{
Console.Write("X ");
}
}
Console.WriteLine();
}
// 获取玩家输入
Console.WriteLine("Player " + player + " make your move (row column):");
string[] input = Console.ReadLine().Split(' ');
int row = int.Parse(input[0]);
int col = int.Parse(input[1]);
// 检查输入是否合法
if (row < 0 || row > 14 || col < 0 || col > 14)
{
Console.WriteLine("Invalid input, please try again.");
continue;
}
if (board[row, col] != 0)
{
Console.WriteLine("That spot is already taken, please try again.");
continue;
}
// 在棋盘上放置棋子
board[row, col] = player;
// 检查是否有玩家获胜
if (CheckWin(board, row, col, player))
{
Console.WriteLine("Player " + player + " wins!");
break;
}
// 切换玩家
player = 3 - player;
}
}
// 检查是否有玩家获胜
static bool CheckWin(int[,] board, int row, int col, int player)
{
// 检查行
int count = 0;
for (int i = 0; i < 15; i++)
{
if (board[row, i] == player)
{
count++;
}
else
{
count = 0;
}
if (count == 5)
{
return true;
}
}
// 检查列
count = 0;
for (int i = 0; i < 15; i++)
{
if (board[i, col] == player)
{
count++;
}
else
{
count = 0;
}
if (count == 5)
{
return true;
}
}
// 检查正对角线
count = 0;
int r = row;
int c = col;
while (r > 0 && c > 0)
{
r--;
c--;
}
while (r < 15 && c < 15)
{
if (board[r, c] == player)
{
count++;
}
else
{
count = 0;
}
if (count == 5)
{
return true;
}
r++;
c++;
}
// 检查反对角线
count = 0;
r = row;
c = col;
while (r > 0 && c < 14)
{
r--;
c++;
}
while (r < 15 && c >= 0)
{
if (board[r, c] == player)
{
count++;
}
else
{
count = 0;
}
if (count == 5)
{
return true;
}
r++;
c--;
}
// 没有获胜
return false;
}
}
}
```