开发者

Calling (and returning from) activities in a game thread

I've written a turn-based game the allows a mixture of AI and human players. The order in which each player takes his turn will be different in each round. Currently it's working in a really non-Android-friendly manner, running through the AI in an activity's onCreate function. Obviously I want to change this so my idea is as follows -

From the main menu I'd like to create an activity which sets up a thread on which I'll run all game logic. The thread will cycle through the players, displaying the outcome of their go after each one. Each AI player will update its logic here. For a human player, though, it will need to create an activity as the player is able to change, view and update many details. How am I able to do this from a thread, and allow the thread to co开发者_运维问答ntinue processing the other players once the human has finished his activity?


Your game logic thread should keep a reference to the Activity (maybe by being a nested class of your Activity-derived class).

When your game logic needs to do anything with the UI at all it should use Activity.runOnUiThread() to do so. I'd suggest updating the state for all players first, and then calling runOnUiThread() just once per game tick.

If you need to startActivity() from the runnable you pass to runOnUiThread, that won't be a problem. You will need some synchronization to pass data gathered from the UI thread (e.g. player pressing a button to change something in the game) into the game thread.


You should take a look at implementing a service for the game logic. A service is like an activity with no UI component. You could then have AI threads and the player (through the UI thread) interact with the service. The AI thread(s) and the UI each also need info about the game state in order to do their jobs, so the service would need to support game state queries as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜