C#编写的五子棋代码
时间: 2023-07-02 15:21:24 浏览: 67
以下是 C# 编写的五子棋代码,供您参考:
```csharp
using System;
namespace FiveChess
{
class Program
{
static int[,] chessboard = new int[15, 15]; // 15 * 15 的棋盘
static bool isBlack = true; // 黑方先手
static void Main(string[] args)
{
Console.WriteLine("欢迎来到五子棋游戏!");
while (true)
{
DrawChessboard(); // 绘制棋盘
int[] point = GetInput(); // 获取用户输入的坐标
PlaceChess(point); // 落子
if (IsWin(point)) // 判断是否胜利
{
Console.WriteLine("恭喜你," + (isBlack ? "黑方" : "白方") + "获胜!");
break;
}
isBlack = !isBlack; // 切换下棋方
}
}
// 绘制棋盘
static void DrawChessboard()
{
Console.Clear();
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 (chessboard[i, j] == 1)
Console.Write("● ");
else if (chessboard[i, j] == 2)
Console.Write("○ ");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
// 获取用户输入的坐标
static int[] GetInput()
{
int[] point = new int[2];
while (true)
{
Console.Write((isBlack ? "黑方" : "白方") + "请落子,输入坐标:");
string input = Console.ReadLine();
if (int.TryParse(input, out int x) && x >= 0 && x < 15)
{
point[0] = x;
break;
}
else
Console.WriteLine("输入不合法,请重新输入!");
}
while (true)
{
Console.Write("请输入纵坐标:");
string input = Console.ReadLine();
if (int.TryParse(input, out int y) && y >= 0 && y < 15)
{
point[1] = y;
break;
}
else
Console.WriteLine("输入不合法,请重新输入!");
}
return point;
}
// 落子
static void PlaceChess(int[] point)
{
if (chessboard[point[0], point[1]] != 0)
{
Console.WriteLine("该位置已经有棋子了,请重新落子!");
PlaceChess(GetInput());
}
else
chessboard[point[0], point[1]] = isBlack ? 1 : 2;
}
// 判断是否胜利
static bool IsWin(int[] point)
{
int count = 1;
// 判断横向
for (int i = point[1] - 1; i >= 0; i--)
{
if (chessboard[point[0], i] == (isBlack ? 1 : 2))
count++;
else
break;
}
for (int i = point[1] + 1; i < 15; i++)
{
if (chessboard[point[0], i] == (isBlack ? 1 : 2))
count++;
else
break;
}
if (count >= 5)
return true;
// 判断纵向
count = 1;
for (int i = point[0] - 1; i >= 0; i--)
{
if (chessboard[i, point[1]] == (isBlack ? 1 : 2))
count++;
else
break;
}
for (int i = point[0] + 1; i < 15; i++)
{
if (chessboard[i, point[1]] == (isBlack ? 1 : 2))
count++;
else
break;
}
if (count >= 5)
return true;
// 判断左上 - 右下
count = 1;
for (int i = point[0] - 1, j = point[1] - 1; i >= 0 && j >= 0; i--, j--)
{
if (chessboard[i, j] == (isBlack ? 1 : 2))
count++;
else
break;
}
for (int i = point[0] + 1, j = point[1] + 1; i < 15 && j < 15; i++, j++)
{
if (chessboard[i, j] == (isBlack ? 1 : 2))
count++;
else
break;
}
if (count >= 5)
return true;
// 判断右上 - 左下
count = 1;
for (int i = point[0] - 1, j = point[1] + 1; i >= 0 && j < 15; i--, j++)
{
if (chessboard[i, j] == (isBlack ? 1 : 2))
count++;
else
break;
}
for (int i = point[0] + 1, j = point[1] - 1; i < 15 && j >= 0; i++, j--)
{
if (chessboard[i, j] == (isBlack ? 1 : 2))
count++;
else
break;
}
if (count >= 5)
return true;
return false;
}
}
}
```
这是一个简单的五子棋程序,可以在控制台中运行。