用c语言写一个井字棋游戏,写出完整代码
时间: 2024-06-17 17:02:29 浏览: 164
好的,下面是一个简单的 C 语言井字棋游戏的完整代码:
```
#include <stdio.h>
char board = { {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '} };
void display_board()
{
printf("\n");
printf(" %c | %c | %c \n", board, board, board);
printf("---+---+---\n");
printf(" %c | %c | %c \n", board, board, board);
printf("---+---+---\n");
printf(" %c | %c | %c \n", board, board, board);
}
int check_win()
{
int i;
// 检查行
for (i = 0; i < 3; i++) {
if (board[i] == board[i] && board[i] == board[i]) {
if (board[i] == 'X')
return 1;
else if (board[i] == 'O')
return -1;
}
}
// 检查列
for (i = 0; i < 3; i++) {
if (board[i] == board[i] && board[i] == board[i]) {
if (board[i] == 'X')
return 1;
else if (board[i] == 'O')
return -1;
}
}
// 检查对角线
if (board == board && board[1] == board) {
if (board == 'X')
return 1;
else if (board == 'O')
return -1;
}
if (board == board && board == board) {
if (board == 'X')
return 1;
else if (board == 'O')
return -1;
}
return 0;
}
int main()
{
int x, y, player = 1;
while (check_win() == 0) {
display_board();
printf("\nPlayer %d, enter x and y coordinates for your move: ", player);
scanf("%d%d", &x, &y);
if (x < 0 || x > 2 || y < 0 || y > 2) {
printf("\nInvalid coordinates! Try again.\n");
continue;
}
if (board[x][y] != ' ') {
printf("\nThat square is already occupied! Try again.\n");
continue;
}
if (player == 1) {
board[x][y] = 'X';
player = 2;
} else {
board[x][y] = 'O';
player = 1;
}
}
display_board();
if (check_win() == 1)
printf("\nPlayer 1 wins!\n");
else
printf("\nPlayer 2 wins!\n");
return 0;
}
```
如果你有任何问题或者需要进一步解释,请随时告诉我。现在,以下是几个相关问题:
阅读全文