写一串c语言井字棋小代码
时间: 2023-06-06 19:07:00 浏览: 84
Sure, here is a sample C code for Tic Tac Toe game:
#include <stdio.h>
#define SIZE 3
#define EMPTY 0
#define PLAYERX 1
#define PLAYERO 2
int check_winner(int board[][SIZE]) {
int i, j, row_sum, col_sum, diagonal_sum;
// Check rows
for (i = 0; i < SIZE; i++) {
row_sum = 0;
for (j = 0; j < SIZE; j++)
row_sum += board[i][j];
if (row_sum == PLAYERX * SIZE)
return PLAYERX;
else if (row_sum == PLAYERO * SIZE)
return PLAYERO;
}
// Check columns
for (j = 0; j < SIZE; j++) {
col_sum = 0;
for (i = 0; i < SIZE; i++)
col_sum += board[i][j];
if (col_sum == PLAYERX * SIZE)
return PLAYERX;
else if (col_sum == PLAYERO * SIZE)
return PLAYERO;
}
// Check diagonals
diagonal_sum = 0;
for (i = 0; i < SIZE; i++)
diagonal_sum += board[i][i];
if (diagonal_sum == PLAYERX * SIZE)
return PLAYERX;
else if (diagonal_sum == PLAYERO * SIZE)
return PLAYERO;
diagonal_sum = 0;
for (i = 0, j = SIZE - 1; i < SIZE; i++, j--)
diagonal_sum += board[i][j];
if (diagonal_sum == PLAYERX * SIZE)
return PLAYERX;
else if (diagonal_sum == PLAYERO * SIZE)
return PLAYERO;
return EMPTY;
}
void print_board(int board[][SIZE]) {
int i, j;
printf("\n\n");
for (i = 0; i < SIZE; i++) {
printf("%3d ", i);
for (j = 0; j < SIZE; j++) {
switch (board[i][j]) {
case EMPTY: printf("| "); break;
case PLAYERX: printf("| X "); break;
case PLAYERO: printf("| O "); break;
}
}
printf("|\n");
}
printf(" 0 1 2\n\n");
}
int main() {
int board[SIZE][SIZE] = {0}, winner = EMPTY;
int row, col, player = PLAYERX;
printf("Welcome to Tic Tac Toe!\n\n");
print_board(board);
while (winner == EMPTY) {
printf("Player %d, enter row and column: ", player);
scanf("%d %d", &row, &col);
if (row >=0 && row < SIZE && col >= 0 && col < SIZE && board[row][col] == EMPTY) {
board[row][col] = player;
player = player == PLAYERX ? PLAYERO : PLAYERX;
print_board(board);
winner = check_winner(board);
} else {
printf("Invalid move, try again.\n");
}
}
printf("Congratulations, player %d! You won!\n", winner);
return 0;
}
阅读全文