SlideShare a Scribd company logo
1 of 15
Download to read offline
Goal: Your goal in this assignment is to write a Java program that simulates this card game
and prints the sequence of played cards and the winner at the end, as shown above. Use
Dealer.java, GeneralPlayer.java, Main.java, Card.java, Table.java, and Deck.java, complete
CardPlayer.java and CardTable.java.
Given codes:
Dealer.java :
import java.util.Random;
/**
* This class represents a dealer who shuffles a deck of cards and
* distributes them to players.
*/
public class Dealer {
private Deck deck;
/**
* Creates a new Dealer object with the specified players and deck.
*
* @param players the array of CardPlayer objects to distribute the cards to
* @param deck the Deck object to shuffle and distribute
*/
public Dealer(CardPlayer[] players, Deck deck) {
this.deck = deck;
this.shuffle();
this.distribute(players, this.deck);
}
/**
* Distributes the cards in the deck to the specified players.
*
* @param players the array of CardPlayer objects to distribute the cards to
* @param deck the Deck object to distribute
*/
private void distribute(CardPlayer[] players, Deck deck) {
for (int cardCounter = 0; cardCounter < deck.cards.length; cardCounter += players.length) {
for (int playerCounter = 0; playerCounter < players.length; playerCounter++) {
players[playerCounter].addToHand(deck.cards[cardCounter + playerCounter]);
}
}
}
/**
* Shuffles the cards in the deck; it generates two random variables as the card
* index and swaps them.
*/
private void shuffle() {
Random randomNumber = new Random();
for (int card = 0; card < this.deck.cards.length; card++) {
swap(randomNumber.nextInt(deck.cards.length), randomNumber.nextInt(deck.cards.length));
}
}
/**
* Swaps the positions of two cards in the deck.
*
* @param random1 the index of the first card to swap
* @param random2 the index of the second card to swap
*/
private void swap(int random1, int random2) {
Card temp;
temp = this.deck.cards[random1];
this.deck.cards[random1] = this.deck.cards[random2];
this.deck.cards[random2] = temp;
}
/**
* Prints out the identifier of each card in the deck.
*/
public void showDeck() {
for (Card card : this.deck.cards) {
System.out.println(card.identifier);
}
}
}
GeneralPlayer.java:
/**
* An abstract class representing a general player.
*
* @param <T> the type of the value returned by the player's play method.
*/
public abstract class GeneralPlayer<T> {
/** The name of the player. */
public String name;
/**
* Creates a new GeneralPlayer with a default name.
*/
public GeneralPlayer() {
this.name = "General Player";
}
/**
* Creates a new GeneralPlayer with the given name.
*
* @param name the name of the player.
*/
public GeneralPlayer(String name) {
this.name = name;
}
/**
* Makes a move or takes an action, depending on the implementation.
*
* @return the result of the player's action or move.
*/
public abstract T play();
}
Card.java:
/**
* A class that represents a playing card with a rank and suit.
*/
public class Card {
/**
* The rank of the card which is a number from 1 to 13.
* Includes King, Queen, Jack, and Ace.
*/
private int rank;
/**
* The suit of the card which is a number from 1 to 4
* Can be clubs (), diamonds (), hearts () or spades ().
*/
private int suit;
/**
* The identifier of the card.
* It is a unique number assigned to each card based on its rank and suit.
* The identifier is calculated as suit * 100 + rank.
*/
public final int identifier;
/**
* Creates a new Card with the given suit and rank.
* It assigns the identifier as well
*
* @param suit The suit of the card.
* @param rank The rank of the card.
*/
public Card(int suit, int rank) {
this.suit = suit;
this.rank = rank;
this.identifier = suit * 100 + rank;
}
/**
* Gets the rank of the card.
*
* @return The rank of the card.
*/
public int getRank() {
return rank;
}
/**
* Sets the rank of the card.
*
* @param rank The new rank of the card.
*/
public void setRank(int rank) {
this.rank = rank;
}
/**
* Gets the suit of the card.
*
* @return The suit of the card.
*/
public int getSuit() {
return suit;
}
/**
* Sets the suit of the card.
*
* @param suit The new suit of the card.
*/
public void setSuit(int suit) {
this.suit = suit;
}
}
Table.java:
/**
* An interface representing a table where cards are played and players can
* occupy places.
*
* @param <T> the type of cards that can be added to the table.
* @param <E> the type of players that can occupy places on the table.
*/
public interface Table<T extends Card, E extends GeneralPlayer> {
/**
* The number of places on the table that players can put their cards.
*/
final int NUMBER_OF_PLACES = 4;
/**
* Adds a card to the table at the first available place.
*
* @param card the card to add to the table.
*/
public void addCardToPlace(T card);
/**
* Returns the identifiers of the cards on places 1, 2, 3, and 4 on the table
* (in that same order).
*
* @return an array of integers representing the identifiers of all cards placed on the table
*/
public int[] getPlaces();
/**
* Checks the places on the table to see if any player occupies a place and
* removes any cards that they played.
*
* @param player the player to check for occupying a place.
*/
public void checkPlaces(E player);
}
Main.java:
/**
* The Main class represents the entry point for the card game.
*/
public class Main {
/**
* The main method initializes the game and starts playing until there's a
* winner.
*
* @param args command line arguments.
*/
public static void main(String[] args) {
// Create a new deck of cards.
Deck deck = new Deck();
// Create two players and assign their names.
CardPlayer[] players = new CardPlayer[2];
players[0] = new CardPlayer("Player 1");
players[1] = new CardPlayer("Player 2");
// Create a dealer and assign the players and deck to it.
Dealer dealer = new Dealer(players, deck);
// Create a new table to place the cards on.
CardTable table = new CardTable();
// Set the first player's turn.
players[0].setTurn(true);
// Print headers for table places.
System.out.println(" CardTable Places ");
System.out.println("-------------------------");
System.out.println("| p1 | p2 | p3 | p4 |");
System.out.println("-------------------------");
int numItrs = 0; // keep track of how many iterations are played
// Play until there's a winner.
while (players[0].getHand().size() != 0 && players[1].getHand().size() != 0) {
if (players[0].isTurn()) {
// Player 1 plays a card.
table.addCardToPlace(players[0].play());
table.checkPlaces(players[0]);
// Set Player 2's turn.
players[1].setTurn(true);
} else if (players[1].isTurn()) {
// Player 2 plays a card.
table.addCardToPlace(players[1].play());
table.checkPlaces(players[1]);
// Set Player 1's turn.
players[0].setTurn(true);
}
numItrs++; // update number of iterations counter
// Show the cards on the table
System.out.printf("| %3d | %3d | %3d | %3d | n",
table.getPlaces()[0], table.getPlaces()[1], table.getPlaces()[2], table.getPlaces()[3]);
}
System.out.println("-------------------------");
System.out.println("End of game. Total #iterations = " + numItrs);
// Display each player's bank of cards:
for (CardPlayer player : players) {
System.out.println(player.bankToString());
}
// Display the winner of the game:
CardPlayer winner = players[0];
for (CardPlayer player : players) {
if (player.getPoints() > winner.getPoints()) {
winner = player;
}
}
System.out.println("The winner is: " + winner.name + " (Points: " + winner.getPoints() + ")");
}
}
Codes needed to be completed:
CardPlayer.java:
/**
* A class that represents a card player.
*
* For each card player instance, we should keep track of how many points
* they earned in the game so far, as well as whether it is their turn or not.
* Additionally, their hand and bank of cards should be stored in two
* separate ArrayLists of Card objects.
*
* <p>
* A player's points, turn, and hand of cards should all be declared
* private fields, whereas the bank of cards should be public, as follows:
* <p>
* <code>
* private int points;
*
* private boolean turn;
*
* private ArrayList&lt;Card&gt; hand = new ArrayList&lt;Card&gt;();
*
* public ArrayList&lt;Card&gt; bank = new ArrayList&lt;Card&gt;();
* </code>
* <p>
*
* Note that the Field Summary section below will only show you public fields,
* but you must declare all the fields described above in your implementation of
this class,
* including the private fields. You are free to create additional fields if deemed
necessary.
*
* @param <Card> the type of card used in the game
*/
// TODO: Create class CardPlayer.
CardTable.java :
/**
*
* This class represents a table where a game is being played.
*
* It implements the Table interface and is designed to work with Card and
* CardPlayer objects.
*
* <p>
* Each table instance must keep track of the cards that players place on the table
* during the game. The number of places available has a fixed size
(<code>NUMBER_OF_PLACES</code>),
* so we use a regular Java array to represent a CardTable's places field.
* Each entry in this places array contains
* the cards that were added to that place, which is a more dynamic structure (we
don't know
* in advance how many cards will be added to this place!).
* <p>
* Therefore, each place
* entry in this array will reference an ArrayList of Card objects.
* <p>
* Here is how to declare the array of ArrayLists field <code>places</code>:
*
* <p>
* <code>
* private ArrayList&lt;Card&gt;[] places = new
ArrayList[NUMBER_OF_PLACES];
* </code>
* <p>
*
* Note that the Field Summary section below will only show you public fields,
* but you must declare the required field places described above, which is
private.
* You are also free to create additional fields in your class implementation, if
deemed necessary.
*
*/
// TODO: Complete the implementation of class CardTable below according
// to the class documentation described here:
// https://www.cs.emory.edu/~nelsay2/cs171_s23/a2/doc/cs171a2/CardTable.html
public class CardTable { // TODO: Fix class declaration to implement Table
interface (see documentation)
// TODO: create all required instance variables (you can add more variables
if needed)
// TODO: basic, no-argument constructor initializes all table
// places to new ArrayLists of Card objects
// TODO: implement all required CardTable methods (you can add helper methods
if needed)
}
Requirement: Finish CardPlayer.java and CardTable.java without changing any other given
code, to successfully generate a game with Main.java.
Game description: In this assignment, you will be implementing a simple game of cards. The
game uses a standard 52-card deck; there are four suits and each suit has 13 ranks. For
simplicity, we use numbers to identify cards in this sssignment. Thus, we have suits 1,2, 3, and 4,
and rarks from 1 to 13 (inclusive). Fach card is identified by its suit number followed by its rank.
For example, card 102 refers to the card whose suit is 1 and rank is 02 . Therefore, we can use
the simple formula suit*100+rank to produce a card's identifier. Figure - below shows the
different entities involved in this game: a dealer who has a deck of cards, two players, and a table
with exactly four places where players can place their cards during the game. Each player has a
hand of cards that is private to them (i.e., not visible to anyone else), and a bank of cards
containing all cards they won during the game (visible to the public). Figure 1: An illustration of
the different entities involved in our card game. The game begins with the dealer shuffling the
deck then distributing (i.e., dealing) the cards to the two players. The players then take turns in
placing their cards on the table, one card a time, starting with place 1 (i.e., places [ 0 ] in our
array implementation), followed by place 2, etc., when a player places a card in place 4 , the next
player places their card in place 1 , and so on. The top card in each place on the table is visible to
everyone. Note: We use the term current place to indicate where the current player can place
their card. 1 When a player wants to play a card, there are two possible scenarios: 1. If there is
another visible card (in places other than the current place) whose rank is the same as the current
player's card rank, then the player takes that card from the table and adds both cards to their
bank. One point is added to the player's score. 2. If none of the visible cards (in places other than
the current place) have a rank that matches the current player's card rank, then this new card
becomes the top card in the current place on the table. No points are added to the player's score.
Then, the next player plays a card, and so on. The game continues until both players finish their
cards. We then count the number of pairs of matching cards they have collected in their banks,
and the winner is the player with more pairs (the most points). If there is a tie, then for simplicity
we can consider player 1 to be the winner (after all, this is just a simulation ;-). Sample Game:
Below is the output of a sample game (where all the rules are implemented correctly). We print
the content of all 4 table places in each iteration, with 1 indicating that no card is placed in that
position 2 Player 1 bank has 10 carda: 401 101402 302 109409404204412112 playar 2 bank has
4 carda: 208 308 106206

More Related Content

Similar to Goal- Your goal in this assignment is to write a Java program that sim.pdf

Complete in JavaCardApp.javapublic class CardApp { private.pdf
Complete in JavaCardApp.javapublic class CardApp {   private.pdfComplete in JavaCardApp.javapublic class CardApp {   private.pdf
Complete in JavaCardApp.javapublic class CardApp { private.pdf
MAYANKBANSAL1981
 
Thanks so much for your help. Review the GameService class. Noti.pdf
Thanks so much for your help. Review the GameService class. Noti.pdfThanks so much for your help. Review the GameService class. Noti.pdf
Thanks so much for your help. Review the GameService class. Noti.pdf
adwitanokiastore
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
asif1401
 
C++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfC++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdf
ezzi97
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
kavithaarp
 
#include deck.h .pdf
#include deck.h .pdf#include deck.h .pdf
#include deck.h .pdf
agarvalcollections16
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
contact41
 
DiceSimulatorProgram
DiceSimulatorProgramDiceSimulatorProgram
DiceSimulatorProgram
Amy Baxter
 

Similar to Goal- Your goal in this assignment is to write a Java program that sim.pdf (11)

Complete in JavaCardApp.javapublic class CardApp { private.pdf
Complete in JavaCardApp.javapublic class CardApp {   private.pdfComplete in JavaCardApp.javapublic class CardApp {   private.pdf
Complete in JavaCardApp.javapublic class CardApp { private.pdf
 
Thanks so much for your help. Review the GameService class. Noti.pdf
Thanks so much for your help. Review the GameService class. Noti.pdfThanks so much for your help. Review the GameService class. Noti.pdf
Thanks so much for your help. Review the GameService class. Noti.pdf
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
 
C++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfC++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdf
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
 
Card Games in C++
Card Games in C++Card Games in C++
Card Games in C++
 
#include deck.h .pdf
#include deck.h .pdf#include deck.h .pdf
#include deck.h .pdf
 
Code em Poker
Code em PokerCode em Poker
Code em Poker
 
AI For Texam Hold'em poker
AI For Texam Hold'em pokerAI For Texam Hold'em poker
AI For Texam Hold'em poker
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
 
DiceSimulatorProgram
DiceSimulatorProgramDiceSimulatorProgram
DiceSimulatorProgram
 

More from aaicommunication34

More from aaicommunication34 (20)

Government funding- The following table presents the budget (in milion.pdf
Government funding- The following table presents the budget (in milion.pdfGovernment funding- The following table presents the budget (in milion.pdf
Government funding- The following table presents the budget (in milion.pdf
 
Government programs during the New Deal revealed institutional racism.pdf
Government programs during the New Deal revealed institutional racism.pdfGovernment programs during the New Deal revealed institutional racism.pdf
Government programs during the New Deal revealed institutional racism.pdf
 
govering tw putilc aerica ham any polbeal nhiturise acpleatos gowh and.pdf
govering tw putilc aerica ham any polbeal nhiturise acpleatos gowh and.pdfgovering tw putilc aerica ham any polbeal nhiturise acpleatos gowh and.pdf
govering tw putilc aerica ham any polbeal nhiturise acpleatos gowh and.pdf
 
Googlet- has a built-in targeting mechanism with its circles- allowed.pdf
Googlet- has a built-in targeting mechanism with its circles- allowed.pdfGooglet- has a built-in targeting mechanism with its circles- allowed.pdf
Googlet- has a built-in targeting mechanism with its circles- allowed.pdf
 
Glucose uptake (nmolmg1h1).pdf
Glucose uptake (nmolmg1h1).pdfGlucose uptake (nmolmg1h1).pdf
Glucose uptake (nmolmg1h1).pdf
 
Good day- I'm posting this question again but not as a picture because.pdf
Good day- I'm posting this question again but not as a picture because.pdfGood day- I'm posting this question again but not as a picture because.pdf
Good day- I'm posting this question again but not as a picture because.pdf
 
Gone acpandage ostinging cell found in Cnidarians free-swimming or flo.pdf
Gone acpandage ostinging cell found in Cnidarians free-swimming or flo.pdfGone acpandage ostinging cell found in Cnidarians free-swimming or flo.pdf
Gone acpandage ostinging cell found in Cnidarians free-swimming or flo.pdf
 
Goal- Identify the tools and techniques to be used to scan for vulnera.pdf
Goal- Identify the tools and techniques to be used to scan for vulnera.pdfGoal- Identify the tools and techniques to be used to scan for vulnera.pdf
Goal- Identify the tools and techniques to be used to scan for vulnera.pdf
 
Glycolysis is the process by which is oxidized into The TCA cycle is t.pdf
Glycolysis is the process by which is oxidized into The TCA cycle is t.pdfGlycolysis is the process by which is oxidized into The TCA cycle is t.pdf
Glycolysis is the process by which is oxidized into The TCA cycle is t.pdf
 
Glycolysis- the TCA or Krebs Cycle- and the electron transport system.pdf
Glycolysis- the TCA or Krebs Cycle- and the electron transport system.pdfGlycolysis- the TCA or Krebs Cycle- and the electron transport system.pdf
Glycolysis- the TCA or Krebs Cycle- and the electron transport system.pdf
 
Given the probabilities of two independent events- P(A)-0-12P(B)-0-22.pdf
Given the probabilities of two independent events- P(A)-0-12P(B)-0-22.pdfGiven the probabilities of two independent events- P(A)-0-12P(B)-0-22.pdf
Given the probabilities of two independent events- P(A)-0-12P(B)-0-22.pdf
 
Given the header of a method public static String m1 (double num1- cha.pdf
Given the header of a method public static String m1 (double num1- cha.pdfGiven the header of a method public static String m1 (double num1- cha.pdf
Given the header of a method public static String m1 (double num1- cha.pdf
 
Given the utility function U(X-Y)-XY- Abby consumes X-4 and Y-9- her M.pdf
Given the utility function U(X-Y)-XY- Abby consumes X-4 and Y-9- her M.pdfGiven the utility function U(X-Y)-XY- Abby consumes X-4 and Y-9- her M.pdf
Given the utility function U(X-Y)-XY- Abby consumes X-4 and Y-9- her M.pdf
 
Given the utility function U(X-Y)-XY- Abby consumes X-2 and Y-7- her M.pdf
Given the utility function U(X-Y)-XY- Abby consumes X-2 and Y-7- her M.pdfGiven the utility function U(X-Y)-XY- Abby consumes X-2 and Y-7- her M.pdf
Given the utility function U(X-Y)-XY- Abby consumes X-2 and Y-7- her M.pdf
 
Globalisation is the process by which businesses develop international.pdf
Globalisation is the process by which businesses develop international.pdfGlobalisation is the process by which businesses develop international.pdf
Globalisation is the process by which businesses develop international.pdf
 
Gloria Chu- a general manager at the MotoX Corporation- wants all of h.pdf
Gloria Chu- a general manager at the MotoX Corporation- wants all of h.pdfGloria Chu- a general manager at the MotoX Corporation- wants all of h.pdf
Gloria Chu- a general manager at the MotoX Corporation- wants all of h.pdf
 
Globalization has led to a- increasing loyalty of customers for produc.pdf
Globalization has led to a- increasing loyalty of customers for produc.pdfGlobalization has led to a- increasing loyalty of customers for produc.pdf
Globalization has led to a- increasing loyalty of customers for produc.pdf
 
GKC- CPA expressed an adverse opinion on the operating effectiveness o.pdf
GKC- CPA expressed an adverse opinion on the operating effectiveness o.pdfGKC- CPA expressed an adverse opinion on the operating effectiveness o.pdf
GKC- CPA expressed an adverse opinion on the operating effectiveness o.pdf
 
Given the probability density function f(x)-2x-3 for 0x3- derive the e.pdf
Given the probability density function f(x)-2x-3 for 0x3- derive the e.pdfGiven the probability density function f(x)-2x-3 for 0x3- derive the e.pdf
Given the probability density function f(x)-2x-3 for 0x3- derive the e.pdf
 
HANDOUT 7-3 Filling in the Blanks Write letters in the blanks to compl.pdf
HANDOUT 7-3 Filling in the Blanks Write letters in the blanks to compl.pdfHANDOUT 7-3 Filling in the Blanks Write letters in the blanks to compl.pdf
HANDOUT 7-3 Filling in the Blanks Write letters in the blanks to compl.pdf
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Goal- Your goal in this assignment is to write a Java program that sim.pdf

  • 1. Goal: Your goal in this assignment is to write a Java program that simulates this card game and prints the sequence of played cards and the winner at the end, as shown above. Use Dealer.java, GeneralPlayer.java, Main.java, Card.java, Table.java, and Deck.java, complete CardPlayer.java and CardTable.java. Given codes: Dealer.java : import java.util.Random; /** * This class represents a dealer who shuffles a deck of cards and * distributes them to players. */ public class Dealer { private Deck deck; /** * Creates a new Dealer object with the specified players and deck. * * @param players the array of CardPlayer objects to distribute the cards to * @param deck the Deck object to shuffle and distribute */ public Dealer(CardPlayer[] players, Deck deck) { this.deck = deck; this.shuffle(); this.distribute(players, this.deck); } /**
  • 2. * Distributes the cards in the deck to the specified players. * * @param players the array of CardPlayer objects to distribute the cards to * @param deck the Deck object to distribute */ private void distribute(CardPlayer[] players, Deck deck) { for (int cardCounter = 0; cardCounter < deck.cards.length; cardCounter += players.length) { for (int playerCounter = 0; playerCounter < players.length; playerCounter++) { players[playerCounter].addToHand(deck.cards[cardCounter + playerCounter]); } } } /** * Shuffles the cards in the deck; it generates two random variables as the card * index and swaps them. */ private void shuffle() { Random randomNumber = new Random(); for (int card = 0; card < this.deck.cards.length; card++) { swap(randomNumber.nextInt(deck.cards.length), randomNumber.nextInt(deck.cards.length)); } } /**
  • 3. * Swaps the positions of two cards in the deck. * * @param random1 the index of the first card to swap * @param random2 the index of the second card to swap */ private void swap(int random1, int random2) { Card temp; temp = this.deck.cards[random1]; this.deck.cards[random1] = this.deck.cards[random2]; this.deck.cards[random2] = temp; } /** * Prints out the identifier of each card in the deck. */ public void showDeck() { for (Card card : this.deck.cards) { System.out.println(card.identifier); } } } GeneralPlayer.java: /** * An abstract class representing a general player.
  • 4. * * @param <T> the type of the value returned by the player's play method. */ public abstract class GeneralPlayer<T> { /** The name of the player. */ public String name; /** * Creates a new GeneralPlayer with a default name. */ public GeneralPlayer() { this.name = "General Player"; } /** * Creates a new GeneralPlayer with the given name. * * @param name the name of the player. */ public GeneralPlayer(String name) { this.name = name; } /** * Makes a move or takes an action, depending on the implementation. *
  • 5. * @return the result of the player's action or move. */ public abstract T play(); } Card.java: /** * A class that represents a playing card with a rank and suit. */ public class Card { /** * The rank of the card which is a number from 1 to 13. * Includes King, Queen, Jack, and Ace. */ private int rank; /** * The suit of the card which is a number from 1 to 4 * Can be clubs (), diamonds (), hearts () or spades (). */ private int suit; /** * The identifier of the card. * It is a unique number assigned to each card based on its rank and suit. * The identifier is calculated as suit * 100 + rank.
  • 6. */ public final int identifier; /** * Creates a new Card with the given suit and rank. * It assigns the identifier as well * * @param suit The suit of the card. * @param rank The rank of the card. */ public Card(int suit, int rank) { this.suit = suit; this.rank = rank; this.identifier = suit * 100 + rank; } /** * Gets the rank of the card. * * @return The rank of the card. */ public int getRank() { return rank; } /**
  • 7. * Sets the rank of the card. * * @param rank The new rank of the card. */ public void setRank(int rank) { this.rank = rank; } /** * Gets the suit of the card. * * @return The suit of the card. */ public int getSuit() { return suit; } /** * Sets the suit of the card. * * @param suit The new suit of the card. */ public void setSuit(int suit) { this.suit = suit; }
  • 8. } Table.java: /** * An interface representing a table where cards are played and players can * occupy places. * * @param <T> the type of cards that can be added to the table. * @param <E> the type of players that can occupy places on the table. */ public interface Table<T extends Card, E extends GeneralPlayer> { /** * The number of places on the table that players can put their cards. */ final int NUMBER_OF_PLACES = 4; /** * Adds a card to the table at the first available place. * * @param card the card to add to the table. */ public void addCardToPlace(T card); /** * Returns the identifiers of the cards on places 1, 2, 3, and 4 on the table * (in that same order).
  • 9. * * @return an array of integers representing the identifiers of all cards placed on the table */ public int[] getPlaces(); /** * Checks the places on the table to see if any player occupies a place and * removes any cards that they played. * * @param player the player to check for occupying a place. */ public void checkPlaces(E player); } Main.java: /** * The Main class represents the entry point for the card game. */ public class Main { /** * The main method initializes the game and starts playing until there's a * winner. * * @param args command line arguments. */
  • 10. public static void main(String[] args) { // Create a new deck of cards. Deck deck = new Deck(); // Create two players and assign their names. CardPlayer[] players = new CardPlayer[2]; players[0] = new CardPlayer("Player 1"); players[1] = new CardPlayer("Player 2"); // Create a dealer and assign the players and deck to it. Dealer dealer = new Dealer(players, deck); // Create a new table to place the cards on. CardTable table = new CardTable(); // Set the first player's turn. players[0].setTurn(true); // Print headers for table places. System.out.println(" CardTable Places "); System.out.println("-------------------------"); System.out.println("| p1 | p2 | p3 | p4 |"); System.out.println("-------------------------"); int numItrs = 0; // keep track of how many iterations are played // Play until there's a winner. while (players[0].getHand().size() != 0 && players[1].getHand().size() != 0) { if (players[0].isTurn()) { // Player 1 plays a card.
  • 11. table.addCardToPlace(players[0].play()); table.checkPlaces(players[0]); // Set Player 2's turn. players[1].setTurn(true); } else if (players[1].isTurn()) { // Player 2 plays a card. table.addCardToPlace(players[1].play()); table.checkPlaces(players[1]); // Set Player 1's turn. players[0].setTurn(true); } numItrs++; // update number of iterations counter // Show the cards on the table System.out.printf("| %3d | %3d | %3d | %3d | n", table.getPlaces()[0], table.getPlaces()[1], table.getPlaces()[2], table.getPlaces()[3]); } System.out.println("-------------------------"); System.out.println("End of game. Total #iterations = " + numItrs); // Display each player's bank of cards: for (CardPlayer player : players) { System.out.println(player.bankToString()); } // Display the winner of the game:
  • 12. CardPlayer winner = players[0]; for (CardPlayer player : players) { if (player.getPoints() > winner.getPoints()) { winner = player; } } System.out.println("The winner is: " + winner.name + " (Points: " + winner.getPoints() + ")"); } } Codes needed to be completed: CardPlayer.java: /** * A class that represents a card player. * * For each card player instance, we should keep track of how many points * they earned in the game so far, as well as whether it is their turn or not. * Additionally, their hand and bank of cards should be stored in two * separate ArrayLists of Card objects. * * <p> * A player's points, turn, and hand of cards should all be declared * private fields, whereas the bank of cards should be public, as follows: * <p> * <code> * private int points; * * private boolean turn; * * private ArrayList&lt;Card&gt; hand = new ArrayList&lt;Card&gt;(); * * public ArrayList&lt;Card&gt; bank = new ArrayList&lt;Card&gt;(); * </code> * <p> * * Note that the Field Summary section below will only show you public fields,
  • 13. * but you must declare all the fields described above in your implementation of this class, * including the private fields. You are free to create additional fields if deemed necessary. * * @param <Card> the type of card used in the game */ // TODO: Create class CardPlayer. CardTable.java : /** * * This class represents a table where a game is being played. * * It implements the Table interface and is designed to work with Card and * CardPlayer objects. * * <p> * Each table instance must keep track of the cards that players place on the table * during the game. The number of places available has a fixed size (<code>NUMBER_OF_PLACES</code>), * so we use a regular Java array to represent a CardTable's places field. * Each entry in this places array contains * the cards that were added to that place, which is a more dynamic structure (we don't know * in advance how many cards will be added to this place!). * <p> * Therefore, each place * entry in this array will reference an ArrayList of Card objects. * <p> * Here is how to declare the array of ArrayLists field <code>places</code>: * * <p> * <code> * private ArrayList&lt;Card&gt;[] places = new ArrayList[NUMBER_OF_PLACES]; * </code> * <p> * * Note that the Field Summary section below will only show you public fields, * but you must declare the required field places described above, which is private. * You are also free to create additional fields in your class implementation, if deemed necessary. *
  • 14. */ // TODO: Complete the implementation of class CardTable below according // to the class documentation described here: // https://www.cs.emory.edu/~nelsay2/cs171_s23/a2/doc/cs171a2/CardTable.html public class CardTable { // TODO: Fix class declaration to implement Table interface (see documentation) // TODO: create all required instance variables (you can add more variables if needed) // TODO: basic, no-argument constructor initializes all table // places to new ArrayLists of Card objects // TODO: implement all required CardTable methods (you can add helper methods if needed) } Requirement: Finish CardPlayer.java and CardTable.java without changing any other given code, to successfully generate a game with Main.java. Game description: In this assignment, you will be implementing a simple game of cards. The game uses a standard 52-card deck; there are four suits and each suit has 13 ranks. For simplicity, we use numbers to identify cards in this sssignment. Thus, we have suits 1,2, 3, and 4, and rarks from 1 to 13 (inclusive). Fach card is identified by its suit number followed by its rank. For example, card 102 refers to the card whose suit is 1 and rank is 02 . Therefore, we can use the simple formula suit*100+rank to produce a card's identifier. Figure - below shows the different entities involved in this game: a dealer who has a deck of cards, two players, and a table with exactly four places where players can place their cards during the game. Each player has a hand of cards that is private to them (i.e., not visible to anyone else), and a bank of cards containing all cards they won during the game (visible to the public). Figure 1: An illustration of the different entities involved in our card game. The game begins with the dealer shuffling the deck then distributing (i.e., dealing) the cards to the two players. The players then take turns in placing their cards on the table, one card a time, starting with place 1 (i.e., places [ 0 ] in our array implementation), followed by place 2, etc., when a player places a card in place 4 , the next player places their card in place 1 , and so on. The top card in each place on the table is visible to everyone. Note: We use the term current place to indicate where the current player can place their card. 1 When a player wants to play a card, there are two possible scenarios: 1. If there is another visible card (in places other than the current place) whose rank is the same as the current player's card rank, then the player takes that card from the table and adds both cards to their bank. One point is added to the player's score. 2. If none of the visible cards (in places other than the current place) have a rank that matches the current player's card rank, then this new card becomes the top card in the current place on the table. No points are added to the player's score. Then, the next player plays a card, and so on. The game continues until both players finish their cards. We then count the number of pairs of matching cards they have collected in their banks, and the winner is the player with more pairs (the most points). If there is a tie, then for simplicity we can consider player 1 to be the winner (after all, this is just a simulation ;-). Sample Game: Below is the output of a sample game (where all the rules are implemented correctly). We print the content of all 4 table places in each iteration, with 1 indicating that no card is placed in that
  • 15. position 2 Player 1 bank has 10 carda: 401 101402 302 109409404204412112 playar 2 bank has 4 carda: 208 308 106206