用C语言写一个井字棋小游戏
时间: 2023-05-18 18:06:50 浏览: 90
好的,以下是一个简单的井字棋小游戏的 C 语言代码:
#include <stdio.h>
char board[3][3]; // 井字棋棋盘
void init_board() { // 初始化棋盘
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
}
void print_board() { // 打印棋盘
int i, j;
printf(" 1 2 3\n");
for (i = 0; i < 3; i++) {
printf("%d ", i + 1);
for (j = 0; j < 3; j++) {
printf("%c", board[i][j]);
if (j != 2) {
printf("|");
}
}
printf("\n");
if (i != 2) {
printf(" -----\n");
}
}
}
int check_win(char c) { // 检查是否有一方胜利
int i, j;
for (i = 0; i < 3; i++) {
if (board[i][0] == c && board[i][1] == c && board[i][2] == c) {
return 1;
}
if (board[0][i] == c && board[1][i] == c && board[2][i] == c) {
return 1;
}
}
if (board[0][0] == c && board[1][1] == c && board[2][2] == c) {
return 1;
}
if (board[0][2] == c && board[1][1] == c && board[2][0] == c) {
return 1;
}
return 0;
}
int main() {
int i, j, x, y, count = 0;
char player = 'X';
init_board();
while (1) {
print_board();
printf("Player %c's turn, please input the coordinate(x y): ", player);
scanf("%d %d", &x, &y);
if (x < 1 || x > 3 || y < 1 || y > 3) {
printf("Invalid coordinate, please input again.\n");
continue;
}
if (board[x - 1][y - 1] != ' ') {
printf("The coordinate has been occupied, please input again.\n");
continue;
}
board[x - 1][y - 1] = player;
count++;
if (check_win(player)) {
printf("Player %c wins!\n", player);
break;
}
if (count == 9) {
printf("Draw!\n");
break;
}
player = player == 'X' ? 'O' : 'X';
}
print_board();
return 0;
}
阅读全文