用C语言基于EASYX制作一个井字棋小游戏:要求如下:1.人和人对弈,双方用O和X表示,轮流落子; 2.3*3棋盘; 3.Asdf键控制方向,高亮显示当前位置,回车确认落子; 4.首先将三个棋子连成一条直线的获胜
时间: 2024-02-22 21:57:48 浏览: 102
好的,以下是基于EASYX的井字棋小游戏的代码:
```c
#include <graphics.h>
#include <conio.h>
#define SIZE 100 // 棋盘格子的边长
#define ROW 3 // 棋盘行数
#define COL 3 // 棋盘列数
int board[ROW][COL] = {0}; // 棋盘状态,0表示空,1表示O,2表示X
int cur_x = 1, cur_y = 1; // 当前光标所在位置的行列坐标
int player = 1; // 当前玩家,1表示O,2表示X
void drawBoard(); // 绘制棋盘
void drawChess(int x, int y, int player); // 在(x,y)位置绘制player的棋子
int checkWin(int player); // 判断player是否获胜
void showMessage(const char* msg); // 显示消息
int main()
{
initgraph(ROW * SIZE, COL * SIZE);
drawBoard();
int key;
while (true) {
key = getch();
if (key == 27) { // ESC键退出
break;
} else if (key == 'a') { // 左移
if (cur_y > 0) {
cur_y--;
}
} else if (key == 'd') { // 右移
if (cur_y < COL - 1) {
cur_y++;
}
} else if (key == 'w') { // 上移
if (cur_x > 0) {
cur_x--;
}
} else if (key == 's') { // 下移
if (cur_x < ROW - 1) {
cur_x++;
}
} else if (key == 13) { // 回车键确认落子
if (board[cur_x][cur_y] == 0) { // 如果当前位置为空
drawChess(cur_x, cur_y, player); // 绘制棋子
if (checkWin(player)) { // 如果当前玩家获胜
showMessage(player == 1 ? "O wins!" : "X wins!");
break;
} else if (player == 1) { // 切换到下一个玩家
player = 2;
} else {
player = 1;
}
}
}
}
closegraph();
return 0;
}
void drawBoard()
{
setbkcolor(WHITE);
cleardevice();
// 绘制横线
for (int i = 1; i < ROW; i++) {
line(0, i * SIZE, ROW * SIZE, i * SIZE);
}
// 绘制竖线
for (int j = 1; j < COL; j++) {
line(j * SIZE, 0, j * SIZE, COL * SIZE);
}
// 绘制光标
setfillcolor(GREEN);
solidrectangle(cur_y * SIZE, cur_x * SIZE, (cur_y + 1) * SIZE, (cur_x + 1) * SIZE);
}
void drawChess(int x, int y, int player)
{
board[x][y] = player;
settextcolor(player == 1 ? BLUE : RED);
settextstyle(SIZE / 2, 0, "Arial");
outtextxy(y * SIZE + SIZE / 4, x * SIZE + SIZE / 4, player == 1 ? "O" : "X");
}
int checkWin(int player)
{
for (int i = 0; i < ROW; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return true; // 横向获胜
}
}
for (int j = 0; j < COL; j++) {
if (board[0][j] == player && board[1][j] == player && board[2][j] == player) {
return true; // 竖向获胜
}
}
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
return true; // 左上到右下斜向获胜
}
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
return true; // 右上到左下斜向获胜
}
return false;
}
void showMessage(const char* msg)
{
setbkcolor(WHITE);
settextcolor(RED);
settextstyle(SIZE, 0, "Arial");
outtextxy(0, ROW * SIZE + SIZE / 2, msg);
}
```
希望对你有帮助!
阅读全文