当您的应用程序启动时,所有东西都在一个线程上运行,包括事件处理程序。在您完成设置并调用battle() 之后,该线程就坐在那里一圈又一圈地循环。它在循环中忙得不可开交,以至于它没有注意到有一个点击事件等待处理!
有几个选项:
- 重构你的代码。看起来基本结构是玩家移动,然后游戏移动。您可以完全删除此循环,而是
randomMove()
在每次处理玩家移动后调用。OnClickListener
在for中处理玩家的移动moveButton1
。这样,一切都发生在事件上。总体而言,这会更简单,并且可能是正确的做法。
- 对代码进行尽可能小的更改以使其正常工作。这可能意味着将 while 循环的内容拉入 a
Runnable
,您可以通过调用Handler.post
. 第一行调用checkDead
,如果为真则返回。最后一行重新安排了Runnable
. 中间是while循环的主体。这样做的效果是你的循环体运行,然后事件处理程序得到一个回合,然后你的循环体运行,然后事件处理程序运行。这可能是个坏主意。
- 在另一个线程中运行battle()。这可能是个坏主意。
Why are 2. and 3. bad ideas? On a mobile device, battery life is precious, and running a check to see if you need to do something over and over again will keep the CPU busy chewing up battery life. Much better to sit there idle until you need to do something - this is what option 1 achieves.
So if 2. and 3. are bad ideas, why mention them? Welllllll, 2. I mention because it's the closest thing I've got to an answer to the question you actually asked. I mention 3. because there's a sense in which your current code is a fairly clear embodiment of the game logic. You could rework it so it runs in a separate thread, and instead of nextMove() returning true, nextMove() waits until the player makes a move (this would involve semaphores or mutexes or promises). But this would be an explicitly multi-threaded program, and as such would be difficult to write correctly. I recommend you don't attempt it at this stage in your programming career - the most likely outcome is a program that stops and waits forever, or that corrupts its data structures, in a way that is exceedingly difficult to diagnose.