西安交通大学c#五子棋
时间: 2023-11-22 13:48:02 浏览: 46
以下是西安交通大学C#五子棋的实现方法:
1. 创建一个棋盘类,包含棋盘大小、棋子颜色等属性和方法。
```csharp
public class Chessboard
{
private int size; // 棋盘大小
private int[,] board; // 棋盘数组,0表示空,1表示黑子,2表示白子
public Chessboard(int size)
{
this.size = size;
board = new int[size, size];
}
public bool PutChess(int x, int y, int color)
{
if (x < 0 || x >= size || y < 0 || y >= size || board[x, y] != 0)
{
return false;
}
board[x, y] = color;
return true;
}
public int CheckWin(int x, int y)
{
int color = board[x, y];
int count = 1;
int i, j;
// 横向
for (i = x - 1; i >= 0 && board[i, y] == color; i--)
{
count++;
}
for (i = x + 1; i < size && board[i, y] == color; i++)
{
count++;
}
if (count >= 5)
{
return color;
}
// 纵向
count = 1;
for (j = y - 1; j >= 0 && board[x, j] == color; j--)
{
count++;
}
for (j = y + 1; j < size && board[x, j] == color; j++)
{
count++;
}
if (count >= 5)
{
return color;
}
// 左上到右下
count = 1;
for (i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i, j] == color; i--, j--)
{
count++;
}
for (i = x + 1, j = y + 1; i < size && j < size && board[i, j] == color; i++, j++)
{
count++;
}
if (count >= 5)
{
return color;
}
// 右上到左下
count = 1;
for (i = x + 1, j = y - 1; i < size && j >= 0 && board[i, j] == color; i++, j--)
{
count++;
}
for (i = x - 1, j = y + 1; i >= 0 && j < size && board[i, j] == color; i--, j++)
{
count++;
}
if (count >= 5)
{
return color;
}
return 0;
}
}
```
2. 创建一个游戏类,包含游戏状态、当前玩家、棋盘等属性和方法。
```csharp
public class Game
{
private Chessboard chessboard;
private int currentPlayer;
private bool isPlaying;
public Game(int size)
{
chessboard = new Chessboard(size);
currentPlayer = 1;
isPlaying = true;
}
public bool PutChess(int x, int y)
{
if (!isPlaying)
{
return false;
}
if (chessboard.PutChess(x, y, currentPlayer))
{
int winner = chessboard.CheckWin(x, y);
if (winner != 0)
{
Console.WriteLine("Player {0} wins!", winner);
isPlaying = false;
}
else
{
currentPlayer = 3 - currentPlayer;
}
return true;
}
return false;
}
}
```
3. 在主函数中创建游戏对象,并循环读取玩家输入并下棋。
```csharp
static void Main(string[] args)
{
Game game = new Game(15);
while (game.IsPlaying)
{
Console.WriteLine("Player {0}'s turn:", game.CurrentPlayer);
Console.Write("x = ");
int x = int.Parse(Console.ReadLine());
Console.Write("y = ");
int y = int.Parse(Console.ReadLine());
if (!game.PutChess(x, y))
{
Console.WriteLine("Invalid input!");
}
}
}
```