到目前为止,我所拥有的程序已初始化并按预期方式打印棋盘。这是初始化和打印功能:
#include <stdio.h>
void initBoard(int n, int board[n][n]){
int i, j;
int numberOfRows = n/2 - 1;
for(i=0; i<numberOfRows; i++){
for(j=0; j<n; j++){
if((i%2==0&&j%2==0)||(i%2==1&&j%2==1)){
board[i][j] = 0;
}else{
board[i][j] = -1;
}
board[numberOfRows][j] = 0;
board[numberOfRows+1][j] = 0;
}
}
for(i=numberOfRows+2;i<n;i++){
for(j=0;j<n;j++){
if((i%2==0&&j%2==0)||(i%2==1&&j%2==1)){
board[i][j] = 0;
}else{
board[i][j] = 1;
}
}
}
}
void printBoard(int n, int board[n][n]){
int i, j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(board[i][j]==0){
board[i][j] = '-';
}else if(board[i][j]==1){
board[i][j] = 'W';
}else{
board[i][j] = 'D';
}
printf("%3c", board[i][j]);
}
printf("\n");
}
}
但是,应该在板上移动零件的 move 功能(提供的示例仅用于正确方向)的实现似乎不起作用。
void move(int n, int board[n][n], int x, int y, char direction){
if(direction!='R'||direction!='L'){
printf("\nYou can move only to right or left.\n\n");
}else if(direction=='R'){
if(x==n-1){
printf("You cannot move the piece to the right because you are already in a right corner of the board.\n");
}else{
if(board[y][x]==0){
printf("There is no piece in the column %i and row %i.\n", x, y);
}else if(board[y][x]==1){
if(y==0){
printf("You are on the kings row! Further move cannot be made.\n");
}else{
if(board[n-2-y][x+1]!=0){
printf("You cannot move in the following direction because there is already a piece in that cell.\n");
}else{
board[n-1-y][x] = 0;
board[n-2-y][x+1] = 1;
}
}
}else{
if(y==n-1){
printf("You are on the kings row! Further move cannot be made.\n");
}else{
if(board[n-y][x+1]!=0){
printf("You cannot move in the following direction because there is already a piece in that cell.\n");
}else{
board[n-1-y][x] = 0;
board[n-y][x+1] = -1;
}
}
}
}
}
测试之后,这里是测试:
int main(){
int size = 8;
int board[size][size];
initBoard(size, board);
printBoard(size, board);
move(size, board, 2, 2, 'R');
printBoard(size, board);
return 0;
}
...它显示在控制台中:
- D - D - D - D //this board is printed w/o any move function.
D - D - D - D -
- D - D - D - D
- - - - - - - -
- - - - - - - -
W - W - W - W -
- W - W - W - W
W - W - W - W -
You can move only to right or left.
D D D D D D D D //this is what happened when move function was called.
D D D D D D D D
D D D D D D D D
D D D D D D D D
D D D D D D D D
D D D D D D D D
D D D D D D D D
D D D D D D D D
答案 0 :(得分:0)
第一次调用printBoard
会用字符board
覆盖'D', 'W', '-'
的内容。
move
根本对董事会没有任何作用,因为您的测试if(direction!='R'||direction!='L')
始终为假。 (消息“您只能向右或向左移动”应该是提示。)您可能打算写if(direction!='R' && direction!='L')
。因此,这并不是您看到的全部{D
输出的原因。
因此,在第二次调用printBoard
时,数组board
仍然充满字符'D', 'W', '-'
。但是printBoard
期望它充满1,-1,0
。测试的编写方式,除那些值外,其他任何内容都落在最后的else
子句中,就像该值是-1
一样,并打印为D
。 / p>
您可能希望将printBoard
更改为非破坏性的,并且在将测试固定为可以实际运行后,可能需要对move
进行更多调试。我非常怀疑您的board[y]
和board[n-1-y]
混合索引。您需要确定y
是从面板顶部还是底部开始计算行数。
提醒:寻求帮助时,请始终发布完整的代码!在这种情况下,您首先猜测哪个函数包含该错误是完全错误的。有人可能会浪费大量时间徒劳地研究该代码。
另一个提示:除了在调试器中单步执行代码,观察board
的内容并查看其更改之处之外,我没有做任何聪明的事情。我建议您熟悉调试器,并使用它来尝试在 寻求互联网帮助之前了解代码的行为。 (并且当您询问时,报告您从调试会话中学到的知识。)