用c语言写一个井字棋小游戏
时间: 2023-05-24 19:00:57 浏览: 97
用C语言编写的井字棋小游戏
5星 · 资源好评率100%
好的,以下是一个简单的井字棋小游戏的 C 语言代码:
```c
#include <stdio.h>
char board[3][3] = { {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '} };
void print_board()
{
printf("\n");
printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[1][0], board[1][1], board[1][2]);
printf("-----------\n");
printf(" %c | %c | %c\n", board[2][0], board[2][1], board[2][2]);
printf("\n");
}
int check_win()
{
int i;
for (i = 0; i < 3; i++) {
if ((board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') ||
(board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')) {
return 1;
}
}
if ((board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ') ||
(board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')) {
return 1;
}
return 0;
}
int main()
{
int i, j, turn = 0;
printf("Welcome to Tic Tac Toe in C!\n");
printf("Player 1 (X) - Player 2 (O)\n");
for (i = 0; i < 9; i++) {
print_board();
printf("Player %d's turn.\n", turn % 2 + 1);
printf("Enter row (0-2): ");
scanf("%d", &j);
printf("Enter column (0-2): ");
scanf("%d", &i);
if (board[i][j] != ' ') {
printf("That cell is already taken.\n");
turn--;
} else {
board[i][j] = turn % 2 ? 'O' : 'X';
}
if (check_win()) {
printf("Player %d wins!\n", turn % 2 + 1);
print_board();
return 0;
}
turn++;
}
printf("It's a tie!\n");
print_board();
return 0;
}
```
这个代码实现了一个简单的井字棋小游戏,首先打印出初始的空棋盘,然后轮流让两个玩家下棋。每次下棋时,程序会提示用户输入想要落子的行和列,如果该位置已经有棋子则会提示用户重新输入。在每次下棋之后,程序会检查是否有任何一方获胜,如果有则输出该玩家获胜的信息并结束游戏,否则游戏继续,直到棋盘填满为止,此时宣布平局并结束游戏。
希望这个代码可以对你有所帮助!
阅读全文