Tracking score in game

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.
reefcrazedAsked:
Who is Participating?
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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
 
BogoJokerCommented:
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
 
reefcrazedAuthor Commented:
I actually have that setup in the player class.

I just wasn't sure how I could make that increment up.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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.

 
reefcrazedAuthor Commented:
hehe btw Hey Bogo. I fixed the points for the last question you helped me with. =)
0
 
BogoJokerCommented:
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
 
reefcrazedAuthor Commented:
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
 
BogoJokerCommented:
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
 
reefcrazedAuthor Commented:
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
 
Manikandan ThiagarajanSenior consultantCommented:
could you give me the player class?
0
 
reefcrazedAuthor Commented:
// 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
 
reefcrazedAuthor Commented:
lol just noticed I forgot to change my comments.
Recycled it from another class i wrote.
0
 
CEHJCommented:
That class should be called 'Player' ;-) A collection of them would be 'Players' or 'Team'
0
 
BogoJokerCommented:
> 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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
BogoJokerCommented:
Alrighty.  Use Integer.toString()
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Any reason for a B-grade?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.