请帮我用c#编写一个人机对战五子棋小游戏
时间: 2023-09-06 09:08:44 浏览: 52
好的,以下是一个简单的人机对战五子棋小游戏的 C# 代码示例:
```csharp
using System;
namespace Gomoku
{
class Program
{
static void Main(string[] args)
{
// 初始化棋盘
int[,] board = new int[15, 15];
// 游戏循环
while (true)
{
// 人类玩家下棋
Console.WriteLine("请您输入您下棋的坐标(格式:x,y):");
string input = Console.ReadLine();
string[] inputArray = input.Split(',');
int x = int.Parse(inputArray[0]);
int y = int.Parse(inputArray[1]);
board[x, y] = 1;
// 判断人类玩家是否胜利
if (IsWin(board, x, y, 1))
{
Console.WriteLine("您赢了!");
break;
}
// 电脑下棋
int[] computerMove = GetNextMove(board);
board[computerMove[0], computerMove[1]] = 2;
// 判断电脑是否胜利
if (IsWin(board, computerMove[0], computerMove[1], 2))
{
Console.WriteLine("电脑赢了!");
break;
}
// 打印当前棋盘状态
PrintBoard(board);
}
}
// 判断是否胜利
private static bool IsWin(int[,] board, int x, int y, int player)
{
int count = 1;
// 横向判断
for (int i = x - 1; i >= 0; i--)
{
if (board[i, y] == player)
{
count++;
}
else
{
break;
}
}
for (int i = x + 1; i < 15; i++)
{
if (board[i, y] == player)
{
count++;
}
else
{
break;
}
}
if (count >= 5)
{
return true;
}
// 竖向判断
count = 1;
for (int j = y - 1; j >= 0; j--)
{
if (board[x, j] == player)
{
count++;
}
else
{
break;
}
}
for (int j = y + 1; j < 15; j++)
{
if (board[x, j] == player)
{
count++;
}
else
{
break;
}
}
if (count >= 5)
{
return true;
}
// 斜向判断
count = 1;
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0; i--, j--)
{
if (board[i, j] == player)
{
count++;
}
else
{
break;
}
}
for (int i = x + 1, j = y + 1; i < 15 && j < 15; i++, j++)
{
if (board[i, j] == player)
{
count++;
}
else
{
break;
}
}
if (count >= 5)
{
return true;
}
// 反斜向判断
count = 1;
for (int i = x - 1, j = y + 1; i >= 0 && j < 15; i--, j++)
{
if (board[i, j] == player)
{
count++;
}
else
{
break;
}
}
for (int i = x + 1, j = y - 1; i < 15 && j >= 0; i++, j--)
{
if (board[i, j] == player)
{
count++;
}
else
{
break;
}
}
if (count >= 5)
{
return true;
}
return false;
}
// 获取电脑下棋的位置
private static int[] GetNextMove(int[,] board)
{
int[] move = new int[2];
// 随机生成下棋位置
Random random = new Random();
while (true)
{
int x = random.Next(15);
int y = random.Next(15);
if (board[x, y] == 0)
{
move[0] = x;
move[1] = y;
break;
}
}
return move;
}
// 打印当前棋盘状态
private static void PrintBoard(int[,] board)
{
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("● ");
}
else
{
Console.Write("○ ");
}
}
Console.WriteLine();
}
}
}
}
```
这个示例程序实现了一个简单的人机对战五子棋小游戏,其中 1 表示玩家下的棋子,2 表示电脑下的棋子,0 表示空位。您可以在此基础上进行修改和扩展,实现更复杂的功能。