我的代碼如下,其中大部分可能沒有幫助,但也許問題出在我認爲的地方之外。這就是說,請首先閱讀以下內容,因爲它會給出我的代碼的簡要說明,並指出我認爲問題在哪裏。C:比較兩個不能產生正確結果的元素?
我想用C創建一個戰艦遊戲。我首先創建兩個二維數組,一個代表玩家的棋盤,另一個代表敵方的棋盤。我用兩段時間填滿他們。我用兩邊的數字將它們打印出來,使事物看起來很漂亮(使用我的initialPrintBoards函數)。然後我通過用's'替換敵人陣列中的某些時段來設置敵方船隻的位置,並將其打印出來以確保它們在我想要的位置。他們是,這很棒。然後我讓玩家在敵人的船上「開火」。這是通過用'x'(代表命中)或替換''來替換敵人陣列中的's'來完成的。 'o'(代表未命中)。我打印出來,一切正常。
現在,這裏是我遇到問題的地方。到目前爲止,爲了測試,敵人的艦船通過我的打印方法已經完全可見。我不想那樣。所以,我想我會做的是創建一個新的打印功能(稱爲printBoards),完全符合我以前的打印功能,除了打印「。」。當它遇到'作爲敵人陣列中的一個元素時。我最初的想法是使用比較。基本上,如果存儲在敵人陣列中任何位置的元素都打印'。',否則打印存儲在陣列中該位置的內容(即'。','x'或'o' )。不幸的是,即使在數組中的某個位置存儲了「x」或「o」,所有操作都會打印所有時段。我對此感到不知所措。我對C很陌生(過去我學習過Java),所以也許在C中有一些我不瞭解的比較。但是,這是假設問題是與比較,它可能不是。
任何幫助或提示將不勝感激。
#include <stdio.h>
char playerBoard[8][8];
char enemyBoard[8][8];
void fillBoards()
{
int a;
for (a = 0; a < 8; a++)
{
int b;
for (b = 0; b < 8; b++)
{
enemyBoard[a][b] = '.';
}
}
int x;
for (x = 0; x < 8; x++)
{
int y;
for (y = 0; y < 8; y++)
{
playerBoard[x][y] = '.';
}
}
}
void initialPrintBoards()//This is used before the enemy's ships are set.
{
printf("Enemy Board\n*12345678\n");
int a;
for (a = 0; a < 8; a++)
{
printf("%d", a + 1);
int b;
for (b = 0; b < 8; b++)
{
printf("%c", enemyBoard[a][b]);
}
printf("\n");
}
printf("\n");
printf("Player Board\n*12345678\n");
int x;
for (x = 0; x < 8; x++)
{
printf("%d", x + 1);
int y;
for (y = 0; y < 8; y++)
{
printf("%c", playerBoard[x][y]);
}
printf("\n");
}
printf("\n");
}
void printGreeting()
{
printf("\nWelcome to Battleship!\n\n");
}
void setEnemyShips()
{
// Ship 1.
enemyBoard[3][2] = 's';
enemyBoard[4][2] = 's';
enemyBoard[5][2] = 's';
// Ship 2.
enemyBoard[1][1] = 's';
enemyBoard[1][2] = 's';
enemyBoard[1][3] = 's';
// Ship 3.
enemyBoard[6][5] = 's';
enemyBoard[6][6] = 's';
enemyBoard[6][7] = 's';
}
void playerFire()
{
if (enemyBoard[2][2] == 's')
{
enemyBoard[2][2] = 'x';
}
else
{
enemyBoard[2][2] = 'o';
}
}
void printBoards()//This is used after the enemy's ships are set.
{
printf("Enemy Board\n*12345678\n");
int a;
for (a = 0; a < 8; a++)
{
printf("%d", a + 1);
int b;
for (b = 0; b < 8; b++)
{
if (enemyBoard[1][0] == 's')
{
printf("%c", '.');
}
else
{
printf("%c", enemyBoard[1][0]);
}
}
printf("\n");
}
printf("\n");
printf("Player Board\n*12345678\n");
int x;
for (x = 0; x < 8; x++)
{
printf("%d", x + 1);
int y;
for (y = 0; y < 8; y++)
{
printf("%c", playerBoard[x][y]);
}
printf("\n");
}
printf("\n");
}
int main()
{
fillBoards();
printGreeting();
initialPrintBoards(); //This will print the boards before the enemy's ships are set.
setEnemyShips();
initialPrintBoards(); //This will end up printing the enemy ships' locations. Need a different print method.
playerFire();
initialPrintBoards(); //This prints to see if a hit or miss is properly printed.
printBoards(); //This prints to see if the ships are hidden and a hit or miss is properly printed.
return 0;
}
您有:'如果(enemyBoard [1] [0] == 'S')'和'的printf( 「%C」,enemyBoard [1] [0]); '。也許這是一個打字錯誤/調試剩餘的,是不是應該包含'enemyBoard [a] [b]'? – nnn