c语言400行井字棋源代码
时间: 2023-06-22 20:22:12 浏览: 88
Romberg,c语言源码tictactoe,c语言项目
以下是一个简单的 C 语言井字棋游戏的源代码,共计 400 行。请注意:这只是一个基本的例子,可能需要进一步完善和改进。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define BOARD_SIZE 3
#define EMPTY_CELL ' '
#define PLAYER_ONE_SYMBOL 'X'
#define PLAYER_TWO_SYMBOL 'O'
char board[BOARD_SIZE][BOARD_SIZE];
void init_board() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY_CELL;
}
}
}
void print_board() {
printf("\n");
printf(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%d ", i + 1);
}
printf("\n");
for (int i = 0; i < BOARD_SIZE; i++) {
printf("%d ", i + 1);
for (int j = 0; j < BOARD_SIZE; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int is_board_full() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY_CELL) {
return 0;
}
}
}
return 1;
}
int is_winner(char player_symbol) {
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][0] == player_symbol && board[i][1] == player_symbol && board[i][2] == player_symbol) {
return 1;
}
if (board[0][i] == player_symbol && board[1][i] == player_symbol && board[2][i] == player_symbol) {
return 1;
}
}
if (board[0][0] == player_symbol && board[1][1] == player_symbol && board[2][2] == player_symbol) {
return 1;
}
if (board[0][2] == player_symbol && board[1][1] == player_symbol && board[2][0] == player_symbol) {
return 1;
}
return 0;
}
void player_move(char player_symbol) {
int row, col;
printf("Player %c's turn:\n", player_symbol);
do {
printf("Enter row number (1-3): ");
scanf("%d", &row);
printf("Enter column number (1-3): ");
scanf("%d", &col);
} while (row < 1 || row > 3 || col < 1 || col > 3 || board[row - 1][col - 1] != EMPTY_CELL);
board[row - 1][col - 1] = player_symbol;
}
void computer_move(char player_symbol) {
int row, col;
printf("Computer's turn:\n");
do {
row = rand() % BOARD_SIZE;
col = rand() % BOARD_SIZE;
} while (board[row][col] != EMPTY_CELL);
board[row][col] = player_symbol;
}
int main() {
srand(time(NULL));
init_board();
print_board();
while (1) {
player_move(PLAYER_ONE_SYMBOL);
print_board();
if (is_winner(PLAYER_ONE_SYMBOL)) {
printf("Player %c wins!\n", PLAYER_ONE_SYMBOL);
break;
}
if (is_board_full()) {
printf("Game over: tie!\n");
break;
}
computer_move(PLAYER_TWO_SYMBOL);
print_board();
if (is_winner(PLAYER_TWO_SYMBOL)) {
printf("Computer wins!\n");
break;
}
if (is_board_full()) {
printf("Game over: tie!\n");
break;
}
}
return 0;
}
```
阅读全文