我实际上是想在C中做一个简单的Tic Tac Toe游戏(经典..)。除了我的一个函数之外,一切都还可以:getPlayerInput。我把它放在这里:
#include <stdio.h>
#define N 3
void getPlayerInput(int player, int *row, int *col, char board[N][N]){
if(player==1){
printf("It is player %d turn, please choose an empty space: \n", player);
scanf("%d %d", row, col);
if((*row>=1) && (*row<=N) && (*col>=1) && (*col<=N) && (board[(*row-1)][(*col-1)] == '_')){
board[(*row-1)][(*col-1)]='O';
}
while((*row-1)<1 || (*row-1)>N || (*col-1)<1 || (*col-1)>N || (board[(*row-1)][(*col-1)] != '_')){
printf("This space is illegal, please choose another: \n");
scanf("%d %d", row, col);
if((*row>=1) && (*row<=N) && (*col>=1) && (*col<=N) && (board[(*row-1)][(*col-1)] == '_')){
board[(*row-1)][(*col-1)]='O';
}
}
}
if(player==2){
printf("It is player %d turn, please choose an empty space: \n", player);
scanf("%d %d", row, col);
if((*row>=1) && (*row<=N) && (*col>=1) && (*col<=N) && (board[(*row-1)][(*col-1)] == '_')){
board[(*row-1)][(*col-1)]='X';
}
while((*row-1)<1 || (*row-1)>N || (*col-1)<1 || (*col-1)>N || (board[(*row-1)][(*col-1)] != '_')){
printf("This space is illegal, please choose another: \n");
scanf("%d %d", row, col);
if((*row>=1) && (*row<=N) && (*col>=1) && (*col<=N) && (board[(*row-1)][(*col-1)] == '_')){
board[(*row-1)][(*col-1)]='X';
}
}
}
}
我的问题是“这个空间是非法的,请选择另一个”。我试着做了一段时间,但它不起作用..我不明白..
当玩家进入不良位置(离开网格或其他地方)时,他必须重新输入一个位置。
有什么想法解决这个问题吗?
先谢谢。
修改1:
void getPlayerInput(int player, int *row, int *col, char board[N][N]){
if((*row-1)<1 || (*row-1)>N || (*col-1)<1 || (*col-1)>N || (board[(*row-1)][(*col-1)] != '_')){
printf("This space is illegal, please choose another: \n");
scanf("%d %d", row, col);
}
if(player==1){
printf("It is player %d turn, please choose an empty space: \n", player);
scanf("%d %d", row, col);
if((*row>=1) && (*row<=N) && (*col>=1) && (*col<=N) && (board[(*row-1)][(*col-1)] == '_')){
board[(*row-1)][(*col-1)]='O';
}
}
if(player==2){
printf("It is player %d turn, please choose an empty space: \n", player);
scanf("%d %d", row, col);
if((*row>=1) && (*row<=N) && (*col>=1) && (*col<=N) && (board[(*row-1)][(*col-1)] == '_')){
board[(*row-1)][(*col-1)]='X';
}
}
}
答案 0 :(得分:1)
条件中存在“一次性”错误;假设您输入一个'合法'坐标,其中行为1.位置设置,但while
循环仍然输入,因为(*row-1)<1
为真;也许它应该是*row<1
,这是不正确的否定。也许坐标约定在某个时刻从0基础变为1基础。