[英]Tic Tac Toe in C
对于作业,我需要在 Putty 中编写 C 中的 Tic Tac Toe 游戏。 我找不到程序有什么问题。 无论我输入什么,程序都会返回“Player X Won!”
谁能发现问题?
这是函数的代码
#include <stdio.h>
#include "tictac.h"
#define BOARD_SIZE 3 // size of the board
void print_theboard(char board[BOARD_SIZE][BOARD_SIZE]) {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
printf(" %c ", board[i][j]);
if (j < BOARD_SIZE - 1) {
printf("|");
}
}
printf("\n");
if (i < BOARD_SIZE - 1) {
printf("---+---+---\n");
}
}
}
int check_whowon(char board[BOARD_SIZE][BOARD_SIZE]) {
//Gewinn in den Reihen
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
return 1;
}
//Gewinn in den Spalten
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[0][j] == board[1][j] && board[1][j] == board[2][j])
return 1;
}
//Gewinn in den Diagonalen
if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
return 0;
if (board[0][2] == board[1][1] && board[1][1] == board[2][0])
return 1;
return 0;
}
~
这是.h文件的代码
void print_theboard();
int check_whowon();
int check_draw();
这是主要代码
#include <stdio.h>
#include "tictac.h"
#define BOARD_SIZE 3 // size of the boad
int main() {
char board[BOARD_SIZE][BOARD_SIZE];
int row, col, game_over = 0;
char player = 'X';
// initialize the board with empty spaces
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = ' ';
}
}
while (!game_over) {
// display the current status of the board
print_theboard(board);
printf("Player %c, enter the row and column (e.g. 0 2): ", player);
scanf("%d %d", &row, &col);
// validate the input
if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE) {
board[row][col] = player;
// check if the game is won or drawn
if (check_whowon(board)) {
printf("Player %c wins!\n", player);
game_over = 1;
}
else {
printf("Invalid input. Please try again.\n");
} if(player='X')
player='O';
else
player='X';
}
return 0;
}
}
无论我输入什么,程序都会返回“Player X Won!”
我猜这张支票很奇怪。 无论您在第一轮将令牌放在哪里,您仍然会有两行是空的。 由于您使用空格字符初始化您的电路板,因此您的行检查
board[i][0] == board[i][1] && board[i][1] == board[i][2]
将评估为
' ' == ' ' && ' ' == ' '
这是真的。 您应该另外检查行/列/对角线是否实际上有一个标记。
该板用空格初始化:
// initialize the board with empty spaces
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = ' ';
}
}
变量 player 初始化为 'X' 因为 X 先播放:
char player = 'X';
但是当第一次调用check_whowon(board) function 时,它会检查水平线、垂直线或对角线是否具有相同的字符(而不是它们是否特别具有“X”或“O”)。 因此,由于初始化了空格字符,它总是返回 true。
要解决此问题,请编辑 checkwhowon() function 以忽略空格字符或专门检查“X”和“O”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.