Create a simple memory game using a single-dimension array. Game Description: Gi
ID: 3762410 • Letter: C
Question
Create a simple memory game using a single-dimension array. Game Description: Give the user a choice between difficult levels: Easy – User gets 20 turns Medium – User gets 10 turns Hard – User gets 5 turns When the user gets a match, they don't lose the turn. If they don't get a match, they lose a turn. 5 incorrect guesses = game over. The user guesses two items, these items are revealed to the user. If they match, the cards stay flipped over when presenting the puzzle. Otherwise re-hide the puzzle and ask for a new guess. The user wins if they match all the items. Specifications: Create a game according to the above rules Your array should use either numbers or letters. (integers might be easier) You should have at least 10 items to match (so your array should be at least 20 items) If you do more than 10 items, you might want to give the player more turns. The positions of the 10 items should be randomized every time the game is played.
Explanation / Answer
If you have any further queries, just get back to me.
import java.io.*;
import java.util.*;
class MemoryGame
{
public static boolean allCardsOpen(int X[])
{
for(int i = 0; i < 20; i++)
if(X[i] == 0)
return false;
return true;
}
public static void main(String[] args)
{
int firstCard, secondCard;
System.out.println("Welcome to the memory game.");
System.out.print("Select the Level.... 1. Easy. 2. Medium. 3. Hard. ?");
Scanner sc = new Scanner(System.in);
int level = sc.nextInt();
int turns;
if(level == 1)
turns = 20;
else if(level == 2)
turns = 10;
else if(level == 3)
turns = 5;
else
turns = 0;
int[] CardFront = new int[20];
int[] CardBack = new int[20];
for(int i = 0; i < 20; i++)
CardBack[i] = 0;
for(int i = 0; i < 10; i++)
CardFront[i] = CardFront[i+10] = i+1;
Random rm = new Random();
for(int i = 0; i < 20; i++)
{
int x = rm.nextInt(20);
int y = rm.nextInt(20);
int temp = CardFront[x];
CardFront[x] = CardFront[y];
CardFront[y] = temp;
}
while(turns != 0)
{
System.out.println(" Choose your first card position: ");
firstCard = sc.nextInt();
System.out.println("Choose your second card position: ");
secondCard = sc.nextInt();
System.out.println("Pos "+firstCard+": "+CardFront[firstCard]);
System.out.println("Pos "+secondCard+": "+CardFront[secondCard]);
if(CardFront[firstCard] == CardFront[secondCard])
{
CardBack[firstCard] = CardBack[secondCard] = CardFront[firstCard];
if(allCardsOpen(CardBack))
break;
}
else
{
turns--;
System.out.println("Oops. Wrong guess.");
}
for(int i = 0; i < 20; i++)
System.out.print(CardBack[i]+" ");
}
if(allCardsOpen(CardBack))
System.out.println("Wow. You made it. Congrats...");
else
System.out.println("Oops. You ran out of turns...");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.