How can I wait for a button press in a loop?

风流意气都作罢 提交于 2019-12-04 06:15:49

问题


Say I have simple program that emulates a board game with a number of players who take turns rolling dice to move across a board. The players can be human or computer.
If this was a command-line style game, I could simply make a loop to iterate over the players which would call the diceRoll function for that player.

If the player is a computer player, diceRoll simply tells the computer to roll the dice.
If the player is a human, the diceRoll will wait until a user inputs the roll command and then continues.

How can I transfer this idea to a graphic design? I don't think it makes sense to continuously check to see if the roll button has been pressed. I am working with actionscript 2, but ideas can be in whatever language you want. I'd just like some opinions on the best way to design this. I don't suppose there's some sort of 'waitForButtonPress' function that I don't know about?


回答1:


I think I've found a solution that I like. The main game class will have a nextTurn function like so:

nextTurn() {
   bool guiSet = false
   while (guiSet = false) {
      //Get the next player
      if (next player is human) {
         //enable the gui (ie. the 'Roll Dice' button)
         guiSet = true
      } else {
         //The player is a computer
         //Have the computer roll the dice and make any necessary decisions
      }
   }
}

When a human player is finished his turn, a call will be made to nextTurn to continue the game play. When a computer finishes a turn, the flow is still in the while loop so the game will continue.




回答2:


depending on the game if you have N turns and every other turn is the humans turn then you could simply call a getUserResponse() from within the loop using if elses..

for i to N
if(i%2==0)
getUserRoll()
else
getComputerRoll()

and if there's any contraints check them in the if conditon.



来源:https://stackoverflow.com/questions/1641209/how-can-i-wait-for-a-button-press-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!