帮我写一个#字棋与电脑对战的代码
时间: 2023-03-26 16:03:25 浏览: 91
好的,我可以为您提供一个#字棋与电脑对战的代码。以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 3
void print_board(char board[][SIZE]);
int check_win(char board[][SIZE], char player);
void player_move(char board[][SIZE], char player);
void computer_move(char board[][SIZE], char computer);
int main()
{
char board[SIZE][SIZE] = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
char player = 'X';
char computer = 'O';
int turn = ;
int winner = ;
srand(time(NULL));
printf("Welcome to # Tic Tac Toe!\n");
printf("You are playing as X, and the computer is playing as O.\n");
while (turn < SIZE * SIZE && winner == )
{
print_board(board);
if (turn % 2 == )
{
player_move(board, player);
winner = check_win(board, player);
}
else
{
computer_move(board, computer);
winner = check_win(board, computer);
}
turn++;
}
print_board(board);
if (winner == 1)
{
printf("Congratulations! You win!\n");
}
else if (winner == -1)
{
printf("Sorry, the computer wins.\n");
}
else
{
printf("It's a tie!\n");
}
return ;
}
void print_board(char board[][SIZE])
{
printf("\n");
printf(" %c | %c | %c \n", board[][], board[][1], board[][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n", board[1][], board[1][1], board[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n", board[2][], board[2][1], board[2][2]);
printf("\n");
}
int check_win(char board[][SIZE], char player)
{
int i, j;
int row, col, diag1, diag2;
for (i = ; i < SIZE; i++)
{
row = ;
col = ;
for (j = ; j < SIZE; j++)
{
if (board[i][j] == player)
{
row++;
}
if (board[j][i] == player)
{
col++;
}
}
if (row == SIZE || col == SIZE)
{
return 1;
}
}
diag1 = ;
diag2 = ;
for (i = ; i < SIZE; i++)
{
if (board[i][i] == player)
{
diag1++;
}
if (board[i][SIZE - 1 - i] == player)
{
diag2++;
}
}
if (diag1 == SIZE || diag2 == SIZE)
{
return 1;
}
return ;
}
void player_move(char board[][SIZE], char player)
{
int row, col;
printf("Enter row (1-3): ");
scanf("%d", &row);
printf("Enter column (1-3): ");
scanf("%d", &col);
while (board[row - 1][col - 1] != ' ')
{
printf("That spot is already taken. Please try again.\n");
printf("Enter row (1-3): ");
scanf("%d", &row);
printf("Enter column (1-3): ");
scanf("%d", &col);
}
board[row - 1][col - 1] = player;
}
void computer_move(char board[][SIZE], char computer)
{
int row, col;
printf("The computer is making its move...\n");
do
{
row = rand() % SIZE;
col = rand() % SIZE;
} while (board[row][col] != ' ');
board[row][col] = computer;
}
阅读全文