×
Samples Blogs Make Payment About Us Reviews 4.9/5 Order Now

Creating an Engaging Memory Game with Java's Swing GUI

June 29, 2024
Dr. Seraphina Stormcloud
Dr. Seraphina
🇬🇧 United Kingdom
Java
Dr. Seraphina Stormcloud is a highly accomplished computer scientist who obtained her PhD from the prestigious University of Oxford, followed by post-doctoral research at the University of Cambridge in the UK. With seven years of experience under her belt, Seraphina has completed over 700 Java Homework assignments with exceptional skill and proficiency.
Tip of the day
Ensure you understand the dataset thoroughly before starting your machine learning assignment. Visualize the data, check for missing values, and identify patterns or anomalies to guide your model-building process effectively.
News
In 2024, universities have introduced new programming courses focusing on cybersecurity, machine learning, and artificial intelligence to better prepare students for modern IT careers.
Key Topics
  • Crafting an Interactive Memory Game in Java
  • Block 1 - Import Statements
  • Block 2 - MemoryGame Class Definition
  • Block 3 - Instance Variables
  • Block 4 - MemoryGame Constructor
  • Block 5 - Frame Setup
  • Block 6 - Image Scaling
  • Block 7 - Panel Setup
  • Block 8 - Image Loading and Shuffling
  • Block 9 - Grid Initialization
  • Block 10 - Timer for Hiding Images
  • Block 11 - Timer for Game Time
  • Block 12 - Frame Visibility
  • Block 13 - ButtonClickListener Inner Class
  • Block 14 - actionPerformed Method
  • Block 15 - Main Method
  • Conclusion

In this guide, we invite you to embark on a journey that combines the thrill of gaming with the joy of programming. Are you looking for a fun and educational Java programming project? Look no further! We will walk you through the process of creating a memory game using Java's Swing GUI library. This memory game project is not only a great way to test your Java skills but also a fun and engaging game that you can play and share with your friends. As we dive into the world of Java and Swing, you'll gain hands-on experience in building a captivating game while honing your programming prowess. So, let's get started on this exciting adventure!

Crafting an Interactive Memory Game in Java

Explore our step-by-step guide on how to build a captivating memory game in Java with our comprehensive guide. This hands-on project will not only help your Java assignment but also provide you with valuable skills in Java Swing GUI development. Create an engaging game to challenge your friends and elevate your programming expertise, making it a fun and educational experience for programmers of all levels. Join us on this exciting journey to master Java game development!

Block 1 - Import Statements

```java import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; ```

This block includes necessary import statements for Swing GUI components and event handling.

Block 2 - MemoryGame Class Definition

```java public class MemoryGame { // Class members and constructor } ```

This block defines the `MemoryGame` class, which contains the game logic.

Block 3 - Instance Variables

```java private JFrame frame; private JButton[][] buttons = new JButton[5][4]; private ImageIcon[][] images = new ImageIcon[5][4]; private ImageIcon empty = new ImageIcon("images\\empty.png"); private int score = 0; private int clickCount = 0; private JButton firstButton; private JButton secondButton; private JLabel scoreLabel; private JLabel timeLabel; private int time = 0; private int pairsFound = 0; private Timer gameTime; ```

These are instance variables of the `MemoryGame` class. They include the frame, buttons, images, score, timers, and other game-related data.

Block 4 - MemoryGame Constructor

```java public MemoryGame() { frame = new JFrame("Memory Game"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600, 500); frame.setLayout(new BorderLayout()); empty = new ImageIcon(empty.getImage().getScaledInstance(150, 90, Image.SCALE_DEFAULT)); JPanel gridPanel = new JPanel(new GridLayout(5, 4)); scoreLabel = new JLabel("Score: 0"); timeLabel = new JLabel("Time: 0"); JPanel scorePanel = new JPanel(new BorderLayout()); scorePanel.add(scoreLabel, BorderLayout.WEST); scorePanel add(timeLabel, BorderLayout.EAST); frame.add(scorePanel, BorderLayout.NORTH); frame.add(gridPanel, BorderLayout.CENTER); ArrayList imageList = new ArrayList<>(); Map imageMap = new HashMap<>(); for(int i=1; i<=7; i++) { String imagePath = "images\\" + i + ".png"; ImageIcon imageIcon; if (!imageMap.containsKey(imagePath)) { imageIcon = new ImageIcon(imagePath); imageIcon = new ImageIcon(imageIcon.getImage().getScaledInstance(150, 90, Image.SCALE_DEFAULT)); imageMap.put(imagePath, imageIcon); } else { imageIcon = imageMap.get(imagePath); } imageList.add(imageIcon); imageList.add(imageIcon); } for(int i=1; i<=3; i++) { String imagePath = "images\\" + i + ".png"; ImageIcon imageIcon; if (!imageMap.containsKey(imagePath)) { imageIcon = new ImageIcon(imagePath); imageIcon = new ImageIcon(imageIcon.getImage().getScaledInstance(264, 158, Image.SCALE_DEFAULT)); imageMap.put(imagePath, imageIcon); } else { imageIcon = imageMap.get(imagePath); } imageList.add(imageIcon); imageList.add(imageIcon); } Collections.shuffle(imageList); int index = 0; for(int i=0; i<5; i++) { for(int j=0; j<4; j++) { buttons[i][j] = new JButton(); buttons[i][j].setIcon(imageList.get(index)); images[i][j] = imageList.get(index); buttons[i][j].setActionCommand(String.valueOf(index)); buttons[i][j].addActionListener(new ButtonClickListener()); gridPanel.add(buttons[i][j]); index++; } } Timer hideImageTimer = new Timer(10000, e -> { for(int i=0; i<5; i++) { for(int j=0; j<4; j++) { buttons[i][j].setIcon(empty); buttons[i][j].setEnabled(true); } gameTime.start(); } }); hideImageTimer.setRepeats(false); hideImageTimer.start(); gameTime = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { time++; timeLabel.setText("Time: " + time); } }); frame.setVisible(true); } ```

This is the constructor for the `MemoryGame` class. It sets up the game interface, initializes variables, and creates the game grid.

Block 5 - Frame Setup

```java frame = new JFrame("Memory Game"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600, 500); frame.setLayout(new BorderLayout()); ```

This block creates and configures the main game frame.

Block 6 - Image Scaling

```java empty = new ImageIcon(empty.getImage().getScaledInstance(150, 90, Image.SCALE_DEFAULT)); ```

It scales the empty image to a specific size.

Block 7 - Panel Setup

```java JPanel gridPanel = new JPanel(new GridLayout(5, 4)); scoreLabel = new JLabel("Score: 0"); timeLabel = new JLabel("Time: 0"); JPanel scorePanel = new JPanel(new BorderLayout()); scorePanel.add(scoreLabel, BorderLayout.WEST); scorePanel.add(timeLabel, BorderLayout.EAST); frame.add(scorePanel, BorderLayout.NORTH); frame.add(gridPanel, BorderLayout.CENTER); ```

This block creates and configures panels to hold the game grid and score/time labels.

Block 8 - Image Loading and Shuffling

```java // Image loading and shuffling code ArrayList imageList = new ArrayList<>(); Map imageMap = new HashMap<>(); for (int i = 1; i <= 7; i++) { String imagePath = "images\\" + i + ".png"; ImageIcon imageIcon; if (!imageMap.containsKey(imagePath)) { imageIcon = new ImageIcon(imagePath); imageIcon = new ImageIcon(imageIcon.getImage().getScaledInstance(150, 90, Image.SCALE_DEFAULT)); imageMap.put(imagePath, imageIcon); } else { imageIcon = imageMap.get(imagePath); } imageList.add(imageIcon); imageList.add(imageIcon); } for (int i = 1; i <= 3; i++) { String imagePath = "images\\" + i + ".png"; ImageIcon imageIcon; if (!imageMap.containsKey(imagePath)) { imageIcon = new ImageIcon(imagePath); imageIcon = new ImageIcon(imageIcon.getImage().getScaledInstance(264, 158, Image.SCALE_DEFAULT)); imageMap.put(imagePath, imageIcon); } else { imageIcon = imageMap.get(imagePath); } imageList.add(imageIcon); imageList.add(imageIcon); } Collections.shuffle(imageList); ```

This section loads and shuffles the game's image pairs.

Block 9 - Grid Initialization

```java int index = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { buttons[i][j] = new JButton(); buttons[i][j].setIcon(imageList.get(index)); images[i][j] = imageList.get(index); buttons[i][j].setActionCommand(String.valueOf(index)); buttons[i][j].addActionListener(new ButtonClickListener()); gridPanel.add(buttons[i][j]); index++; } } ```

This block initializes the game grid by adding buttons and assigning images to them.

Block 10 - Timer for Hiding Images

```java Timer hideImageTimer = new Timer(10000, e -> { for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { buttons[i][j].setIcon(empty); buttons[i][j].setEnabled(true); } gameTime.start(); } }); hideImageTimer.setRepeats(false); hideImageTimer.start(); ```

A timer is set up to hide the images after a certain period.

Block 11 - Timer for Game Time

```java gameTime = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { time++; timeLabel.setText("Time: " + time); } }); ```

This code sets up a timer to keep track of the game's elapsed time.

Block 12 - Frame Visibility

```java frame.setVisible(true); } ```

This line makes the game frame visible to the player.

Block 13 - ButtonClickListener Inner Class

```java // ButtonClickListener Inner Class class ButtonClickListener implements ActionListener { public void actionPerformed(ActionEvent e) { JButton clickedButton = (JButton) e.getSource(); int clickedIndex = Integer.parseInt(clickedButton.getActionCommand()); clickedButton.setIcon(images[clickedIndex / 4][clickedIndex % 4]); clickedButton.setEnabled(false); if (clickCount == 0) { firstButton = clickedButton; clickCount++; } else { secondButton = clickedButton; if (firstButton.getIcon().equals(secondButton.getIcon())) { pairsFound++; score++; if (pairsFound == 10) { gameTime.stop(); JOptionPane.showMessageDialog(frame, "You won the game! Time: " + time + " seconds"); System.exit(0); } } else { score--; if (score == -10) { gameTime.stop(); JOptionPane.showMessageDialog(frame, "Game Over! Score: " + score); System.exit(0); } Timer timer = new Timer(1000, e1 -> { firstButton.setIcon(empty); firstButton.setEnabled(true); secondButton.setIcon(empty); secondButton.setEnabled(true); }); timer.setRepeats(false); timer.start(); } clickCount = 0; } scoreLabel.setText("Score: " + score); } } ```

This inner class handles button click events and implements the game logic.

Block 14 - actionPerformed Method

```java public void actionPerformed(ActionEvent e) { JButton clickedButton = (JButton) e.getSource(); int clickedIndex = Integer.parseInt(clickedButton.getActionCommand()); clickedButton.setIcon(images[clickedIndex / 4][clickedIndex % 4]); clickedButton.setEnabled(false); if (clickCount == 0) { firstButton = clickedButton; clickCount++; } else { secondButton = clickedButton; if (firstButton.getIcon().equals(secondButton.getIcon())) { pairsFound++; score++; if (pairsFound == 10) { gameTime.stop(); JOptionPane.showMessageDialog(frame, "You won the game! Time: " + time + " seconds"); System.exit(0); } } else { score--; if (score == -10) { gameTime.stop(); JOptionPane.showMessageDialog(frame, "Game Over! Score: " + score); System.exit(0); } Timer timer = new Timer(1000, e1 -> { firstButton.setIcon(empty); firstButton.setEnabled(true); secondButton.setIcon(empty); secondButton.setEnabled(true); }); timer.setRepeats(false); timer.start(); } clickCount = 0; } scoreLabel.setText("Score: " + score); } ```

This method handles button click events, checks for matches, and updates the game state.

Block 15 - Main Method

```java public static void main(String[] args) { new MemoryGame(); } ```

The `main` method initializes the game by creating an instance of the `MemoryGame` class.

Conclusion

In conclusion, this Java memory game project offers a delightful blend of education and entertainment, making it a perfect choice for both novice and experienced Java programmers. By delving into the intricacies of Swing GUI, you've not only developed a captivating memory game but also honed your Java skills. Whether you're a student looking to enhance your programming abilities or a hobbyist eager to create fun games, this project has provided valuable insights and hands-on experience. We encourage you to explore further, expand your Java knowledge, and keep creating exciting projects. Happy coding!

Related Samples

Explore our Java Assignments samples for comprehensive solutions to programming challenges. From basic algorithms to advanced data structures, these samples provide clear, commented code for learning and reference. Perfect for students and professionals looking to enhance their Java programming skills. Dive into our curated collection and elevate your coding expertise today!