Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using Java, design a simple card game called War You are to design a simple card

ID: 3723907 • Letter: U

Question

Using Java, design a simple card game called War

You are to design a simple card game called War (see http://www.bicyclecards.com/how-to-play/war/ for a detailed description of the card game). In this game, there are two players who each get half the deck of cards (26 cards each). Players, at the same time, flip over the top card on their pile. The player who flips the higher value/rank card wins and gets both cards. The winning player adds both cards to their pile of cards. If b /rank, then a "War" starts. When "War" is declared both oth players flip over cards with the same value players put four cards into a separate pile and flip over the top card. The player who flips over the highest card wins the "War" pile. If the players both turn over the same card while at "War", you play War again (etc.). The game then resumes as normal (one card at a time). The game ends when one player runs out of cards. The winner has all the cards. You can play an online version of the game here https://cardgames.io/war/. You will have three Classes (Card, Deck and a Demo Class) Card Class You need to first create a Card Class. A Card object is made up of a suit (which are Hearts, Diamonds, Clubs, and Spades). Each suit has the same set of ranked cards: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace. And each card has a value (eg, you could make Ace=14. King= 13, Queen=12, Jack-11, then the numbered values e.g., "2" has a value of 2, "8" has a value of 8. The suit of the card doesn't matter in this game (that is only the rank and value of a card matter but you need to print out the suit in your output) The order of best to worst cards: Ace, King, Queen, Jack, 10, 9, 8,7, 6, 5, 4, 3, 2. Nothing beats an Ace and a 2 doesn't beat anything Demo Class (play the game) In your Demo class, you will ask two players for their names, create a deck of cards and shuffle them. Then you will "deal" the cards into two hands (give each player their own pile of cards) so that each player has 26 cards (that is each player will have their own ArrayList with their pile of cards). Then play the game. This is an automated game, meaning once you start the game, the cards in each players hand (pile) will automatically keep flipping until a winner is found Note, your display must be like the above. You can use the printf function to help you format strings so that the columns line up. See this source to help you format your printf: https://alvinalexander.com/programming/printf-format-cheat-sheet See the below sample output, for an example of how the game plays Welcome to WAR! Let's Play! Enter the first player's name: BOB Enter the second player's name: SUE BOB 2 Clubs 9 Clubs King Spades 6 Spades #Cards 26 25 24 25 SUE Jack Hearts Ace Clubs Jack Spades 6 Diamonds #Cards 26 27 28 27 Winner SUE SUE BOB WAR 4 Spades 25 6 Hearts 27 SUE 9 Hearts 20 10 Diamonds 32 SUE ... 5 Clubs Queen Spades 51 SUE SUE Wins! Congratulations Play again (y/n)? n

Explanation / Answer

JAVA PROGRAMME :

Deck.java

public class Deck {

public static void main(String[] args) {

String[] SUITS = {

"Clubs", "Diamonds", "Hearts", "Spades"

};

String[] RANKS = {

"2", "3", "4", "5", "6", "7", "8", "9", "10",

"Jack", "Queen", "King", "Ace"

};

// initialize deck

int n = SUITS.length * RANKS.length;

String[] deck = new String[n];

for (int i = 0; i < RANKS.length; i++) {

for (int j = 0; j < SUITS.length; j++) {

deck[SUITS.length*i + j] = RANKS[i] + " of " + SUITS[j];

}

}

// shuffle

for (int i = 0; i < n; i++) {

int r = i + (int) (Math.random() * (n-i));

String temp = deck[r];

deck[r] = deck[i];

deck[i] = temp;

}

// print shuffled deck

for (int i = 0; i < n; i++) {

System.out.println(deck[i]);

}

}

}

demo.java

package cards;

import java.net.URL;

import javax.swing.*;

////////////////////////////////////////////////////////////// class CardDemoGUI

class CardDemo1 extends JFrame {

//=================================================================== fields

private static Card[] _deck = new Card[52];

//===================================================================== main

public static void main(String[] args) {

CardDemo1 window = new CardDemo1();

window.setTitle("Card Demo 1");

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

window.setContentPane(new CardTable(_deck));

window.pack();

window.setLocationRelativeTo(null);

window.setVisible(true);

}

//============================================================== constructor

public CardDemo1() {

//... ClassLoader is where to get images from this .jar file.

ClassLoader cldr = this.getClass().getClassLoader();

int n = 0; // Which card.

int xPos = 0; // Where it should be placed initially.

int yPos = 0;

//... Read in the cards using particular file name conventions.

// Images for the backs and Jokers are ignored here.

String suits = "shdc";

String faces = "a23456789tjqk";

for (int suit=0; suit < suits.length(); suit++) {

for (int face=0; face < faces.length(); face++) {

//... Get the image from the images subdirectory.

String imagePath = "cards/images/" + faces.charAt(face) +

suits.charAt(suit) + ".gif";

URL imageURL = cldr.getResource(imagePath);

ImageIcon img = new ImageIcon(imageURL);

//... Create a card and add it to the deck.

Card card = new Card(img);

card.moveTo(xPos, yPos);

_deck[n] = card;

//... Update local vars for next card.

xPos += 5;

yPos += 4;

n++;

}

}

}

}

CardTable.java

package cards;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

////////////////////////////////////////////////////////////////////// CardTable

public class CardTable extends JComponent implements MouseListener,

MouseMotionListener {

//================================================================ constants

private static final Color BACKGROUND_COLOR = Color.GREEN;

private static final int TABLE_SIZE = 400; // Pixels.

//=================================================================== fields

//... Initial image coords.

private int _initX = 0; // x coord - set from drag

private int _initY = 0; // y coord - set from drag

//... Position in image of mouse press to make dragging look better.

private int _dragFromX = 0; // Displacement inside image of mouse press.

private int _dragFromY = 0;

private Card[] _deck; // Should really be in a model, but ...

private Card _currentCard = null; // Current selected card.

//============================================================== constructor

public CardTable(Card[] deck) {

_deck = deck; // Should be passed a model.

//... Initialize graphics

setPreferredSize(new Dimension(TABLE_SIZE, TABLE_SIZE));

setBackground(Color.blue);

//... Add mouse listeners.

addMouseListener(this);

addMouseMotionListener(this);

}

//=========================================================== paintComponent

@Override

public void paintComponent(Graphics g) {

//... Paint background

int width = getWidth();

int height = getHeight();

g.setColor(BACKGROUND_COLOR);

g.fillRect(0, 0, width, height);

//... Display the cards, starting with the first array element.

// The array order defines the z-axis depth.

for (Card c : _deck) {

c.draw(g, this);

}

}

//====================================================== method mousePressed

// Check to see if press is within any card.

// If it is,

// * Set _currentCard so mouseDragged knows what to drag.

// * Record where in the image (relative to the upper left coordinates)

// the mouse was clicked, because it looks best if we drag from there.

// TODO: Move the card to the last position so that it displays on top.

public void mousePressed(MouseEvent e) {

int x = e.getX(); // Save the x coord of the click

int y = e.getY(); // Save the y coord of the click

//... Find card image this is in. Check from top down.

_currentCard = null; // Assume not in any image.

for (int crd=_deck.length-1; crd>=0; crd--) {

Card testCard = _deck[crd];

if (testCard.contains(x, y)) {

//... Found, remember this card for dragging.

_dragFromX = x - testCard.getX(); // how far from left

_dragFromY = x - testCard.getY(); // how far from top

_currentCard = testCard; // Remember what we're dragging.

break; // Stop when we find the first match.

}

}

}

//============================================================= mouseDragged

// Set x,y to mouse position and repaint.

public void mouseDragged(MouseEvent e) {

if (_currentCard != null) { // Non-null if pressed inside card image.

int newX = e.getX() - _dragFromX;

int newY = e.getY() - _dragFromY;

//--- Don't move the image off the screen sides

newX = Math.max(newX, 0);

newX = Math.min(newX, getWidth() - _currentCard.getWidth());

//--- Don't move the image off top or bottom

newY = Math.max(newY, 0);

newY = Math.min(newY, getHeight() - _currentCard.getHeight());

_currentCard.moveTo(newX, newY);

this.repaint(); // Repaint because position changed.

}

}

//======================================================= method mouseExited

// Turn off dragging if mouse exits panel.

public void mouseExited(MouseEvent e) {

_currentCard = null;

}

//=============================================== Ignore other mouse events.

public void mouseMoved (MouseEvent e) {} // ignore these events

public void mouseEntered(MouseEvent e) {} // ignore these events

public void mouseClicked(MouseEvent e) {} // ignore these events

public void mouseReleased(MouseEvent e) {} // ignore these events

}

Card.java

package cards;

import java.awt.*;

import javax.swing.*;

/////////////////////////////////////////////////////////////////////////// Card

class Card {

//=================================================================== fields

private ImageIcon _image;

private int _x;

private int _y;

//============================================================== constructor

public Card(ImageIcon image) {

_image = image;

}

//=================================================================== moveTo

public void moveTo(int x, int y) {

_x = x;

_y = y;

}

//================================================================= contains

public boolean contains(int x, int y) {

return (x > x && x < (x + getWidth()) &&

y > y && y < (y + getHeight()));

}

//================================================================= getWidth

public int getWidth() {

return _image.getIconWidth();

}

//================================================================ getHeight

public int getHeight() {

return _image.getIconHeight();

}

//===================================================================== getX

public int getX() {

return _x;

}

//===================================================================== getY

public int getY() {

return _x;

}

//===================================================================== draw

public void draw(Graphics g, Component c) {

image.paintIcon(c, g, x, _y);

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote