Create a card guessing game using multiple classes. The goal of this game is to
ID: 3642363 • Letter: C
Question
Create a card guessing game using multiple classes.The goal of this game is to allow two players (in this case, a player and a computer) to each pick two cards at random, and count the total value of their cards. If the player has a higher total than the computer, the player wins.
If the computer has a higher total than the player or if their totals are even, the player loses. The game continues until the player chooses to quit.
This game consists of three main classes: CardGuessingGame, Player and Card. The Player class is used to instantiate Player objects, which keep track of a player
Explanation / Answer
please rate
import java.util.Random;
import java.util.Scanner;
class Player{
String name;
Card card1,card2;
Player(String name){
this.name = name;
card1 = null;
card2 = null;
}
public void acceptDeal(){
Random r = new Random();
int value = r.nextInt(13) + 1;
card1 = new Card(value);
value = r.nextInt(13) + 1;
card2 = new Card(value);
}
public int getHandStrength(){
int strength = card1.getValue() + card2.getValue();
return strength;
}
public String toString(){
String cards = new String();
cards = "Card 1: "+card1.getValue()+" Card 2: "+card2.getValue();
return cards;
}
}
class Card{
int value;
Card(int value){
this.value = value;
}
public int getValue(){
return value;
}
}
public class CardGuessingGame {
public static void main(String[] args){
boolean finished = false;
Scanner input = new Scanner(System.in);
System.out.println("Enter player name: ");
String name = input.next();
Player p1 = new Player(name);
Player computer = new Player("Computer");
while(!finished){
p1.acceptDeal();
computer.acceptDeal();
System.out.println("1. Show cards in hand 2. Winner 3. Exit");
int choice = input.nextInt();
switch(choice){
case 1:
System.out.println("Value of cards: "+p1.toString());
break;
case 2:
Player winner = p1.getHandStrength() > computer.getHandStrength() ? p1 : computer;
System.out.println("Winner is "+winner.name);
System.out.println("Your card values "+p1.toString()+" Computer card values "+computer.toString());
break;
case 3:
finished = true;
break;
default:
System.out.println("No such choice");
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.