【发布时间】:2023-03-28 15:19:02
【问题描述】:
我的代码如下,其中大部分可能没有帮助,但问题可能不在我认为的位置。话虽如此,请先阅读以下内容,因为它简要介绍了我的代码并说明了我认为问题所在。
我正在尝试用 C 创建一个 Battleship 游戏。我首先创建两个二维数组,一个代表玩家的棋盘,一个代表敌人的棋盘。我用句号填充它们。我用数字打印出来,让事情看起来不错(使用我的 initialPrintBoards 函数)。然后我通过用's'替换敌人数组中的一些句点来设置敌人船只的位置并将其打印出来以确保它们在我想要的位置。他们是,这很棒。然后我让玩家向敌舰“开火”。这是通过将敌人数组中的“s”替换为“x”(表示命中)或替换“.”来完成的。带有“o”(代表未命中)。我把它打印出来,一切正常。
现在,我遇到了问题。至此,为了测试,敌人的船只已经通过我的打印方法对玩家完全可见。我不想要那个。所以,我想我要做的是创建一个新的打印函数(称为 printBoards),它与我之前的打印函数完全一样,除了打印“。”当它遇到's'作为敌人数组中的一个元素时,它在棋盘上。我最初的想法是使用比较。基本上,如果存储在敌人数组中的元素是's',则打印'.',否则打印出存储在数组中该位置的元素(可能是'.'、'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;
}
【问题讨论】:
-
你有:
if (enemyBoard[1][0] == 's')和printf("%c", enemyBoard[1][0]);。也许这是一个错字/调试剩余,不应该包含enemyBoard[a][b]吗?
标签: c multidimensional-array comparison