帮我一个C语言三子棋代码
时间: 2023-05-15 16:05:22 浏览: 64
以下是一个简单的 C 语言三子棋代码:
#include <stdio.h>
#include <stdlib.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]);
}
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 x, y, turn = 0;
char player = 'X';
init_board();
while (1) {
print_board();
printf("Player %c's turn. Enter row and column: ", player);
scanf("%d %d", &x, &y);
if (x < 1 || x > 3 || y < 1 || y > 3) {
printf("Invalid input. Try again.\n");
continue;
}
if (board[x-1][y-1] != ' ') {
printf("That spot is already taken. Try again.\n");
continue;
}
board[x-1][y-1] = player;
if (check_win(player)) {
printf("Player %c wins!\n", player);
break;
}
turn++;
if (turn == 9) {
printf("It's a tie!\n");
break;
}
player = (player == 'X') ? 'O' : 'X';
}
print_board();
return 0;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)