我想在国际象棋程序中移动骑士。出于这个原因,我在包括 main 在内的所有函数之上定义了这两个变量(currentRow
和)。currentColumn
(我这样做是因为我希望这些变量作为所有函数的全局变量)如下。因为当骑士移动时,它的位置会改变。这将是其下一步行动的输入。
我不明白的是,当我调试时,我看到这些变量在函数中发生了变化,但是一旦它退出函数,它们就会返回到它们的默认值(3 和 4)。
你能告诉我如何解决这个问题吗?提前致谢...
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int currentRow=3;
int currentColumn=4;
int main(void){
...
}
int checkIsEmptyandMoveAccordingly(int moveNumber, int currentRow, int currentColumn){
if (chessBoard[currentRow+vertical[moveNumber]][currentColumn+horizontal[moveNumber]]==0 && currentRow+vertical[moveNumber]>=0 && currentColumn+horizontal[moveNumber] >=0 ){ //if empty,move to new location
currentRow+=vertical[moveNumber];
currentColumn+=horizontal[moveNumber];
printf("Move randomised to: %d\n", moveNumber);
printf("Knight has moved to chessBoard[%d][%d].\n",currentRow,currentColumn);
count++;
printf("Move count is %d.\n",count);
chessBoard[currentRow][currentColumn]=1;
if(!checkIsAroundFUll()){
moveNumber=randomiseMovement();
return moveNumber;
}
else {
printf("ALL TARGET SPACES ARE VISITED BEFORE. KNIGHT CAN NOT MOVE\n PROGRAM WILL BE TERMINATED!!!\n");
return -1;
}
}
else if (chessBoard[currentRow+vertical[moveNumber]][currentColumn+horizontal[moveNumber]]==1) { //if not empty, randomise again
printf("Knight CAN NOT MOVE! Target SPACE IS OCCUPIED\n");
if(!checkIsAroundFUll()){
moveNumber=randomiseMovement();
return moveNumber;
}
else {
printf("ALL TARGET SPACES ARE VISITED BEFORE. KNIGHT CAN NOT MOVE\n PROGRAM WILL BE TERMINATED!!!");
return -1;
}
}
else {
printf("OUT OF BOUNDS!! CAN NOT MOVE. TRYING ANOTHER MOVEMENT");
if(!checkIsAroundFUll()){
moveNumber=randomiseMovement();
return moveNumber;
}
else {
printf("ALL TARGET SPACES ARE VISITED BEFORE. KNIGHT CAN NOT MOVE\n PROGRAM WILL BE TERMINATED!!!");
return -1;
}
}
}