Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 86,252 Java Programmers. There are 2,115 online right now! Ask your question and get quick answers from Dream.In.Code experts. Join the #1 programming help community on the internet! Registration is fast and FREE... Join Now!

Chat LIVE With a Java Expert
Powered by LivePerson.com

Register to Make This Box Go Away!

Having problems getting going on a Memory Game Applet

 
Reply to this topicStart new topic

Having problems getting going on a Memory Game Applet

Ridlet25825
post 8 May, 2008 - 08:16 AM
Post #1


New D.I.C Head

*
Joined: 8 May, 2008
Posts: 5



Ok, I'm not too sure where to start... I'm working on a Memory Game JApplet that I'm very lost on. I know what I want it to do, but I can't seem to figure out where to even begin coding... I have created the JApplet and added 3 panels... within the second panel, I want to place 20 JButtons that will function as my "cards". I want to be able to push 2 buttons at a time and if they match, they are removed from the board, otherwise they should become JButtons again. I am trying to create a class that extends JButton for these cards. I've tried a bunch of different things, so you'll see a bunch of random code within the code I've attached.

CODE
import javax.swing.JApplet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MemoryGame extends JApplet { // ABSOLUTELY MUST BE PUBLIC!!!
    private int row;
    private int column;
    private int [] [] gameBoard = {
        {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {8, 8}, {9, 9}, {10, 10}};
    private MemoryCards [] pictureButtons = new MemoryCards [20];

    public void init() {
        // Set the layout to BorderLayout
        setLayout(new BorderLayout());

        // Create 3 panels
        JPanel northPanel = new JPanel();
        JLabel titleLabel = new JLabel("Memory");
        titleLabel.setFont(new Font("Curlz MT", Font.PLAIN, 40));
        northPanel.add(titleLabel);
        JPanel gamePanel = new JPanel();
        gamePanel.setLayout(new GridLayout(4, 0));
        for(int lcv = 0; lcv <=pictureButtons.length; lcv++)
            gamePanel.add(pictureButtons[lcv]);
        JPanel southPanel = new JPanel();
        JLabel counterLabel = new JLabel("Number of moves: ");
        counterLabel.setFont(new Font("Curlz MT", Font.PLAIN, 20));
        //counterLabel.setHorizontalTextPosition(SwingConstants.LEFT);
        southPanel.add(counterLabel);

        // Color the panels so I can see them
        northPanel.setBackground(Color.YELLOW);
        gamePanel.setBackground(Color.MAGENTA);
        southPanel.setBackground(Color.CYAN);

         //Add 1 panel to the NORTH section and the 2nd to the CENTER section
         this.add(northPanel, BorderLayout.NORTH);
         this.add(gamePanel, BorderLayout.CENTER);
         this.add(southPanel, BorderLayout.SOUTH);
    }

    class MemoryCards extends JButton {
        ImageIcon pictureSide = new ImageIcon("baseball.jpg");
        ImageIcon backOfCard = new ImageIcon("Dog Bone.jpg");

        public ImageIcon getPicture() {
            //if (matched)
                return pictureSide;
            //else
            //    return backOfCard;
            }
        }


I guess I just need guidance as to where to start... This isn't due until next Thursday, so I still have a little while to work on it. I'm just started to stress a bit because I don't even know where to start! Thanks a bunch for any help! rolleyes.gif
User is offlineProfile CardPM
Go to the top of the page
+Quote Post


pbl
post 8 May, 2008 - 08:58 AM
Post #2


D.I.C Addict

Group Icon
Joined: 6 Mar, 2008
Posts: 843

That is a good start indeed.

But I guess you will need 10 different images for your 20 buttons so
CODE

   String[] imageFile = {"file1.jpg", "file2.jpg", "file3.jpg","file4.jpg", "file5.jpg", "file6.jpg",
        "file7.jpg", "file8.jpg", "file9.jpg", "file10.jpg"};


Now you can pass the image to use to your MemoryCard constructor (constructor that your forgot to call in your for loop);

CODE

   for(int lcv = 0; lcv <=pictureButtons.length; lcv++) {
      pictureButtons[lcv] = new MemoryCard(imageFile[lcv/2]);
      gamePanel.add(pictureButtons[lcv]);
   }


as I pass as parameter to the constructor imageFile[lcv/2] lcv divided by 2
pictureButton[0] will be created with imageFile[0] which is file1.jpg
pictureButton[1] will be created with imageFile[0] which is file1.jpg
pictureButton[2] will be created with imageFile[1] which is file2.jpg
....
pictureButton[19] will be created with imageFile[9] which is file10.jpg

So now your constructor need to be changed
It will also need an ActionListener so it will react when cliqued
and maybe something to compare them to know if they show the same image

CODE

class MemoryCard extends JButton implements ActionListener {
    // to be displayed when clicked
    ImageIcon icon;
    // remember which image I display for comparaison
    String file;

    MemoryCard(String filename) {
         super("");
         file = filename;
         ImageIcon icon = new ImageIcon(filename);
         addActionListener(this);
    }

    // to see if 2 buttons show the same image
    boolean equals(MemoryCard theOtherButton) {
        return file == theOtherButton.file;
    }

    // called when button is clicked
    public void actionPerformed(ActionEvent e) {
        setIcon(icon);
    }
}


That should keep you busy for a while
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

Ridlet25825
post 8 May, 2008 - 09:15 AM
Post #3


New D.I.C Head

*
Joined: 8 May, 2008
Posts: 5

Thank you, thank you, thank you! I will let you know how I'm doing!
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

pbl
post 8 May, 2008 - 12:14 PM
Post #4


D.I.C Addict

Group Icon
Joined: 6 Mar, 2008
Posts: 843

QUOTE(Ridlet25825 @ 8 May, 2008 - 09:15 AM) *

Thank you, thank you, thank you! I will let you know how I'm doing!


You're welcome and as I already know what will be your next question I'll answer it right now.

Your question will be: the way you did it, the pictures are one after the other. They should be random because, without that, It would be a very very easy Memory game. I need to suffle them.

Answer:

Instead of adding the MemoryCards to the JPanel right away after their creation put them first in an ArrayList. After that put them randomly into the GridLayout.

CODE

// ArrayList to hold the MemoryCard
ArrayList<MemoryCard> list = new ArrayList<MemoryCard>();

for(int lcv = 0; lcv <=pictureButtons.length; lcv++) {
      pictureButtons[lcv] = new MemoryCard(imageFile[lcv/2]);
      list.add(pictureButtons[lcv]);
   }

Random ran = newRandom();
while(list.size() > 0) {
    int n = ran.nextInt(list.size());
    MemoryCard button = list.remove(n);
    gamePanel.add(button);
}
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

Ridlet25825
post 9 May, 2008 - 07:22 AM
Post #5


New D.I.C Head

*
Joined: 8 May, 2008
Posts: 5

And thank you again! biggrin.gif
Ok, so I've gotten a lot further than I was yesterday when I first posted my problem wink2.gif but now I'm stuck on how to stop the user from clicking on more than two buttons at a time. The program should work in such a way that the user clicks two buttons, the program checks to see if they match, if they do match, the pictures stay visible, and if they don't match, the pictures go away and the user clicks two new buttons. I thought about possibly using a setEnabled(true) and setEnabled(false), but I wasn't sure where to put it... I'm open to any ideas any may have! Thanks again... Here's the code I have so far...

CODE
import javax.swing.JApplet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class MemoryGame extends JApplet  {
    private int row;
    private int column;
    private MemoryCard [] pictureButton = new MemoryCard [20];
    // ArrayList to hold the MemoryCard
    ArrayList<MemoryCard> cardList = new ArrayList<MemoryCard>();
    String[] imageFile = {"file1.png", "file2.png", "file3.png","file4.png", "file5.png", "file6.png",
       "file7.png", "file8.png", "file9.png", "file10.png"};
     static int lcv = 0;
     private JLabel pictureViewerLabel;

    public void init() {
        setSize(600, 500);
        setLayout(new BorderLayout());

        // Create 3 panels
        JPanel northPanel = new JPanel();
        JLabel titleLabel = new JLabel("Memory");
        titleLabel.setFont(new Font("Curlz MT", Font.PLAIN, 40));
        northPanel.add(titleLabel);

        JPanel gamePanel = new JPanel();
        gamePanel.setLayout(new GridLayout(4, 0));
        for(lcv = 0; lcv < pictureButton.length; lcv++) {
                  pictureButton[lcv] = new MemoryCard(imageFile[lcv/2]);
                  cardList.add(pictureButton[lcv]);
               }
            Random ran = new Random();
            while(cardList.size() > 0) {
                int randomCounter = ran.nextInt(cardList.size());
                MemoryCard pictureButton = cardList.remove(randomCounter);
                gamePanel.add(pictureButton);
}
        JPanel southPanel = new JPanel();
        southPanel.setLayout(new GridLayout(2,0));
        JLabel counterLabel = new JLabel("Number of moves: ");
        counterLabel.setFont(new Font("Curlz MT", Font.PLAIN, 20));
        JTextArea directions = new JTextArea("Directions: \n1. Turn two cards" +
         " picture-side-up by clicking on the cards.  \n2. Make matches by selecting" +
         " two identical cards.  \n3. Try to match all the cards in as few moves as" +
         " possible.  \n4. HAVE FUN!", 5, 25);
        directions.setFont(new Font("Bookman Old Style", Font.PLAIN, 17));
        directions.setLineWrap(true);
        directions.setWrapStyleWord(true);
        directions.setEditable(false);
        southPanel.add(directions);
        counterLabel.setHorizontalTextPosition(SwingConstants.LEFT);
        southPanel.add(counterLabel);

        // Color the panels so I can see them
        //northPanel.setBackground(Color.YELLOW);
        //gamePanel.setBackground(Color.MAGENTA);
        //southPanel.setBackground(Color.CYAN);

        //Add 1 panel to the NORTH section and the 2nd to the CENTER section
        this.add(northPanel, BorderLayout.NORTH);
        this.add(gamePanel, BorderLayout.CENTER);
        this.add(southPanel, BorderLayout.SOUTH);


        for (lcv = 0; lcv < pictureButton.length; lcv++) {
            pictureButton[lcv].addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                        String filename = ((MemoryCard)(evt.getSource())).getFile();
                        ((MemoryCard)(evt.getSource())).setIcon(new ImageIcon(filename));
                }
            });
        }
    }

    class MemoryCard extends JButton {
        ImageIcon icon;
        String file;

        MemoryCard(String filename) {
            super();
            file = filename;
            icon = new ImageIcon(filename);
        }

        String getFile(){
            return file;
        }
    }
}
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

pbl
post 9 May, 2008 - 08:34 AM
Post #6


D.I.C Addict

Group Icon
Joined: 6 Mar, 2008
Posts: 843

I guess that should do it
Haven't test it don't have all your .png files

Also removed the pictureButton array you will see that it was useless

java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class MemoryGame extends JApplet {
// you will not need these anymore
// private int row;
// private int column;
// private MemoryCard [] pictureButton = new MemoryCard [20];
// no need to make this one an instance variable.. let it disappear when constructor is done
// ArrayList to hold the MemoryCard
// ArrayList<MemoryCard> cardList = new ArrayList<MemoryCard>();
String[] imageFile = {"file1.png", "file2.png", "file3.png","file4.png", "file5.png", "file6.png",
"file7.png", "file8.png", "file9.png", "file10.png"};
// static int lcv = 0;
private JLabel pictureViewerLabel;

// to remember last call
MemoryCard firstChoice, secondChoice;
// number turned up
int nbMatched;

public void init() {
setSize(600, 500);
setLayout(new BorderLayout());

// Create 3 panels
JPanel northPanel = new JPanel();
JLabel titleLabel = new JLabel("Memory");
titleLabel.setFont(new Font("Curlz MT", Font.PLAIN, 40));
northPanel.add(titleLabel);

JPanel gamePanel = new JPanel();
gamePanel.setLayout(new GridLayout(4, 0));
ArrayList<MemoryCard> cardList = new ArrayList<MemoryCard>();
// now we use the lenght of the imageFile times 2
for(int lcv = 0; lcv < imageFile.length * 2; lcv++)
cardList.add(new MemoryCard(imageFile[lcv/2]));

Random ran = new Random();
while(cardList.size() > 0) {
int randomCounter = ran.nextInt(cardList.size());
gamePanel.add(cardList.remove(randomCounter));
}

JPanel southPanel = new JPanel();
southPanel.setLayout(new GridLayout(2,0));
JLabel counterLabel = new JLabel("Number of moves: ");
counterLabel.setFont(new Font("Curlz MT", Font.PLAIN, 20));
JTextArea directions = new JTextArea("Directions: \n1. Turn two cards" +
" picture-side-up by clicking on the cards. \n2. Make matches by selecting" +
" two identical cards. \n3. Try to match all the cards in as few moves as" +
" possible. \n4. HAVE FUN!", 5, 25);
directions.setFont(new Font("Bookman Old Style", Font.PLAIN, 17));
directions.setLineWrap(true);
directions.setWrapStyleWord(true);
directions.setEditable(false);
southPanel.add(directions);
counterLabel.setHorizontalTextPosition(SwingConstants.LEFT);
southPanel.add(counterLabel);

// Color the panels so I can see them
//northPanel.setBackground(Color.YELLOW);
//gamePanel.setBackground(Color.MAGENTA);
//southPanel.setBackground(Color.CYAN);

//Add 1 panel to the NORTH section and the 2nd to the CENTER section
this.add(northPanel, BorderLayout.NORTH);
this.add(gamePanel, BorderLayout.CENTER);
this.add(southPanel, BorderLayout.SOUTH);


// I move the listener back to MemoryCode because the code will be
// longer and it becomes messy and hard to read
// for (lcv = 0; lcv < pictureButton.length; lcv++) {
// pictureButton[lcv].addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent evt) {
// String filename = ((MemoryCard)(evt.getSource())).getFile();
// ((MemoryCard)(evt.getSource())).setIcon(new ImageIcon(filename));
// }
// });
}


class MemoryCard extends JButton implements ActionListener {
ImageIcon icon;
String file;

MemoryCard(String filename) {
super();
file = filename;
icon = new ImageIcon(filename);
}
// no need for that we are playing with it internally
// String getFile(){
// return file;
// }

public void actionPerformed(ActionEvent arg0) {

// if the button displays its Icon it is because it
// has already be turned on so ignore it
if(this.getIcon() != null)
return;

// if the secondChoice has already be turned on the user
// try on a third button (or play too fast)
if(secondChoice != null)
return;

// ok is it first choice or second choice
// in both case I will display my image
setIcon(icon); // turn on image

// test first choice first
if(firstChoice == null) {
firstChoice = this; // remember selection
return;
}

// ok so it is secondChoice
// is there a match
if(file == firstChoice.file) {
firstChoice = null;
nbMatched++;
// test if we are done
if(nbMatched == imageFile.length) {
// do here what ever you want to do when the game
// is over
}
return;
}
// OK remember this as second choice
secondChoice = this;
// sleep 2 seconds
try {
Thread.sleep(2000);
}
catch(Exception e) {
}
// display back the plain button
firstChoice.setIcon(null);
setIcon(null);
// flag no selection made yet
firstChoice = secondChoice = null;

}
}
}
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 5/16/08 09:06AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month