• Home
  • Blog
  • Update the following War Game java program so that it uses an Array List?

Update the following War Game java program so that it uses an Array List?

0 comments

I have the following War Game. How do I update it so that the java program uses an Array List for n player and m decks. 

I have already written out the following methods:
Array List for CardPile which contains the makeFullDeck which takes as input int n. This makeFullDeck method should create a full deck which has n copies of every card and then shuffles it. 

The new War game using Array List should return an int representing which player won the game. 

The below program is my original War game(shown below) i wrote. How do i update this so that the program uses an ArrayList. The update can be in a class class MultiPlayerWar

import java.util.Scanner;

public class War 
{
public static void main(String[] args) 
{
Scanner reader = new Scanner(System.in);
String[] names = new String[2];
System.out.println(“What is player one’s name?”);
names[0] = reader.nextLine();
System.out.println(“What is player two’s name?”);
names[1] = reader.nextLine();

int winner = playGame();
System.out.println(“The winner was player ” + (1 + winner) + “. Congratulations to ” + names[winner] + ” on his/her hard earned victory!”);
}

//returns 0 if first player wins
//returns 1 if second player wins
public static int playGame() 
{
CardPile deck = CardPile.makeFullDeck();
CardPile p1 = new CardPile();
CardPile p2 = new CardPile();
while (!deck.isEmpty()) 
{
p1.addToBottom(deck.removeTopCard());
p2.addToBottom(deck.removeTopCard()); 
}

//now play the game
while ((!p1.isEmpty()) && (!p2.isEmpty()))
{
//check the top card, see which is better
int winner = compareTo(p1.peekTop(), p2.peekTop());

while (winner == 0)
{
//add the 2 cards to the deck and have a war
deck.addToBottom(p2.removeTopCard());
deck.addToBottom(p1.removeTopCard());

if (p1.isEmpty())
{
return 1;
}

if (p2.isEmpty())
{
return 0; 
}

winner = compareTo(p1.peekTop(), p2.peekTop());
}

deck.addToBottom(p1.removeTopCard());
deck.addToBottom(p2.removeTopCard());
//introduce randomness to avoid games going on forever (in real life you would “randomly” put cards back this way
deck.shuffle();
//now add entire card pile to winner’s hand
if (winner > 0) 
{
p1.takeFromPile(deck);
}
else
{
p2.takeFromPile(deck); 
}
}

if (p1.isEmpty())
{
return 1;
}

//else p2 must be empty or else the previous while loop would not have completed
return 0; 
}

//returns -1 if card 1 is less than card 2,
//returns 0 if values are equal
//returns 1 if card 1 is greater than card 2
public static int compareTo(Card card1, Card card2) 
{
if (card1.getValue().ordinal() < card2.getValue().ordinal())
{
return -1; 
}
else if (card1.getValue().ordinal() == card2.getValue().ordinal())
{
return 0;
}
else
{
return 1; 
}
}
}

About the Author

Follow me


{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}