c语言代码战争类小游戏
时间: 2024-10-09 09:01:41 浏览: 18
在C语言中制作一个简单的代码战争(Tic Tac Toe)游戏,你可以创建一个二维数组来表示棋盘,然后利用循环、条件判断和用户输入来控制玩家A(X)和玩家B(O)的游戏进程。以下是一个基础版的简单实现:
```c
#include <stdio.h>
#define SIZE 3
char board[SIZE][SIZE] = { {' ', ' ', ' ' },
{' ', ' ', ' ' },
{' ', ' ', ' ' } };
void print_board() {
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int check_win(char player) {
// 检查行、列和对角线是否有连续的三个同字符
for(int i = 0; i < SIZE; i++) {
if(board[i][0] == player && board[i][1] == player && board[i][2] == player)
return 1;
if(board[0][i] == player && board[1][i] == player && board[2][i] == player)
return 1;
}
if(board[0][0] == player && board[1][1] == player && board[2][2] == player)
return 1;
if(board[0][2] == player && board[1][1] == player && board[2][0] == player)
return 1;
return 0;
}
int main() {
char player = 'X'; // 初始玩家为X
int turn = 1;
while(1) {
print_board();
int row, col;
printf("Player %c, enter row and column (0-2): ", player);
scanf("%d%d", &row, &col);
if(board[row][col] != ' ') {
printf("Invalid move! Try again.\n");
continue;
}
board[row][col] = player;
if(check_win(player)) {
printf("Player %c wins!\n", player);
break;
}
if(turn % 2 == 0) {
player = 'O'; // 如果是偶数轮,则切换到玩家B
} else {
player = 'X'; // 如果是奇数轮,则切换回玩家A
}
turn++;
}
return 0;
}
```
阅读全文