?
Solved

Tracking score in game

Posted on 2006-03-21
17
Medium Priority
?
492 Views
Last Modified: 2010-03-31
I am having a problem trying to keep track of score for players.  I need to be able to add mulitple players and manage the number of correct matches. I setup a JTextArea for the Player info, including the score, but I am unsure how to go about updating it.

Also I am having an issue with getting the JButton to restart the game to work as well, again not sure where to start.

Any help or direction is always appreicated.


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

      public class GameGUI extends JFrame implements ActionListener
      {
            JPanel imagePanel;                                          // Panel for the images on buttons.
            JTextArea playerInfo;                                    // JTextArea for Player Information.
            JButton [] imageButton;                                    // Array of buttons to hold images.
            ImageIcon [] imageOnButton;                              // Array of imageIcons.
            Players [] playerArray = new Players [10];      // Array for Player information.
            ImageIcon imageNull;                                    // Null image for blank button.
            int status =1;                                                // Flag for when button selected.
            int indexOfFirst = 0;                                    // Temp index for image comparison.
            int lastPlayer = 0;
            int prompt;
            int currentTurn = 0;      
            private JButton startButton, closeButton;
            
            // Array of image file names to be used to create imageIcons to be shown on
            // the buttons.
            String [] images = {"apple.gif", "ball.gif", "bannana.gif", "bear.gif", "bird.gif", "bug.gif",
                        "butterfly.gif", "cake.gif", "cat.gif", "dog.gif", "doll.gif", "dragon.gif", "duck.gif",
                        "elephant.gif", "fish.gif", "flower.gif", "frog.gif", "gift.gif", "hat.gif", "hotdog.gif",
                        "jackinthebox.gif", "keys.gif", "pizza.gif", "plane.gif", "rabbit.gif", "rocket.gif",
                        "rockinghorse.gif", "shoe.gif", "skateboard.gif", "snail.gif", "squirrel.gif", "sun.gif",
                        "apple.gif", "ball.gif", "bannana.gif", "bear.gif", "bird.gif", "bug.gif",
                        "butterfly.gif", "cake.gif", "cat.gif", "dog.gif", "doll.gif", "dragon.gif", "duck.gif",
                        "elephant.gif", "fish.gif", "flower.gif", "frog.gif", "gift.gif", "hat.gif", "hotdog.gif",
                        "jackinthebox.gif", "keys.gif", "pizza.gif", "plane.gif", "rabbit.gif", "rocket.gif",
                        "rockinghorse.gif", "shoe.gif", "skateboard.gif", "snail.gif", "squirrel.gif", "sun.gif"};
            
            Container container;
            
            public GameGUI()
            {      
                  super();

                  container = getContentPane();
                  JPanel southLayout = new JPanel();
                  JPanel northLayout = new JPanel();
                  JPanel border = new JPanel (new BorderLayout ());
                  CloseButtonListener closeButtonListener = new CloseButtonListener();
                  
                  // South Layout
                  southLayout.setLayout (new FlowLayout());
                  startButton = new JButton( "Start New Game");
                  southLayout.add (startButton);
                  startButton.addActionListener(this);
                  
                  closeButton = new JButton( "Exit");
                  southLayout.add (closeButton);
                  closeButton.addActionListener(closeButtonListener);
                  
                  // North Layout
                  playerInfo = new JTextArea(5,70);
                  playerInfo.setEditable( false );
                  northLayout.add( new JScrollPane( playerInfo));
                  
                  // Center Layout
                  JPanel imageGrid = new JPanel();
                  imageGrid.setLayout(new GridLayout(8,8,3,3));
                  imageButton = new JButton[64];
                  imageOnButton = new ImageIcon[64];
                  imageNull = new ImageIcon("");      
                  scramble (images);
                  for (int i =0; i < images.length; i++)              
                  {
                        imageButton[i] = new JButton(""+i);             // Create the array of buttons.
                        imageButton[i].addActionListener(this);                  // Add the listener for button clicks.
                        imageGrid.add(imageButton[i]);                              // Add the buttons to the panel.
                        imageOnButton[i] = new ImageIcon(images[i]);      // Create the array of imageIcons.
                  }      
                  
                  
                  do
                  {
                        String playerName = JOptionPane.showInputDialog("Please Enter the Players Name.");
                        String age = JOptionPane.showInputDialog("Enter the Players Age.");
                        int playerAge = Integer.parseInt(age);
                        int playerScore = 0;
                        // Enter Player into Player Array
                        playerArray [lastPlayer] = new Players ( playerName, playerAge, playerScore );
                        playerInfo.append(playerArray [lastPlayer].toString() + "\n");
                        
                        // Prompt for More Players
                        prompt = JOptionPane.showConfirmDialog(null, "Add another Player?");
                                                
                  } while( prompt == JOptionPane.YES_OPTION );
                  
                  border.add(northLayout,BorderLayout.NORTH);
                  border.add(imageGrid,BorderLayout.CENTER);
                  border.add(southLayout,BorderLayout.SOUTH);
                  container.add(border);
                  setSize(800,800);
                  setVisible(true);
            }
            public void actionPerformed(ActionEvent event)
            {
                  for (int i = 0; i < images.length; i++)
                  {
                        if ((event.getSource()== imageButton[i])&& status==1)
                        {
                              imageButton[i].setIcon(imageOnButton[i]);
                              indexOfFirst = i;
                              status = 2;
                        }
                        else if ((event.getSource()== imageButton[i])&& status == 2)
                        {
                              imageButton[i].setIcon(imageOnButton[i]);
                        System.out.println(" "+i+" "+images[i]+" "+indexOfFirst+" "+
                                    images[indexOfFirst]);
                              if(images[i]==(images[indexOfFirst]))
                              {
                                    JOptionPane.showMessageDialog(null,"Match\nSelect Again");
                                    // Add point to player
                                    
                              }
                              else
                              {
                                    JOptionPane.showMessageDialog(null,"Try Again");
                                    imageButton[i].setIcon(imageNull);
                                    imageButton[indexOfFirst].setIcon(imageNull);
                                    
                                    // Switch to next player
                                    if (currentTurn == lastPlayer)
                                    {
                                          currentTurn = 0;
                                          JOptionPane.showMessageDialog(null,"First Player's Turn");
                                    }
                                    else
                                    {
                                          currentTurn++;
                                          JOptionPane.showMessageDialog(null,"Next Player");
                                    }
                              }
                              status = 1;
                        }
                  }      
            }// End actionPerformed.
            public static void scramble(String array[])
             {
                for (int i = 0; i < array.length; i++)
                {
                   swap(array, (int)(Math.random()* 63), (int)(Math.random()* 63));
                }
             }
            public static void swap(String array[], int firstElement, int secondElement)
             {
                String temp = array[firstElement];
                array[firstElement] = array[secondElement];
                array[secondElement] = temp;
             }
      public static void main(String[] args)
      {      
            GameGUI application = new GameGUI();
            application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }//End main.
    class CloseButtonListener implements ActionListener
    {
         public void actionPerformed(ActionEvent evt)
         {
               System.exit(0);
         }
    }
}// End JFrame.
0
Comment
Question by:reefcrazed
  • 6
  • 5
  • 3
  • +2
16 Comments
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16254336
Hi reefcrazed,

Can you add a class variable to the Player class called score?
Then you would have setScore(), getScore(),
Maybe a clearScore, or just do setScore(0).
That sound reasonable?

Joe P
0
 

Author Comment

by:reefcrazed
ID: 16254357
I actually have that setup in the player class.

I just wasn't sure how I could make that increment up.
0
 

Author Comment

by:reefcrazed
ID: 16254364
hehe btw Hey Bogo. I fixed the points for the last question you helped me with. =)
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 17

Assisted Solution

by:BogoJoker
BogoJoker earned 900 total points
ID: 16254384
Why thank you, I remember seeing that. =)
You could increment that like so:

Player p = new Player();
p.setScore( (p.getScore() + 1) );

Or, have a CONSTANT class variable (or multiple) for score increments
p.setScore( (p.getScore() + SCORE_INCREMENT) );

There could be multiple score increments, which is why I considered CONSTANTS.

Joe P
0
 

Author Comment

by:reefcrazed
ID: 16254467
Added this line
       thePlayers.setScore( (thePlayers.getScore() + SCORE_INCREMENT) );

When I run the program and get a match it crashed with a null pointer.

Will the score change automatically in the JTextArea or would I need some way to refresh it after I change the score?
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16254488
1. Make sure that you define SCORE_INCREMENT as a constant in your programm here is the code:
private final int SCORE_INREMENT = 10; // put whatever values you want here, I put 10, a common number

2. You said:
>Will the score change automatically in the JTextArea or would I need some way to refresh it after I change the score?
A JTextArea only changes text when setText() is called.  We did not call setText() yet.  So just add this line, after we set the new score with p.setScore().  I will call the JTextArea txtArea, I don't know your actual name for it but make sure you use the name you gave the textarea in your program:
txtArea.setText(p.getScore());

Joe P
0
 

Author Comment

by:reefcrazed
ID: 16254546
Getting this: " The method setText(String) in the type JTextComponent is not applicable for the arguments (int) "

I set the constant and reconifgured the line to fit my variables.
0
 
LVL 9

Expert Comment

by:Manikandan Thiagarajan
ID: 16254589
could you give me the player class?
0
 

Author Comment

by:reefcrazed
ID: 16254592
// Players Class
public class Players extends Object
{

      private String name;
      int age;
      int score;
      
// Constructor      
public Players ( String playerName,  int playerAge, int playerScore )
      {
      name = playerName;
      age = playerAge;
      score = playerScore;
      }

// Set First Name
public void setName ( String playerName )
      {
      name = playerName;
      }
// return First Name
public String getName ()
      {
            return name;
      }
// Set Last Name
public void setAge ( int playerAge )
      {
      age = playerAge;
      }
// return Last Name
public int getAge ()
      {
            return age;
      }

// Set Genre
public void setScore ( int playerScore )
      {
      score = playerScore;
      }
// return Genre
public int getScore ()
{
      return score;
}
// return String representation of Author object
public String toString ()
      {
            return "Player Name: " + getName () + "\tPlayer Age: " + getAge () +
                  "\t\tPlayer Score: " + getScore();
      }
}// End Players class
0
 
LVL 30

Accepted Solution

by:
Mayank S earned 600 total points
ID: 16254639
>> The method setText(String) in the type JTextComponent is not applicable for the arguments (int)

You are passing an integer to it. You need to pass a string:

textField.setText ( Integer.toString ( yourInt ) ) ;

>> public class Players extends Object

extends Object is not required there.
0
 

Author Comment

by:reefcrazed
ID: 16254647
lol just noticed I forgot to change my comments.
Recycled it from another class i wrote.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16254915
That class should be called 'Player' ;-) A collection of them would be 'Players' or 'Team'
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16257259
> The method setText(String) in the type JTextComponent is not applicable for the arguments (int)
You could do this:
txtArea.setText(Integer.toString(p.getScore()));
or:
txtArea.setText(""+p.getScore());

I normally use the second way, its shorter, its sorta a hack to make that a string.
Joe P

0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16257278
I wouldn't recommend the second method :) its a useless string concatenation (which does not even use StringBuffer, so is worse in performance). It might internally anyway end up trying to convert p.getScore () to a String using Integer.toString () for doing the concatenation.
0
 
LVL 17

Expert Comment

by:BogoJoker
ID: 16257302
Alrighty.  Use Integer.toString()
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16265876
Any reason for a B-grade?
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month15 days, 4 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question