OK, I just don't understand how threads work. I don't know how I'm supposed to wake up a -specific- thread.
I'm working on the implementation of a simple two-player card game. I have five classes: Card, CardDeck, Dealer, Player and CardGame.
First, I ask for keyboard input for two Strings representing the names of the two players. I make two Players based on those names, and make a new CardDeck.
The CardDeck contains an ArrayList of Cards, which are numbered 0-7. There are 4 cards with each number in the deck. The CardDeck is shuffled after its creation.
Then an instance of Dealer takes the top 8 cards off CardDeck and gives each player four of the cards.
Starting with player1, each player draws a card (now having five in their hand). The player's hand is printed out to the console and the player discards one of their cards, aiming to have four cards all with the same value (4 4 4 4, or 0 0 0 0). If player1 doesn't win at this point, player2 takes their turn and vice versa until one player wins.
CardGame acts as the 'main' class and sets everything in motion. It starts three threads (dealer, player1 and player2) and waits for Dealer to give the signal that the game is over, after which it just cleans up and terminates.
CardGame.java
Player represents a player and implements Runnable. Each instance has a name and a hand, and a boolean showing whether or not they have won. I also pass in CardDeck and the Scanner object representing the keyboard in order to take keyboard input within the class.
At the moment, the run() method does nothing. This is because I don't know how to implement the multithreading functionality into Player.
Player.java
The code for CardDeck might be necessary for the solution I'm asking for, so here it is. It's a simple ArrayList of instances of Card, and CardDeck contains the methods necessary for drawing cards from the top of the deck and discarding cards to the bottom of the deck.
CardDeck.java
Added the code for Dealer below. Dealer just represents the dealer and has one job: to deal four cards to each player at the beginning of the game. This code is inside its own class because I'm following the instructor (otherwise I'd just have deal() in CardGame).
Dealer pretty much runs the entire game once its thread is started. This is because I haven't figured out the multithreading part of the exercise yet. Preferably, at the very end of Dealer's run() method it would notify CardGame to let it know that the game has finished.
Dealer.java
What's the correct implementation for this? After starting the two Player threads, Player1 should go first immediately. When Player1's turn is done (and Player1 hasn't won yet), Player2 should be notified and Player1 should go to sleep and vice versa. And of course, when either Player1 or Player2 hasWon, the main() thread should keep going.
Any help would be greatly appreciated. I'm just having trouble grasping how this is supposed to work.
Bookmarks