c语言五子棋源代码easyx
时间: 2023-09-24 15:10:40 浏览: 51
以下是一个简单的 C语言五子棋程序的源代码,使用了 EasyX 图形库:
```c
#include <graphics.h>
#define BOARD_SIZE 15
#define PIECE_SIZE 30
#define MARGIN_SIZE 40
int board[BOARD_SIZE][BOARD_SIZE] = {0};
int curPlayer = 1; // 1 for black, 2 for white
void drawBoard()
{
setlinecolor(BLACK);
for(int i = 0; i <= BOARD_SIZE; i++)
{
line(MARGIN_SIZE, MARGIN_SIZE + i * PIECE_SIZE, MARGIN_SIZE + BOARD_SIZE * PIECE_SIZE, MARGIN_SIZE + i * PIECE_SIZE);
line(MARGIN_SIZE + i * PIECE_SIZE, MARGIN_SIZE, MARGIN_SIZE + i * PIECE_SIZE, MARGIN_SIZE + BOARD_SIZE * PIECE_SIZE);
}
}
void drawPiece(int x, int y, int player)
{
setfillcolor(player == 1 ? BLACK : WHITE);
solidcircle(MARGIN_SIZE + x * PIECE_SIZE, MARGIN_SIZE + y * PIECE_SIZE, PIECE_SIZE / 2);
}
bool isValidPos(int x, int y)
{
if(x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE)
return false;
if(board[x][y] != 0)
return false;
return true;
}
bool checkGameOver(int x, int y)
{
int dx[] = {1, 1, 0, -1}, dy[] = {0, 1, 1, 1};
for(int i = 0; i < 4; i++)
{
int cnt = 1;
for(int j = 1; j <= 4; j++)
{
int nx = x + dx[i] * j, ny = y + dy[i] * j;
if(isValidPos(nx, ny) && board[nx][ny] == curPlayer)
cnt++;
else
break;
}
for(int j = 1; j <= 4; j++)
{
int nx = x - dx[i] * j, ny = y - dy[i] * j;
if(isValidPos(nx, ny) && board[nx][ny] == curPlayer)
cnt++;
else
break;
}
if(cnt >= 5)
return true;
}
return false;
}
int main()
{
initgraph(640, 640);
drawBoard();
while(true)
{
MOUSEMSG msg = GetMouseMsg();
if(msg.uMsg == WM_LBUTTONDOWN)
{
int x = (msg.x - MARGIN_SIZE + PIECE_SIZE / 2) / PIECE_SIZE,
y = (msg.y - MARGIN_SIZE + PIECE_SIZE / 2) / PIECE_SIZE;
if(!isValidPos(x, y))
continue;
drawPiece(x, y, curPlayer);
board[x][y] = curPlayer;
if(checkGameOver(x, y))
{
outtextxy(50, 300, curPlayer == 1 ? "Black wins!" : "White wins!");
while(true)
{
MOUSEMSG msg = GetMouseMsg();
if(msg.uMsg == WM_LBUTTONDOWN)
return 0;
}
}
curPlayer = curPlayer == 1 ? 2 : 1;
}
}
closegraph();
return 0;
}
```
这是一个非常简单的五子棋程序,只有基本的下棋、判断胜负等功能。如果需要更复杂的 AI 策略,可以考虑使用博弈树等算法。