Java Project – Memory Game
FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!
In today’s fast-paced world, memory and cognitive abilities play a crucial role in our daily lives. Whether it’s remembering important information, staying focused, or enhancing problem-solving skills, a sharp memory can be a valuable asset. But how can we train and improve our memory while having fun? That’s where the captivating Memory Game comes into play!
In this project, we’ll dive into the fascinating world of Java programming and explore how to build an interactive and engaging Memory Game from scratch. This project will not only help you enhance your Java skills but also provide an entertaining way to challenge and boost your memory power.
So, get ready to exercise your brain, enhance your programming skills, and have a blast while building your very own Memory Game in Java. Are you up for the challenge? Let’s dive in and embark on this exciting journey together!
About Java Memory Game Project
We will implement the following functionalities in the Java Memory Game Project :
1. We will define a MemoryGame class that represents the memory game.
2. We will use two lists: cards to store the card values and matches to track if a card is matched or not.
3. We will keep track of the number of matches found and the number of attempts made.
4. The initializeCards(int numPairs) function will initialize the game cards by adding pairs of cards and shuffling them randomly.
5. The play() function will manage the gameplay by displaying the board, taking user input for card indices, checking for matches, updating the match status, and counting attempts.
6. The displayCards() function will print the current board state, showing matched cards and hidden cards.
7. The validInput(int firstIndex, int secondIndex) function will check if the input indices are valid and not the same.
8. The main() function will create an instance of the MemoryGame class and start the game by calling the play() function.
Prerequisites For Java Memory Game Project
To write and run the Java Memory Game Project code, the following prerequisites are required:
1. Basic understanding of the Java programming language, including knowledge of loops, conditional statements, and object-oriented programming concepts.
2. Familiarity with array data structures and Java.util package.
3. A working Java development environment, which includes installing the Java Development Kit (JDK) on your computer. You can download the JDK from the official Oracle website or use a package manager specific to your operating system.
4. An Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or NetBeans, can greatly simplify Java development. Choose an IDE you are comfortable with and set it up.
Download Java Memory Game Project Code
Please download the source code of the Java Memory Game Project: Java Memory Game Project Code.
Code Breakdown
1. MemoryGame class, Instance variables and MemoryGame() constructor:
MemoryGame class:
Represents the main class that encapsulates the memory game functionality.
Instance variables:
•cards: A list to store the cards.
•matched: A list to track if a card is matched or not.
•numMatches: An integer representing the number of matches found.
• Attempt: An integer representing the number of attempts made.
MemoryGame() constructor:
•Initializes the cards, matched, numMatches, and attempts variables.
public class MemoryGame { private List<String> cards; // List to store the cards private List<Boolean> matched; // List to track if a card is matched or not private int numMatches; // Number of matches found private int attempts; // Number of attempts made public MemoryGame() { cards = new ArrayList<>(); // Initialize the cards list matched = new ArrayList<>(); // Initialize the matched list numMatches = 0; // Initialize the number of matches to 0 attempts = 0; // Initialize the number of attempts to 0 }
2. initializeCards(int numPairs) method:
•Initializes the game cards and their matching status.
•Populates the cards list with pairs of cards based on numPairs.
•Initializes the matched list with false values for each card.
•Shuffles the cards list randomly using Collections.shuffle().
public void initializeCards(int numPairs) { for (int i = 0; i < numPairs; i++) { cards.add(String.valueOf(i + 1)); // Add the card value (number) to the list cards.add(String.valueOf(i + 1)); // Add the card value (number) again to create a pair matched.add(false); // Set the initial match status of the card to false matched.add(false); // Set the initial match status of the card to false } Collections.shuffle(cards); // Shuffle the cards randomly }
3. play() method:
• Manages the gameplay logic for the memory game.
• Takes user input for the number of pairs to play with.
• Calls initializeCards(numPairs) to set up the game.
• Enters a loop until all matches are found.
• Displays the current board using displayCards() method.
• Takes user input for the indices of the first and second cards to flip.
• Checks if the input is valid and the cards are not already matched using the validInput() method.
• Compares the values of the selected cards and updates the match status accordingly.
• Tracks the number of attempts made and the number of matches found.
• Prints appropriate messages based on the match result and input validity.
• Prints the number of attempts taken to complete the game.
public void play() { Scanner scanner = new Scanner(System.in); System.out.println("Welcome to the Memory Game by ProjectGurukul!"); System.out.print("Enter the number of pairs you want to play with: "); int numPairs = scanner.nextInt(); initializeCards(numPairs); while (numMatches < numPairs) { displayCards(); // Display the current board System.out.print("Enter the first card index (0 to " + (cards.size() - 1) + "): "); int firstIndex = scanner.nextInt(); System.out.print("Enter the second card index (0 to " + (cards.size() - 1) + "): "); int secondIndex = scanner.nextInt(); // Check if the input is valid and the cards are not already matched if (validInput(firstIndex, secondIndex) && !matched.get(firstIndex) && !matched.get(secondIndex)) { if (cards.get(firstIndex).equals(cards.get(secondIndex))) { System.out.println("Match found!"); matched.set(firstIndex, true); // Set the match status of the cards to true matched.set(secondIndex, true); // Set the match status of the cards to true numMatches++; // Increment the number of matches } else { System.out.println("No match. Try again."); } attempts++; // Increment the number of attempts } else { System.out.println("Invalid input. Try again."); } System.out.println(); } System.out.println("Congratulations! You have completed the game in " + attempts + " attempts."); scanner.close(); }
4. displayCards() method:
• Displays the current state of the game board.
• Iterates through the cards list and prints either the matched card value or a hidden card indicator based on the matched list.
private void displayCards() { System.out.println("Current Board:"); for (int i = 0; i < cards.size(); i++) { if (matched.get(i)) { System.out.print("[" + cards.get(i) + "] "); // Display the matched card } else { System.out.print("[*] "); // Display a hidden card } } System.out.println(); }
5. validInput(int firstIndex, int secondIndex) method:
• Checks if the input indices are within the valid range and are not the same.
• Returns true if the input is valid; otherwise, returns false.
private boolean validInput(int firstIndex, int secondIndex) { // Check if the indices are within the valid range and are not the same return firstIndex >= 0 && firstIndex < cards.size() && secondIndex >= 0 && secondIndex < cards.size() && firstIndex != secondIndex; }
6. main(String[] args) method:
• Creates an instance of the MemoryGame class.
• Invokes the play() method to start the game.
public static void main(String[] args) { MemoryGame game = new MemoryGame(); game.play(); } }
Code to illustrate the Java Memory Game Project
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class MemoryGame { private List<String> cards; // List to store the cards private List<Boolean> matched; // List to track if a card is matched or not private int numMatches; // Number of matches found private int attempts; // Number of attempts made public MemoryGame() { cards = new ArrayList<>(); // Initialize the cards list matched = new ArrayList<>(); // Initialize the matched list numMatches = 0; // Initialize the number of matches to 0 attempts = 0; // Initialize the number of attempts to 0 } public void initializeCards(int numPairs) { for (int i = 0; i < numPairs; i++) { cards.add(String.valueOf(i + 1)); // Add the card value (number) to the list cards.add(String.valueOf(i + 1)); // Add the card value (number) again to create a pair matched.add(false); // Set the initial match status of the card to false matched.add(false); // Set the initial match status of the card to false } Collections.shuffle(cards); // Shuffle the cards randomly } public void play() { Scanner scanner = new Scanner(System.in); System.out.println("Welcome to the Memory Game by ProjectGurukul!"); System.out.print("Enter the number of pairs you want to play with: "); int numPairs = scanner.nextInt(); initializeCards(numPairs); while (numMatches < numPairs) { displayCards(); // Display the current board System.out.print("Enter the first card index (0 to " + (cards.size() - 1) + "): "); int firstIndex = scanner.nextInt(); System.out.print("Enter the second card index (0 to " + (cards.size() - 1) + "): "); int secondIndex = scanner.nextInt(); // Check if the input is valid and the cards are not already matched if (validInput(firstIndex, secondIndex) && !matched.get(firstIndex) && !matched.get(secondIndex)) { if (cards.get(firstIndex).equals(cards.get(secondIndex))) { System.out.println("Match found!"); matched.set(firstIndex, true); // Set the match status of the cards to true matched.set(secondIndex, true); // Set the match status of the cards to true numMatches++; // Increment the number of matches } else { System.out.println("No match. Try again."); } attempts++; // Increment the number of attempts } else { System.out.println("Invalid input. Try again."); } System.out.println(); } System.out.println("Congratulations! You have completed the game in " + attempts + " attempts."); scanner.close(); } private void displayCards() { System.out.println("Current Board:"); for (int i = 0; i < cards.size(); i++) { if (matched.get(i)) { System.out.print("[" + cards.get(i) + "] "); // Display the matched card } else { System.out.print("[*] "); // Display a hidden card } } System.out.println(); } private boolean validInput(int firstIndex, int secondIndex) { // Check if the indices are within the valid range and are not the same return firstIndex >= 0 && firstIndex < cards.size() && secondIndex >= 0 && secondIndex < cards.size() && firstIndex != secondIndex; } public static void main(String[] args) { MemoryGame game = new MemoryGame(); game.play(); } }
Java Memory Game Output
Summary
Congratulations on completing the journey of building your very own Memory Game in Java! Throughout this project, we’ve explored the fascinating world of programming, challenged our memory, and enhanced our Java skills.
By creating an interactive and engaging game, we’ve combined learning and entertainment into a single project. Remember, this is just the beginning of your journey into game development and Java programming.
There are endless possibilities to explore and countless ways to expand upon this Java memory game project. You can consider adding features such as score tracking, difficulty levels, or even a graphical user interface to take your Memory Game to the next level.
Thank you for joining us on this incredible journey of building a Memory Game in Java. We’re confident that the skills you’ve acquired and the memories you’ve made will stay with you as you continue your programming endeavours. Keep coding, keep challenging your memory, and keep pushing the boundaries of what you can achieve!
Happy gaming and programming!