Nadeem Jamali
Nadeem Jamali

Reputation: 1423

How to make awaiting java application for users events

I am working on a 4 player card game. One player is user, while others are computer players. I started a loop to get cards from each player. Computer players throw cards by selecting an appropriate card automatically, while user by clicking over card. But the problem is, loop don't wait for user to select.

Upvotes: 0

Views: 59

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234807

There are a couple of ways to approach this. One is to have the game logic be in a separate thread from the user interface. It would go through a loop like this:

while (!gameOver()) {
    getPlayerMoves();
    updateGameState();
    notifyUI();
}

The getPlayerMoves() method would block on each player (whether computer or human) until a move was available. The computer players could be implemented in the same thread, since they don't really block. The notifyUI() method would notify the UI thread that the game state has changed. A convenient way to do this is with a message queue.

The UI thread would simply listen for events and react to them. It would expect two kinds of events: notifications from the game logic thread (as above) and moves by (human) players. When it received a notification that the game state has changed, it would update the display and enable player moves. When it received a player move, it would disable additional moves by that player (since players shouldn't move twice per turn), send a notice to the game thread, and wait for another event. (If there is only one human player, then at this point the only possible event should be a game state change.)

If you're using Swing, there are several built-in classes that greatly simplify this kind of notification between threads. Take a look at the SwingWorker class to get started. If not, take a look at this thread for ways message between threads.

Upvotes: 1

dnuttle
dnuttle

Reputation: 3830

What you need is an event, and an event listener. The event would be generated by the user throwing a card. The event listeners would be assigned to the computer players; each listener would be "registered" to listen for events from the player. The Sun tutorial goes over this in detail, and it's fairly easy to understand:

http://download.oracle.com/javase/tutorial/uiswing/events/index.html

Upvotes: 0

Related Questions