I’m working on a turn-based strategy game in Java (in the Android framework). Following the structure in Beginning Android Games, I have a render thread and a UI thread. The render thread repeatedly updates the world state and then redraws the world. When the user interacts with the screen, the GUI sends Actions to the world (Command pattern). Now I’m adding AI players, and here is my plan:
Each AI player will have an AI that runs on a separate thread.
When the world updates on an AI turn, it checks to see if there is a pending action. If so, it executes it. Then it asks the AI player for its next action.
The AI player will send the request for an action to the AI thread, and then return.
Eventually, the AI will come up with an action, and post it back to the World, which will see it on the next update.
Two questions:
1) Does this design seem sound?
2) How do I handle the communication to and from the AI thread? If I have the AI thread call world.queueAction(action), that seems like it would work, but if the render thread calls ai.chooseAction(world) that will run the action choosing on the render thread, which is not what I want.
I would have an ExecutorService for the AIs and add tasks to it for things you want it to perform. For the UI you can have a queue of things which have changed and may need to be re-drawn. I would be tempted to use a single thread for all AIs until you know this would help. Most Android devices only have 1-2 CPUs anyway.