帮我用c#写一个五子棋的游戏代码
时间: 2023-08-20 14:42:33 浏览: 114
好的,以下是五子棋游戏的 C# 代码实现,供您参考:
```csharp
using System;
namespace GomokuGame
{
class Program
{
static int[,] Board = new int[15, 15]; // 棋盘
static bool IsBlack = true; // 判断当前是黑棋还是白棋
static void Main(string[] args)
{
Console.WriteLine("欢迎来到五子棋游戏!");
Console.WriteLine("黑棋先手,白棋后手。");
PrintBoard();
while (true)
{
Console.Write(IsBlack ? "黑棋" : "白棋");
Console.Write("请落子(例如:3,4):");
try
{
string input = Console.ReadLine();
string[] positions = input.Split(',');
int x = int.Parse(positions[0]) - 1;
int y = int.Parse(positions[1]) - 1;
if (x < 0 || x > 14 || y < 0 || y > 14)
{
Console.WriteLine("输入的坐标不合法,请重新输入!");
continue;
}
if (Board[x, y] != 0)
{
Console.WriteLine("该位置已经有棋子了,请重新输入!");
continue;
}
Board[x, y] = IsBlack ? 1 : 2; // 黑棋为1,白棋为2
PrintBoard();
if (IsWin(x, y))
{
Console.WriteLine(IsBlack ? "黑棋胜利!" : "白棋胜利!");
break;
}
IsBlack = !IsBlack; // 切换下棋方
}
catch
{
Console.WriteLine("输入的坐标格式不正确,请重新输入!");
}
}
Console.WriteLine("游戏结束。");
Console.ReadLine();
}
// 打印棋盘
static void PrintBoard()
{
Console.Write(" ");
for (int i = 1; i <= 15; i++)
{
Console.Write(i + " ");
}
Console.WriteLine();
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 IsWin(int x, int y)
{
int count = 0;
// 判断横向
for (int i = 0; i < 15; i++)
{
if (Board[x, i] == Board[x, y])
{
count++;
}
else
{
count = 0;
}
if (count == 5)
{
return true;
}
}
// 判断纵向
count = 0;
for (int i = 0; i < 15; i++)
{
if (Board[i, y] == Board[x, y])
{
count++;
}
else
{
count = 0;
}
if (count == 5)
{
return true;
}
}
// 判断左上到右下斜线
count = 0;
int min = Math.Min(x, y);
int startX = x - min;
int startY = y - min;
for (int i = startX, j = startY; i < 15 && j < 15; i++, j++)
{
if (Board[i, j] == Board[x, y])
{
count++;
}
else
{
count = 0;
}
if (count == 5)
{
return true;
}
}
// 判断左下到右上斜线
count = 0;
min = Math.Min(x, 14 - y);
startX = x - min;
startY = y + min;
for (int i = startX, j = startY; i < 15 && j >= 0; i++, j--)
{
if (Board[i, j] == Board[x, y])
{
count++;
}
else
{
count = 0;
}
if (count == 5)
{
return true;
}
}
return false;
}
}
}
```
这段代码实现了五子棋游戏的基本功能,包括打印棋盘、落子、判断胜负等。您可以在此基础上进行扩展,实现更多的功能。
阅读全文