[英]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.