Question

In Java, Write a program in Java FX or Swing that sets up a game of...

In Java, Write a program in Java FX or Swing that sets up a game of concentration(Memory Matching Card Game), first shuffle the cards well and then place eachcard face down in 4 rows of 13 cards each. Each player takes a turn by turning two cards over. If the cards match, then the player picks up the cards and keeps them. If they don't match, the player turns the cards back over. I need the code! You have to uses images like the deck of cards.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Rank.java

public enum Rank {
   TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
}


//Suit.java

public enum Suit {
   CLUBS, HEARTS, SPADES, DIAMONDS
}


//Card.java

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;

public class Card extends JButton {

   // Instance variables
   private Suit suit;
   private Rank rank;

   /**
   * Constructor
   */
   public Card(Suit s, Rank r) {
       super();

       // Set suit and rank
       this.suit = s;
       this.rank = r;

       // Set text alignment
       setHorizontalAlignment(SwingConstants.CENTER);

       // Set size
       setPreferredSize(new Dimension(200, 50));
   }

   /**
   * @return the suit
   */
   public Suit getSuit() {
       return suit;
   }

   /**
   * @return the rank
   */
   public Rank getRank() {
       return rank;
   }

   /**
   * Displays the text
   */
   public void faceUp() {
       setText(rank.toString() + " of " + suit.toString());
       setEnabled(false);
       setBorder(new LineBorder(Color.GREEN, 2));
   }

   /**
   * Removes the text
   */
   public void faceDown() {
       setEnabled(true);
       setText("");
       setBorder(new LineBorder(Color.GRAY));
   }

   /**
   * Checks whether this card is same as Card c
   * @param c - Card to be compared
   * @return - Returns true if both card are same, false otherwise
   */
   public boolean isEqual(Card c) {
       return (this.getRank().equals(c.getRank()) && this.getSuit().equals(c.getSuit()));
   }

   /**
   * Checks whether this card has same rank as Card c
   * @param c - Card to be compared
   * @return - Returns true if both card has same value, false otherwise
   */
   public boolean isEqualRank(Card c) {
       return (this.getRank().equals(c.getRank()));
   }

   @Override
   public String toString() {
       return rank.toString() + " of " + suit.toString();
   }
}


//Board.java

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.TitledBorder;

public class Board implements ActionListener {

   private static final int WIDTH = 4;
   private static final int HEIGHT = 13;

   // Instance variables
   private List<Card> card;
   private Card c1;
   private Card c2;
   private Timer t;
   private int player1;
   private int player2;
   private JLabel turnLbl;
   private int turn;
   private JLabel player1Lbl;
   private JLabel player2Lbl;

   /**
   * Constructor
   */
   public Board() {
       super();

       // Set cards c1 and c2 as null
       c1 = null;
       c2 = null;

       // Set timer to display 2nd card for sometime before displaying the
       // result
       t = new Timer(750, new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent arg0) {
               // Check cards for match
               checkCards();
           }
       });

       // Create cards
       createCards();
   }

   /**
   * Creates cards
   */
   private void createCards() {
       card = new ArrayList<Card>();
       for (Suit s : Suit.values()) {
           for (Rank r : Rank.values())
               card.add(new Card(s, r));
       }

       // Shuffle cards
       shuffle();
   }

   /**
   * Shuffles the cards
   */
   private void shuffle() {
       Collections.shuffle(card);
   }

   /**
   * Gets a panel of cards
   */
   public JPanel getPanel() {
       JPanel panel = new JPanel();

       // Set border
       panel.setBorder(new TitledBorder(""));

       // Set layout
       panel.setLayout(new GridLayout(HEIGHT, WIDTH));

       // Add cards
       for (int i = 0; i < card.size(); i++) {
           panel.add(card.get(i));
           card.get(i).addActionListener(this);
       }

       return panel;
   }

   @Override
   public void actionPerformed(ActionEvent ae) {
       // Check if all cards are not displayed
       if (card.size() != 0) {
           // Get card clicked
           Card c = (Card) ae.getSource();

           // Display card text
           c.faceUp();

           // Set card c1 or c2
           if (c1 == null)
               c1 = c;
           else if (c2 == null) {
               c2 = c;
               t.start();
           }
       }
   }

   /**
   * Checks whether the two selected cards have same rank
   */
   private void checkCards() {
       // Check if cards are equal
       if (c1.isEqualRank(c2)) {
           // Remove cards c1, c2 from list
           for (int i = 0; i < card.size(); i++) {
               // Get card at i
               Card c = card.get(i);

               if (c.isEqual(c1) || c.isEqual(c2)) {
                   card.remove(i);
                   i -= 1;
               }
           }

           // Update points
           updatePoints();

           // Check if game is over
           if (card.size() == 0) {
               if (player1 > player2)
                   JOptionPane.showMessageDialog(null, "Player1 won!!!");
               else if (player1 < player2)
                   JOptionPane.showMessageDialog(null, "Player2 won!!!");
               else
                   JOptionPane.showMessageDialog(null, "The game is tied!!!");
               System.exit(0);
           }
       } else {
           // Set both cards face down
           c1.faceDown();
           c2.faceDown();
       }

       // Set c1, c2 as null
       c1 = null;
       c2 = null;
       t.stop();

       // Set next player's turn
       setTurn();
   }

   /**
   * Updates the current player's points
   */
   private void updatePoints() {
       if (turn == 1) {
           player1 += 1;
           player1Lbl.setText("" + player1);
       } else if (turn == 2) {
           player2 += 1;
           player2Lbl.setText("" + player2);
       }
   }

   /**
   * Sets the turn of the next player
   */
   private void setTurn() {
       if (turn == 1)
           turn = 2;
       else if (turn == 2)
           turn = 1;

       // Update label
       turnLbl.setText("Player " + turn);
   }

   /**
   * Creates a score panel
   */
   public JPanel getScorePanel() {
       JPanel panel = new JPanel();

       // Set border
       panel.setBorder(new TitledBorder(""));

       // Set layout
       panel.setLayout(new GridLayout(3, 2, 10, 30));

       // Set turn and player points
       turn = 1;
       player1 = 0;
       player2 = 0;

       // Create and add labels
       panel.add(new JLabel("TURN: "));
       turnLbl = new JLabel("Player " + turn);
       panel.add(turnLbl);
       panel.add(new JLabel("Player 1: "));
       player1Lbl = new JLabel("" + player1);
       panel.add(player1Lbl);
       panel.add(new JLabel("Player 2: "));
       player2Lbl = new JLabel("" + player2);
       panel.add(player2Lbl);

       return panel;
   }
}


//Game.java

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Game extends JFrame {

   /**
   * Constructor
   */
   public Game() {
       super("Memory Matching Card Game");

       // Set default close operation
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       // Set Layout
       setLayout(new BorderLayout());

       // Set title panel
       JPanel titlePanel = new JPanel();
       titlePanel.add(new JLabel("Memory Matching Card Game"));
       titlePanel.setPreferredSize(new Dimension(500, 75));
       add(titlePanel, BorderLayout.NORTH);

       // Add game board
       Board board = new Board();
       add(board.getPanel(), BorderLayout.CENTER);

       // Add score panel
       add(board.getScorePanel(), BorderLayout.WEST);

       // Pack frame
       pack();

       // Show frame
       setVisible(true);
   }

   public static void main(String[] args) {
       new Game();
   }
}


SAMPLE OUTPUT:

Memory Matching Card Game Memory Matching Card Game ACE of SPADES FIVE of CLUBS TURN: Player 2 FIVE of DIAMONDS SIX of DIAMON

Add a comment
Know the answer?
Add Answer to:
In Java, Write a program in Java FX or Swing that sets up a game of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Needs to use Java FX, with user interface included. Design and implement your project base on following specificat...

    Needs to use Java FX, with user interface included. Design and implement your project base on following specification using FX Make sure you follow MVC design paradigm. Concentration, also known as Match Match, Match Up, Memory, Pelmanism, Shinkei-suijaku, Pexeso or simply Pairs, is a card game in which all of the cards are laid face down on a surface and two cards are flipped face up over each turn. Concentration can be played with any number of players or as...

  • This is python3. Please help me out. Develop the following GUI interface to allow the user...

    This is python3. Please help me out. Develop the following GUI interface to allow the user to specify the number of rows and number of columns of cards to be shown to the user. Show default values 2 and 2 for number of rows and number of columns. The buttons "New Game" and "Turn Over" span two column-cells each. Fig 1. The GUI when the program first starts. When the user clicks the "New Game" button, the program will read...

  • Using Python 3.5.2 and IDLE Write the code for a modified game of the card game...

    Using Python 3.5.2 and IDLE Write the code for a modified game of the card game crazy eights (much like a game of UNO, where the card played is now on top of the deck and its number or face value is now what is playable for the next player). Write the code to be a 2 player game with any 8 card being able to input a new face value to play on the discard pile. Rules: Use a...

  • C++ program This program involves writing a VERY simplified version of the card game War. You...

    C++ program This program involves writing a VERY simplified version of the card game War. You may know this game or not but my rules are these 1. Split the deck between player1 and player2. Only the face values matter (2-14) and not the suits 2. Each player puts a card down on the table. The higher face value wins that hand. If the card values match, you will simply indicate tie and neither player wins.The original rules would require...

  • (C++) Write a program to play the Card Guessing game. Your program must give the user...

    (C++) Write a program to play the Card Guessing game. Your program must give the user the following choices: a. Guess the face value of my card. b. Guess only the suit of the card. c. Guess both the face value and the suit of the card.. Before the start of the game, create a deck of cards. Before each guess, use the function random_shuffle to randomly shuffle the deck. Also include vector into the program. (C++)

  • I am just curious about this question... please can you answer with applying indent and space...

    I am just curious about this question... please can you answer with applying indent and space clearly. Furthermore, can you make answer shortly as possible..? This is a python question Question 6.34 The two-player card game war is played with a standard deck of 52 cards. A shuffled deck is evenly split among the two players who keep their decks face-down. The game consists of battles until one of the players runs out of cards. In a battle, each player...

  • Please to indent and follow structure!!!!! Assignment 3 - The card game: War Due Date: June...

    Please to indent and follow structure!!!!! Assignment 3 - The card game: War Due Date: June 9th, 2018 @ 23:55 Percentage overall grade: 5% Penalties: No late assignments allowed Maximum Marks: 10 Pedagogical Goal: Refresher of Python and hands-on experience with algorithm coding, input validation, exceptions, file reading, Queues, and data structures with encapsulation. The card game War is a card game that is played with a deck of 52 cards. The goal is to be the first player to...

  • 2 A Game of UNO You are to develop an interactive game of UNO between a...

    2 A Game of UNO You are to develop an interactive game of UNO between a number of players. The gameplay for UNO is described at https://www.unorules.com/. Your program should operate as follows. 2.1 Setup 1. UNO cards are represented as variables of the following type: typedef struct card_s { char suit[7]; int value; char action[15]; struct card_s *pt; } card; You are allowed to add attributes to this definition, but not to remove any. You can represent colors by...

  • the card game Acey Deucey, which is also known by several other names. In general, the...

    the card game Acey Deucey, which is also known by several other names. In general, the game is played with three or more people that continue to gamble for a pot of money. The pot grows and shrinks depending on how much General description of the game ● Two cards are dealt face up to a player from a shuffled deck of cards. ○ If the face of each card is the same then the player adds $1 into the...

  • Using C++ Create a Blackjack program with the following features: Single player game against the dealer....

    Using C++ Create a Blackjack program with the following features: Single player game against the dealer. Numbered cards count as the number they represent (example: 2 of any suit counts as 2) except the Aces which can count as either 1 or 11, at the discretion of the player holding the card. Face cards count as 10. Player starts with $500. Player places bet before being dealt a card in a new game. New game: Deal 2 cards to each...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT