Building card game need same cards to match in value - java

I am building a war card game for an assignment I have the game built and it is working but I am running into the issue such as card 10 jack of spades is less in value as say card 23 the jack of hearts. Looking for advice about the best way to be able to compare the cards to see if they are equal.
Below is the code I have so far:
import java.util.Random;
import java.util.Scanner;
public class WarGame {
public static void main(String a[]) {
DeckOfCards d = new DeckOfCards();
int input = 0;
int computer = 0;
int you = 0;
Scanner sc = new Scanner(System.in);
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
while (input != 2) {
if (input == 1) {
System.out.print("\n\nEnter the value of the card:");
int card = sc.nextInt();
if (card >= 0 && card <= 51) {
int systemCard = d.computerTurn(card);
System.out.println("Your card - " + d.inputCard(card));
System.out.println("Computer card - " + d.inputCard(systemCard));
if(systemCard > card)
++computer;
else
++you;
System.out.println("The winner is " + (systemCard > card ? "Computer" : "You"));
} else {
System.out.println("Invalid card");
}
}
else {
System.out.println("That is an invalid selection please choose 1 or 2.");
}
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
}
System.out.println("Total Wins by Computer: "+ computer);
System.out.println("Total Wins by You: "+ you);
if (computer > you)
System.out.println("Computer is the champion");
else if (computer == you)
System.out.println("Its a Tie");
else
System.out.println("You are the champion");
}
}
class DeckOfCards {
String suits[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
Random ran = new Random();
int systemWin = 0;
int playerWin = 0;
String inputCard(int card) {
int suit = card / 13; //assigning suit to your card
int rank = card % 13; //Assigning rank to your card
String out = "";
switch (rank) { //Setting up face cards for the cases
case 0:
out = "Ace of " + suits[suit];
break;
case 10:
out = "Jack of " + suits[suit];
break;
case 11:
out = "Queen of " + suits[suit];
break;
case 12:
out = "King of " + suits[suit];
break;
default:
out = rank + 1 + " of " + suits[suit]; //Adding one to remainder so it will go from 2-10 instead of 1-9
break;
}
return out;
}
int computerTurn(int playerRank) { //Keeping track of the wins for computer and player
int systemRank = this.ran.nextInt(51);
if (systemRank > playerRank)
systemWin++;
else
playerWin++;
return systemRank;
}
}

I think you're comparing the index to your deck rather than the card values themselves. If I'm understanding, you want to compare d.inputCard(card) with d.inputCard(systemCard) instead of card with systemCard. But of course, that's a String. Having a hard time following the code :-).

Related

Java Slot Machine Slot Comparison Trouble

I've been working on a slot machine program for class and have been having trouble figuring out how to compare the different "slots" on the machine to determine whether or not there are matches and tell the program how to proceed with calculate winnings. I originally thought of storing each result of my random number generator in a variable and then comparing them but am unsure of how to do this. I am unable to use arrays or lists or anything like that unfortunately. Thanks in advance and sorry if my code looks sloppy.
import java.util.*;
//Start Program
public class Slots
{
public static void main(String[] args)
{ //Start Main
//=====Declare Variables=====
int pool = 0,
won = 0,
slot_disp = 0,
slot0 = 0,
slot1 = 0,
slot2 = 0,
slot3 = 0,
slot4 = 0,
matches = 0,
bet = 0;
boolean again = true;
String msg = "",
ans = "";
Scanner key = new Scanner(System.in);
//=====Welcome and Start=====
System.out.println("\t* * * Welcome to SLOTS * * *");
System.out.print("\nEnter amount of money to play: ");
pool = key.nextInt();
while(again)
{
System.out.print("\nEnter your bet: ");
bet = key.nextInt();
while(bet < 0 || bet > pool)//-----Bet Validation-----
{
System.out.println("\tInvalid bet of : " + (double)bet);
System.out.println("\tFunds available: " + (double)pool);
System.out.print("\tRe-Enter bet : ");
bet = key.nextInt();
}
System.out.print(" ");
for(int cntSlot = 0; cntSlot < 5; cntSlot++)
{
Random rand = new Random();
slot_disp = rand.nextInt(5);
//=====Converting Random Number into Slot Display=====
switch(slot)
{
case 0:
msg = "Cherries";
break;
case 1:
msg = "Oranges";
break;
case 2:
msg = "Plums";
break;
case 3:
msg = "Melons";
break;
case 4:
msg = "Bars";
break;
}
System.out.print(msg + " ");
}//-----End Slot Conversion Loop-----
//=====Comparing Slot Output to Determine Winnings=====
switch(matches)
{
case 2:
won = 0;
break;
case 3:
won = bet * 2;
break;
case 4:
won = bet * 3;
break;
case 5:
won = bet * 4;
break;
default:
won = 0;
}
(double)(pool = (pool - bet) + won);
//=====Displaying the Results=====
if(matches == 5)//-----Jackpot-----
{
System.out.println("\n\n * * * You hit the JACKPOT * * *");
System.out.println("You Won: " + won);
}
if(matches > 2 && match < 5)//-----Winner-----
System.out.println("\n\nYou WIN: " + won);
else
System.out.println("\n\n\nNo matches, sorry you lost.");
if(pool <= 0)//-----Game Over-----
{
System.out.println("\n> > > You ran out of money. < < < ");
System.out.println("\nRestart the game to play again");
again = false;
break;
}
else
System.out.println("\nAvailable money: " + (double)pool);
//=====Asking User if they want to Continue=====
if(pool > 0)
{
System.out.print("\nWould you like to play again (y/n): ");
ans = key.next();
}
if(ans.equalsIgnoreCase("y"))
again = true;
else
again = false;
}
System.out.println("Game over, cash out: " + (double)pool);
System.out.println("\nThanks for playing the Slots!");
} //End Main
}
Use an int[] hits = new int[5]; array to store for each value how often it was selected. in the loop increment hits(slot) += 1;. Later, loop over the array to find the maximum.

Java - finding the winner between 4 players using getter (War card game) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi there I am trying to get this to calculate the winner from 4 players (The game is the classic card game war) but I can only get it to do two. the first bit of the code is my Card class and the second bit is the main program where there are more if statements for working out the winner. the issue i'm having is with the method "getWinner". I have included the deck class also if that is needed (at the bottom).
package warcard;
public class Card
{
private int value, suit;
private String result, suitStr;
/**
* #param num represents value of card
* #param type represents the suit of card
*/
public Card(int num, int type)
{
/**
* Class constructor.
*/
value = num;
suit = type;
switch(value)
{
case 1: result = "Ace";
break;
case 2: result = "Two";
break;
case 3: result = "Three";
break;
case 4: result = "Four";
break;
case 5: result = "Five";
break;
case 6: result = "Six";
break;
case 7: result = "Seven";
break;
case 8: result = "Eight";
break;
case 9: result = "Nine";
break;
case 10: result = "Ten";
break;
case 11: result = "Jack";
break;
case 12: result = "Queen";
break;
case 13: result = "King";
break;
default: result = "";
break;
}
switch(suit)
{
case 1: suitStr = "Clubs";
break;
case 2: suitStr = "Diamonds";
break;
case 3: suitStr = "Hearts";
break;
case 4: suitStr = "Spades";
break;
}
}
/**
* getters
*/
public int getNum()
{
return value;
}
public int getSuit()
{
return suit;
}
/**
* setters
*/
public void setVal(int choice)
{
value = choice;
}
public void setSuit(int choice)
{
suit = choice;
}
/**
* #param play represents Cards object
* #return flag the String result of the game
*/
public String getWinner(Card play)
{
String flag = "";
if(value == play.getNum())
{
if(suit > play.getSuit())
flag = "win";
else if (suit == play.getSuit())
flag = "tie";
else
flag = "lose";
}
else if (value > play.getNum())
flag = "win";
else
flag = "lose";
return flag;
}
/**
* toString method
*/
public String toString()
{
String info = "";
info = info + result + " of " + suitStr;
return info;
}
} /** end Cards class */
main program
package warcard;
public class Warcard
{
public static void main(String[] args)
{
// instantiation of 2 decks
Deck hand1, hand2, hand3, hand4;
hand1 = new Deck();
hand2 = new Deck();
hand3 = new Deck();
hand4 = new Deck();
String result = "";
// shuffle the decks
hand1.shuffle();
hand2.shuffle();
hand3.shuffle();
hand4.shuffle();
/** tracker variables
* wins1 tracks user's wins
* wins2 tracks computer's wins
*/
int count = 0;
int wins1 = 0;
int wins2 = 0;
int wins3 = 0;
int wins4 = 0;
int ties = 0;
for (int i= 0; i < 52; i++)
{
Card tester = hand1.getCard(count);
Card tester2 = hand2.getCard(count);
Card tester3 = hand3.getCard(count);
Card tester4 = hand4.getCard(count);
count++;
System.out.println("Player 1's hand: " + tester);
System.out.println("Player 2's hand: " + tester2);
System.out.println("Player 3's hand: " + tester3);
System.out.println("Player 4's hand: " + tester4);
result = tester.getWinner(tester2);
if(result == "win")
{
System.out.println("Win!");
wins1++;
}
else if(result == "tie")
{
System.out.println("Tie!");
ties++;
}
else
{
System.out.println("Lose!");
wins2++;
}
} // end for loop
System.out.println();
System.out.println("Total score:");
System.out.println();
System.out.println("Player 1's wins: " + wins1 + "\n" + "Player 2's wins: " + wins2 + "\n" + "Player 3's wins: " + wins3 + "\n" + "Player 4's wins: " + wins4 + "\n" + "Ties: " + ties);
if (wins1 > wins2 && wins1 > wins3 && wins1 > wins4)
System.out.println("Player 1 won the game!");
else if(wins2 > wins1 && wins2 > wins3 && wins2 > wins4)
System.out.println("Player 2 wins!");
else if(wins3 > wins1 && wins3 > wins2 && wins3 > wins4)
System.out.println("Player 3 wins!");
else if(wins4 > wins1 && wins4 > wins2 && wins4 > wins3)
System.out.println("Player 4 wins!");
else if(wins1 == wins2 && wins1 == wins3 && wins1 == wins4)
System.out.println("It's a tie!");
} // end main
} // end class
Deck class
package warcard;
import java.util.Random;
public class Deck
{
private Card[] deck;
private int[] suit = {1, 2, 3, 4};
private int[] numbers = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
private int count;
public Deck()
{
deck = new Card[52];
count = 0;
for(int i = 0; i <= 3; i++)
{
for(int k = 2; k <= 14; k++)
{
deck[count] = new Card(k, suit[i]);
count++;
}
} /**
* end outer loop
*/
}
/**
* end constructor
*/
public Card getCard(int index)
{
return deck[index];
}
public void shuffle()
{
int rand;
Random mix = new Random();
for (int i = 0; i < deck.length; i++)
{
/**
* shuffles deck
*/
rand = mix.nextInt(deck.length);
Card temp = deck[i];
deck[i] = deck[rand];
deck[rand] = temp;
} /**
* end for loop
*/
}
} /** end DeckCards class */
Currently, you are only comparing the values of 2 cards; you're comparing tester against tester2, but do not include player 3 or player 4's cards. Not only that, you don't return which player has won. Instead, you only specify whether p1 has won or lost.
Your String getWinner(Card) method needs more parameters, so you can pass more cards into it. Compare against all the cards. It should also return which player has won:
public String getWinner(Card p2, Card p3, Card p4) {
//compare against ALL cards
//return which player won
}
You would then call this, passing in all opposing cards, not just tester2:
result = tester.getWinner(tester2, tester3, tester4);
Finally, you have to fix up your score keeper. Instead of checking for "win" or "lose", check for which player won:
/* could use a switch statement */
if(result == "p1") {
System.out.println("Player 1 wins!");
wins1++;
} else if(result == "p2") {
System.out.println("Player 2 wins!");
wins2++;
} else if(result == "p3") {
//...
}
If I were on a computer, I'd suggest a LOT more, such as encapsulating the "battle" somewhere else rather than within the first player's Card; I recommend posting to CodeReview once you are done. If you have any problems, let me know.
As far as I can see, only the tester-deck is playing against the tester2-deck. If thats not intended, the reason, only 2 of your 4 decks are "competitive" ist that only 2 of them do play, right?

how to output numbers as strings/names

I'm writing the code for a HiLo card game in which the player has to guess whether the next card drawn will be higher, lower or equal.
Although for the numbers 11, 12, 13 and 1, I'd like the output to be Jack, Queen, King and Ace.
I've worked out the program to point where it returns a random int between 0 and 13 (I'm still unaware as to how I would write the code to make it only choose random int between 1 and 13).
How do I set it so the 11, 12, 13 and 1 numbers appear as
The Card pulled is the Ace,
is the next card Higher, Lower or Equal?
and so on, I've tried if statements and changing int to String, but neither work, and to my avail was nothing I was able to find about a String generator...
Here is my code, any help would be greatly appreciated
import java.util.Random;
import javax.swing.JOptionPane;
public class HiLo {
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
public static final int ACE = 1;
public static void main(String[] args) {
int correctGuesses = 0;
Random generator = new Random();
int currentCard;
int nextCard = generator.nextInt( KING+1 );
while (correctGuesses < 4) {
currentCard = nextCard;
nextCard = generator.nextInt( KING+1 );
Object[] options = {"Higher",
"Lower",
"Equal"};
int Input = JOptionPane.showOptionDialog(null,
"The Card pulled is the " + currentCard +
" \nis the next card Higher, Lower or Equal?",
"HiLo Card Game",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if(nextCard > currentCard) {
switch(Input) {
case JOptionPane.YES_OPTION:
correctGuesses++;
break;
case JOptionPane.NO_OPTION:
case JOptionPane.CANCEL_OPTION:
correctGuesses = 0;
break;
}
} else if(nextCard < currentCard) {
switch(Input) {
case JOptionPane.NO_OPTION:
correctGuesses++;
break;
case JOptionPane.YES_OPTION:
case JOptionPane.CANCEL_OPTION:
correctGuesses = 0;
break;
}
} else {
switch(Input) {
case JOptionPane.CANCEL_OPTION:
correctGuesses++;
break;
case JOptionPane.YES_OPTION:
case JOptionPane.NO_OPTION:
correctGuesses = 0;
break;
}
}
}
JOptionPane.showMessageDialog(null,
"Congratulations, You guessed correctly 4 times,"
+ "\nthe Last Card was the " + nextCard + ", resart to play again" );
}
}
Change currentCard to a String. Then instead of
currentCard = nextCard;
do
currentCard = Integer.toString(nextCard);
Then you can do your if statements and assign the strings you need to for the output.
String getCardString(int card) {
String cardString = null;
switch (card) {
ACE:
cardString = "ace";
break;
KING:
cardString = "king";
break;
// same for queen and jack
DEFAULT:
cardString = Integer.toString(nextCard);
}
return cardString;
}
JOptionPane.showMessageDialog(null,
"Congratulations, You guessed correctly 4 times,"
+ "\nthe Last Card was the " + getCardString(nextCard) + ", resart to play again" );
For the random generator, you can generate between 0 and 12, then add 1:
nextCard = ACE + generator.nextInt(KING);

BlackJack java random.nextInt

public class BlackJack {
public static void main(String args[]) {
String input;
char reDo;
Scanner keyboard = new Scanner (System.in);
Random random = new Random();
int card1 = random.nextInt(10) + 1;
int card2 = random.nextInt(10) + 1;
int card = random.nextInt(10) + 1;
int total1 = card1 + card2;
int total2 = total1 + card;
System.out.print("First cards: " + card1 + ", " + card2 + "\n");
System.out.print("Total: " + total1 + "\n");
boolean loop = true;
while (loop) {
System.out.print("Do you want another card? (y/n): ");
input = keyboard.nextLine();
reDo = input.charAt(0);
if (reDo == 'y' || reDo == 'Y') {
System.out.print("Card: " + card + "\n");
System.out.print("Total: " + total2 + "\n");
} else if (reDo == 'n' || reDo == 'N') {
loop = false;
}
}
}
}
The output is as follows:
First cards: 8, 3
Total: 11
Do you want another card? (y/n): y
Card: 7
Total: 18
Do you want another card? (y/n): y
Card: 7
Total: 18
Do you want another card? (y/n): n
I want to be able to generate a new random card within the loop, display the recurring total, and stop the program. The issue I can't understand is how to use the random.nextInt tool and be able to reuse it more accessibly. Currently its stuck as card1, card2, card, total1, and total2. If I could make them so that I could access them more easily the program would be easier I think to write. The issue is that I can't understand how to repeat the random.nextInt within the while loop.
First put all the cards in a deck.
Then generate a random number between 0 and the number of cards in the deck.
If deck is an ArrayList (for example), you could do
import java.util.*;
public class Main
{
public static void main(String[] args)
{
List<Card> deck = new ArrayList<Card>();
deck.add(new Card(1));
deck.add(new Card(3));
deck.add(new Card(7));
deck.add(new Card(10));
Random randomGenerator = new Random();
System.out.println("Deck 1 tests");
// draw 3 cards:
for (int i = 0; i < 3; i++)
{
int randomCard = randomGenerator.nextInt(deck.size());
Card card = deck.remove(randomCard);
System.out.println("Removed a(n) "+card);
}
// you could also do
List<Card> deck2 = new ArrayList<Card>();
deck2.add(new Card(1));
deck2.add(new Card(7));
deck2.add(new Card(3));
deck2.add(new Card(10));
Collections.shuffle(deck2);
System.out.println("Deck 2 tests");
// draw 3 cards:
for (int i = 0; i < 3; i++)
{
Card card = deck2.remove(0);
System.out.println("Removed a(n) "+card);
}
}
}
class Card {
public Card(int i)
{
blackJackValue = i;
}
public int blackJackValue;
public String toString() {
return String.valueOf(blackJackValue);
}
}

Java War card game round

Whenever I run the code, if any of the players gets an ace, king, queen, or jack, I get the following error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Card.getCard(Card.java:19)
at Card.main(Card.java:37)
this is the code I have so far :
public class Card
{
String suit;
String rank;
int getCard;
int a;
int b;
int getSuit;
public Card(){
String [] xSuit = {"Clubs","Diamonds","Hearts","Spades"};
String [] xRank = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};
a = ((int)(Math.random() * 4));
b = ((int)(Math.random() * 13));
suit = xSuit[a];
rank = xRank[b];
}
int getCard(){
getCard = Integer.parseInt (rank);
return getCard;
}
int getSuit(){
getSuit = Integer.parseInt (suit);
return getSuit;
}
public static void main(String[] args)
{
Card player = new Card();
Card player2 = new Card();
System.out.println("WAR");
System.out.println("--------------");
System.out.println("You played the " + player.rank + " of " + player.suit);
System.out.println("Player 2 played the " + player2.rank + " of " + player2.suit);
if (player.getCard() > player2.getCard()){
System.out.println("You win!");
}
else if (player.getCard() < player2.getCard()){
System.out.println("Player 2 wins!");
}
else if (player.getCard() == player2.getCard()){
if(player.getSuit() > player2.getSuit()){
System.out.println("You win!");
}
else if(player.getSuit() < player2.getSuit()){
System.out.println("Player 2 wins!");
}
else{
System.out.println("There was a draw.");
}
}
}
}
Is there a way I could make it so it will say "Jack" and "Queen" without getting an error?
You're not able to pass non-numeric text into a parseInt() method call because it's not actually a number. Another way you could do it would be to try this instead:
String suit;
String rank;
int a;
int b;
int getCard;
int getSuit;
public Card(){
String [] xSuit = {"Clubs","Diamonds","Hearts","Spades"};
// xRank array removed because I don't think you need it anymore.
a = ((int)(Math.random() * 4));
b = ((int)(Math.random() * 13) + 1);
suit = xSuit[a];
switch(b) {
case 1:
rank = "Ace";
break;
case 11:
rank = "Jack";
break;
case 12:
rank = "Queen";
break;
case 13:
rank = "King";
break;
default:
rank = Integer.toString(a);
break;
}
}
int getCard(){
return b; // this will probably be unnecessary now, you'd probably also want a better name for this numeric card value...
}

Categories