【发布时间】:2021-01-18 02:45:59
【问题描述】:
我有一个简单的井字游戏程序,应该可以工作,但不能。我只做了一个获胜条件,即使我手动将所有空格设置为 x,似乎也没有满足。我已经尝试在 Visual Studio Code 中对其进行调试,但它并不总是有效,而且可能很烦人,它似乎没有调用该函数,我不确定为什么。
#include <stdio.h>
#include <stdbool.h>
// l l
// 0 l 1 l 2
// l l
// ***********************
// l l
// 3 l 4 l 5
// l l
// ***********************
// l l
// 6 l 7 l 8
// l l
char space[9] = {'p','p','p','p','p','p','p','p','p'};//p is just a placement value
unsigned int currentPlayer = 1;
bool winner = false;
int p1;
int p2;
int win();
int win(){
if(space[0] == 'x' && space[1] == 'x' && space[2] == 'x'){
printf("Player 1 wins");
winner = true;
}
}
int main(){
while(winner == false){//winenr becomes true when someone wins
//The Board//
printf(" l l \n %c l %c l %c \n l l \n***********************\n l l \n %c l %c l %c \n l l \n***********************\n l l \n %c l %c l %c \n l l \n\n",space[0], space[1], space[2], space[3], space[4], space[5], space[6], space[7], space[8]);
if(winner == false){
//Player 1's turn//
while(currentPlayer == 1 && winner == false){//to keep the loop going if they make a wrong move
win();//to refer back to the win function to see if win conditions are met
printf("Player 1:");
scanf("%d", &p1);
printf("\n\n\n\n");
if(space[p1] == 'x' || space[p1] == 'o'){//if the space is equal to either letter that means they need to input a new move
printf("That space is currently taken pick another space\n\n");
}
if(space[p1] != 'x' && space[p1] != 'o'){//if neither space is equal to a letter then you can put your move there
space[p1] = 'x';
currentPlayer = 2;
break;
}
else{
printf("invalid input\n\n");
}
}
while(currentPlayer == 2 && winner == false){//player 2's turn
printf("Player 2:");
scanf("%d", &p2);
printf("\n\n\n\n");
if(space[p2] == 'x' || space[p2] == 'o'){
printf("That space is currently taken pick another space\n\n");
}
if(space[p2] != 'x' || space[p2] != 'o'){
space[p2] = 'o';
currentPlayer = 1;
break; //changing the player
}
else{
printf("invalid input\n\n");
}
}
}
else{
break;
}
}
}
【问题讨论】:
-
出于某种原因#include
未包含在我的帖子中,但它在那里 -
另外,如果我在向网站提交此即时消息时做错了什么,我表示歉意,任何帮助或建议将不胜感激
-
带有三个反引号的行应该只包含语言名称(或
none)。它必须与实际代码分开。 -
你的函数
win()被定义为返回一个整数,但它实际上并没有返回任何东西。除非您遵守已有 30 多年历史且已过时 20 多年的原始 C90 标准,否则这应该会导致编译器警告。你应该让函数返回一个值——可能是winner——并且你应该在调用函数时检查返回值。如果有赢家,你应该打破循环。在我看来,您应该在每个球员比赛后检查获胜者。 (我不认为在win()函数中使用exit()是一个好的解决方案,因为它可以工作。) -
另外,由于这是 C 而不是 C++,声明
int win();没有声明函数的原型,因此您可以使用任意参数调用函数,编译器不会抱怨。您应该在声明中使用int win(void);,以及函数定义(对称性、一致性、可靠性)。
标签: c tic-tac-toe