我用C ++写蛇,遇到了一些问题。我的printBoard方法只是打印游戏地图。它可以访问干净地图所在的数组。但是最重要的部分是它检查当前场的坐标是否与食物坐标或蛇的身体坐标之一相同。显然,如果他们不满意,它只会打印干净的字段。这里的问题是,我可以以某种方式将if语句从上一个循环内部连接到if and else外部。现在它的说法是没有先前的if语句?
void Board::printBoard(Player player1)
{
system("cls");
for(unsigned int i=0; i< BOARD_HEIGHT ; i++)
{
for(unsigned int j=0; j< BOARD_WIDTH; j++)
{
for(unsigned int z=0; z< player1._snakeBody.size(); z++)
{
if(j == player1._snakeBody.at(z).first && i == player1._snakeBody.at(z).second)
{
std::cout<< "S";
}
}
if(j ==_foodXcord && i == _foodYcord)
{
std::cout<< "X";
}
else
{
std::cout << this->_board[i][j];
}
}
std::cout << std::endl;
}
}
这是我所没有的,因为即使在其上找到SnakeBody,它也会打印空白字段。
答案 0 :(得分:1)
如果仅用适当的算法替换循环,则可以很容易地使用if-else语句:
for(unsigned int i=0; i< BOARD_HEIGHT ; i++)
{
for(unsigned int j=0; j< BOARD_WIDTH; j++)
{
if (std::any_of(std::begin(player1._snakeBody), std::end(player1._snakeBody),
[&](auto snake) { return snake == {j, i};
})
{
std::cout<< "S";
}
else if(j ==_foodXcord && i == _foodYcord)
{
std::cout<< "X";
}
else
{
std::cout << this->_board[i][j];
}
}
}
这避免了必须使用bool
标志,而for循环则需要使用。这样的优势还在于,只要在某个位置找到了主体,就可以将其破坏(您也可以在原始代码中使用break
语句来完成)。
答案 1 :(得分:0)
最简单的解决方案是仅跟踪是否已打印:
for(unsigned int j=0; j< BOARD_WIDTH; j++) {
bool havePrinted = false;
for(unsigned int z=0; z< player1._snakeBody.size(); z++) {
if(j == player1._snakeBody.at(z).first && i == player1._snakeBody.at(z).second) {
havePrinted = true;
std::cout<< "S";
}
}
if(j ==_foodXcord && i == _foodYcord && !havePrinted) {
std::cout<< "X";
havePrinted = true;
}
if (!havePrinted) {
std::cout << this->_board[i][j];
}
}
更复杂的解决方案可能涉及重新考虑您的数据结构,这样当您查找板上的某个位置时,便知道要打印什么。
答案 2 :(得分:0)
另一种替代方法是使用中间缓冲区:
void Board::printBoard(Player player1)
{
auto screen = this->_board; // assuming no C-array but std::vector or std::array
for (auto pos : player1._snakeBody) {
screen[pos.first][p.second] = 'S';
}
if (0 <= _foodYcord && _foodYcord < BOARD_HEIGHT
&& 0 <= _foodXcord && _foodXcord < BOARD_WIDTH) {
screen[_foodYcord][_foodXcord] = 'X';
}
system("cls");
for (unsigned int y = 0; y != BOARD_HEIGHT; ++y) {
for (unsigned int x = 0; x != BOARD_WIDTH; ++x) {
std::cout << screen[y][x];
}
std::cout << std::endl;
}
}