c#实现五子棋小游戏
时间: 2023-07-27 08:21:45 浏览: 55
好的,下面是一个简单的 C# 实现五子棋小游戏的示例代码。
首先,在窗体上添加一个 PictureBox 控件,用于绘制游戏棋盘。
```csharp
public partial class Form1 : Form
{
private const int ROWS = 15; // 棋盘行数
private const int COLS = 15; // 棋盘列数
private const int CELL_SIZE = 30; // 每个格子的大小
private int[,] board; // 棋盘数组,0表示空格,1表示黑棋,2表示白棋
private bool isBlackTurn; // 当前轮到黑棋或白棋下
public Form1()
{
InitializeComponent();
board = new int[ROWS, COLS];
isBlackTurn = true;
// 初始化棋盘数组
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
board[i, j] = 0;
}
}
// 设置PictureBox控件的大小和背景色
pictureBox1.Width = ROWS * CELL_SIZE;
pictureBox1.Height = COLS * CELL_SIZE;
pictureBox1.BackColor = Color.FromArgb(255, 225, 158);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
// 绘制棋盘
Pen pen = new Pen(Color.Black, 2);
for (int i = 0; i <= ROWS; i++)
{
e.Graphics.DrawLine(pen, i * CELL_SIZE, 0, i * CELL_SIZE, ROWS * CELL_SIZE);
}
for (int j = 0; j <= COLS; j++)
{
e.Graphics.DrawLine(pen, 0, j * CELL_SIZE, COLS * CELL_SIZE, j * CELL_SIZE);
}
// 绘制棋子
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
if (board[i, j] == 1)
{
e.Graphics.FillEllipse(Brushes.Black, i * CELL_SIZE - CELL_SIZE / 2, j * CELL_SIZE - CELL_SIZE / 2, CELL_SIZE, CELL_SIZE);
}
else if (board[i, j] == 2)
{
e.Graphics.FillEllipse(Brushes.White, i * CELL_SIZE - CELL_SIZE / 2, j * CELL_SIZE - CELL_SIZE / 2, CELL_SIZE, CELL_SIZE);
}
}
}
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
int x = e.X / CELL_SIZE;
int y = e.Y / CELL_SIZE;
if (x >= 0 && x < ROWS && y >= 0 && y < COLS && board[x, y] == 0)
{
if (isBlackTurn)
{
board[x, y] = 1;
}
else
{
board[x, y] = 2;
}
isBlackTurn = !isBlackTurn;
pictureBox1.Invalidate(); // 重新绘制PictureBox控件
}
}
}
```
在窗体设计器中,将 PictureBox 控件的 Paint 事件和 MouseClick 事件分别绑定到 pictureBox1_Paint 和 pictureBox1_MouseClick 方法。
这样就完成了一个简单的五子棋小游戏。