所以我正在制作一个游戏,我只是通过将我的OR更改为AND来解决我遇到的问题而且我不确定我理解为什么它的工作原理而不是逻辑||我以前在那里。
//while user doesn't press quit, hasn't crashed into a bomb or hasn't saved all bears the game continues
while (((!wantsToQuit(key)) && (hasLost == false)) && (bearsSaved !=3))
{
if (isArrowKey(key))
{
updateGameData(grid, bears, bombs, detonator, exit, key, message, bearsSaved, bombsActive, moves, hasLost); //move bear in that direction
updateGrid(grid, maze, bears, bombs, detonator, exit); //update grid information
}
else if (toupper(key) == CHEAT) //pressing c enables cheat mode; disables bombs and sets the users moves to 500
{
cheatMode(message, moves, cheatActive, bombsActive);
}
else
message = "INVALID KEY!"; //set 'Invalid key' message
paintGame(grid, message, bearsSaved, moves); //display game info, modified grid & messages
key = getKeyPress(); //display menu & read in next option
}
endProgram(); //display final message
return(0);
基本思想是用户必须通过引导他们穿过迷宫并避免炸弹来拯救3只熊。
我不明白为什么这个while循环有效:
玩家不想退出并且玩家没有丢失并且玩家没有保存所有3只熊。
相反:
玩家不想退出并且玩家没有丢失或者玩家没有保存所有3只熊。
对我来说,后者在逻辑上更有意义,因为人们会期望游戏继续运行,而他们不想退出并且没有丢失,或者如果他们没有全部保存熊的。
感谢您的澄清
答案 0 :(得分:1)
玩家不想退出并且玩家没有丢失或者玩家没有保存所有3只熊
在这种情况下,您的while循环条件如下所示:
while (((!wantsToQuit(key)) && (hasLost == false)) || (bearsSaved !=3))
让我们假设玩家不输了,而不想要退出游戏。现在,如果你的玩家节省3个熊,那么bearsSaved !=3
条件就会被伪造。但是,由于您使用||
,即使第二个语句被伪造,游戏也会继续,因为第一个语句仍然是 true 。这违背了你的逻辑,因为你想要:
然而,如果所有熊都被保存,那么游戏也会结束。
使用||
语句,您必须伪造两个条件(我将前2个括号内的条件作为一个主要条件),以便循环终止。
这就是为什么你现在使用的逻辑是有道理的;一旦用户获胜,AND条件就会被伪造,一旦一个AND条件被伪造,循环就会终止。