【发布时间】:2018-03-18 10:23:27
【问题描述】:
我正在控制台中编写战舰游戏,并且正在编写一个函数,该函数将基于二维数组绘制一个网格。我采取的方法是这样的:
--> Draw 1 row which contains a character X amount of times (like 10)
--> Draw that row, putting a newline at the end of the drawing process, 10 times to get a nice field.
现在,我确实需要在 1 行的末尾插入一个换行符,对吗?但是如何只比较数组的 x 元素而不比较 y 元素呢?
这是我的代码:
// Includes
#include <iostream> // For IO
#include <cstdlib> // For rand()
// Important game stuff
const int empty = 0; // Water
const int occupied = 1; // Ship
const int hit = 2; // Hit a ship
const int missed = 3; // Missed
// Variables
const int fields = 10;
// We want a 10x10 field
int board[fields][fields]; // board[x][y]
// Initialize board
void initb(int array[fields][fields]);
// Draw board x-axis
void drawbx(int array[fields][fields]);
int main(void)
{
drawbx(board;)
// game(Players);
return 0;
}
// Initialize the board, make everything hit
void initb(int array[fields][fields])
{
for(int x = 1; x <= 10; x++)
{
for(int y = 1; y <= 10; y++)
{
array[x][y] = hit;
}
}
}
void drawbx(int array[fields][fields])
{
for(int i = 1; i <= fields; i++)
{
if(array[i][] == empty || array[i][] == occupied)
{
if(i == 10)
std::cout << " X\n";
else if(i == 1)
std::cout << "X ";
else
std::cout << " X ";
}
}
}
具体看一下drawbx()函数。我想画类似的东西
X X X X X X X X X X\n
我尝试的语法if(array[i][] == empty || array[i][] == occupied) 不起作用。第二对方括号中必须有表达式。有人可以帮我吗?
【问题讨论】:
-
你不能。像
array[i][]这样的代码是非法的。您必须为两者提供索引。喜欢array[i][0]或array[i][1]。除此之外,请记住索引从 0 开始到 9。 -
我不清楚为什么
drawbx只能画一条线。但如果这就是你想要的,你应该这样做:void drawbx(int array[fields][fields], int row_to_draw),然后使用array[row_to_draw][i]。顺便说一句:考虑使用向量而不是数组 -
@4386427 非常感谢。我认为这将解决我的问题。只要回答它,我就可以将其标记为答案。
-
@4386427 我不想尝试一次绘制所有内容,因为这会使我的代码非常不可读。我宁愿控制一行的单个元素,然后打印该行 X 次。