Hi, Im slightly stuck with a java project ive been asked to do. The problem is the game is a simon game so I the computer picks a letter randomly and the player has to copy it, if the player picks the wrong letter in the sequence the game informs the user that they have lost and tells them how many right in the sequence they got. This all works ok but there is a problem with the output sequence during the game, it tell us how large the computers sequence is and what characters it holds but for the players sequence it says 0 for the size and [] for the characters im at a loss to what ive done wrong as the game works apart from that part. Here is the code i have used.

import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.*;



public class ButtonPanel extends JPanel
{
    private JButton[] buttons;
    private int sleepTime = 1000;
    private ArrayList<Character> simonSequence; // Simon's sequence of numbered buttons
    private ArrayList<Character> playerSequence; // sequence pressed by player
    private ImageIcon pressed;
    private int nextClick;
    private boolean playerCorrect; // player correct so far
    private static final Character firstChar = 'A';
    private static final Character lastChar = 'D';
    /** Creates a new instance of ButtonPanel */
    public ButtonPanel()
    {
        buttons = new JButton[4];
        simonSequence = new ArrayList<Character>();
        playerSequence = new ArrayList<Character>();
        
        pressed = createImageIcon("smile.gif"); // icon to show button being pressed
        setLayout(new GridLayout(2,2)); // two rows two columns for the buttons
        Character label = firstChar;
        for (JButton b: buttons)
        {
            b = new JButton("" + label);
            buttons[label - firstChar]= b;
            b.setActionCommand("" + label); // for use in ButtonWatcher
            label++;
            add(b);
            //is this how to create and add a ButtonWatcher for each of the buttons
            b.addActionListener(new ButtonWatcher());  
        }
        
        setButtonsEnabled(true);
    }
    
    
    public class ButtonWatcher implements ActionListener
    {
       public void actionPerformed(ActionEvent b)
       {
          Object clicked = b.getActionCommand();
          if(clicked.equals("A"))
          {
            playerSequence.add('A');
            Utility.playSound(1);
            
          }
          if(clicked.equals("B"))
          {
              playerSequence.add('B');
              Utility.playSound(2);
              
          }
          if(clicked.equals("C"))
          {
             playerSequence.add('C');
             Utility.playSound(3);
          
          }
          if(clicked.equals("D"))
          {
             playerSequence.add('D');
             Utility.playSound(4);  
          } 
        
       }
       
    }
          
   
    
    //returns an ImageIcon or null if the path was invalid
    private ImageIcon createImageIcon(String path)
    {
        java.net.URL imgURL = ButtonPanel.class.getResource(path);
        if (imgURL != null)
        {
            return new ImageIcon(imgURL);
        }
        else
        {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
    
    //reset everything
    public void resetAll()
    {
      
        sleepTime = 1000;
        setNextClick(0);
        playerCorrect = true;
        simonSequence.clear(); // redundant on first use
        playerSequence.clear();
    }
     public void speedUp()
    {
        System.out.println("speeding up");
        sleepTime = (int) (sleepTime / 2);
    }
    public void simonTurn()
    {
        setButtonsEnabled(false);
        addCharToSimonSequence();
        playSimonSequence();
        System.out.println("Simon's turn done");
        setButtonsEnabled(true);
    }
    
    //enable or disable all buttons
    private void setButtonsEnabled(boolean v)
    {
        for (JButton b: buttons)
        {
            b.setEnabled(v);
        }
    }
    
    private void addCharToSimonSequence()
    {
        simonSequence.add(nextChar());
        System.out.println("current sequence is " + simonSequence);
    }
    
    // choose the next button for Simon's sequence
    private Character nextChar()
    {
        int i = firstChar + (int) (4 * Math.random());
        return (char) i;
    }
    
    //play Simon's sequence - plus sounds
    private void playSimonSequence()
    {
        Utility.pause(sleepTime);
        for(Character i: simonSequence)
        {
            buttons[i-firstChar].setIcon(pressed);
            Utility.playSound(i-firstChar+1);
            Utility.pause(sleepTime);
            buttons[i-firstChar].setIcon(null);
            Utility.pause(sleepTime);
        }
        sleepTime = (int) (sleepTime * 0.95); // get progressively faster
    }
    
    public boolean playerTurn()
    {
        resetPlayer(); // so start storing from first player click
        waitForCompletePlayerSequence();
        return checkSequencesMatch();
    }
    
    //to support playerTurn()
    private boolean checkSequencesMatch()
    {
        // check sequences
        playerCorrect = true;
        int checkIndex = 0;
        while (checkIndex < playerSequence.size() && playerCorrect)
        {
            int seqNext = simonSequence.get(checkIndex);
            int playerNext = playerSequence.get(checkIndex);
            if (seqNext != playerNext)
            {
                System.out.println("a click didn't match ");
                playerCorrect = false; // mismatch - so stop checking
            }
            checkIndex ++;
        }
        return playerCorrect;
    }
    
    //just resets player
    private void resetPlayer()
    {
        setNextClick(0);
        playerSequence.clear();
        playerCorrect = true;
    }
    
    private void setNextClick(int v)
    {
        nextClick = v;
    }
    
   
    
    private void waitForCompletePlayerSequence()
    {
        System.out.println("player sequence " + playerSequence);
        System.out.println("sequence length" + simonSequence.size());
        System.out.println("player length " + playerSequence.size());
        do
        {
            System.out.println("in waitForcompletePlayerSequence loop");
            Utility.pause(500);//note this is in the main thread
        }
        while (playerSequence.size() < simonSequence.size());
    }
    
     public ArrayList<Character> getPlayerSequence()
    {
        return playerSequence;
    }
       
}
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.*;


public class GameFrame extends JFrame
{
    private MessagePanel messagePanel; //for writing messages underneath the buttons
    private ButtonPanel buttonPanel; // for buttons
    
    private JMenuBar bar;
    private JMenu menuOptions;
    private JMenuItem speed;
    private JMenuItem restart;
    
    private boolean finished;
    private boolean restarting;
    
    /** Creates a new instance of GameFrame */
    public GameFrame()
    {
        finished = false;
        restarting = false;
        setSize(300,300);
        setTitle("SIMON - Repeat after me!");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(2,1));
        
        buttonPanel = new ButtonPanel(); // button area
        messagePanel = new MessagePanel(); // message area
        add(buttonPanel);
        add(messagePanel);
        
        //set up menu
        bar = new JMenuBar();
        menuOptions = new JMenu("Edit");
        speed = new JMenuItem("Speed up the game");
        restart = new JMenuItem("Restart");
        menuOptions.add(speed);
        menuOptions.add(restart);
        
        speed.setEnabled(true);
        restart.setEnabled(true);
        
        setJMenuBar(bar);
        bar.add(menuOptions);
        // TODO: add listeners for the menu options
        speed.addActionListener(new MenuSelection());
        restart.addActionListener(new MenuSelection());

        
    }
    
    //play the game
    public void play()
    {
        Utility.playSound(0);// initial gong to get started
        messagePanel.setText("Welcome to SIMON - let's start!");
        Utility.pause(3000);
        while(!finished)
        {
            messagePanel.setText("Here comes the sequence of " + (buttonPanel.getPlayerSequence().size() + 1));
            buttonPanel.simonTurn();
            messagePanel.setText("Your turn!");
            speed.setEnabled(true);
            restart.setEnabled(true);
            finished = !buttonPanel.playerTurn();
            if (!finished && !restarting)
            {
                messagePanel.setText("Well done! Now get ready for the next turn!");
                Utility.pause(2000);
            }
            if (restarting)
            {
                restarting = false;
                messagePanel.setText("restarting");
                Utility.pause(5000);
            }
            speed.setEnabled(false);
            restart.setEnabled(false);
        }
        // finish with feedback on score
        messagePanel.showEndMessages(buttonPanel.getPlayerSequence().size()-1);
        Utility.pause(100000);
        System.exit(0);
    }
    
    
     private class MenuSelection implements ActionListener
     {
        public void actionPerformed(ActionEvent e)
        {
           Object menuOptions = e.getSource();
           ButtonPanel button = new ButtonPanel();
           if(menuOptions == restart)
           {
             button.resetAll();
           }
           else if(menuOptions == speed)
           {
              button.speedUp();
           }
        }
     }
    
    
}
public class Main
{
   
    public static void main(String[] args)
    {
       GameFrame game = new GameFrame();
       game.setVisible(true);
       System.out.println("about to invoke play");
       game.play();  
    }
    
}
import java.awt.Graphics;
import javax.swing.JPanel;

public class MessagePanel extends JPanel
{
    private String text;
    
    
    /** Creates a new instance of MessagePanel */
    public MessagePanel()
    {
        text = "";
    }
    
    
    public void paintComponent(Graphics g)
    {
        
       super.paintComponent(g);
       g.drawString(text,50,50);
        
    }
    
    public void setText(String s)
    {
        
       this.text = s;
       repaint();
    }
    
    public void showEndMessages(int howManyCorrect)
    {
        
       Utility.pause(3000);
       setText("‘Whoops, got one wrong there!’");
       Utility.pause(3000);
       setText("You managed " + howManyCorrect + " correctly!");
       Utility.pause(3000);
       switch (howManyCorrect)
      {
         case 0: 
         case 1: 
         case 2: setText("Oh dear, not very good :-("); break;
         case 3: 
         case 4: 
         case 5: setText("Okay for a beginner"); break;
         case 6: 
         case 7: 
         case 8: setText("Pretty good!"); break;
         case 9: 
         case 10: 
         case 11: setText("Very good! :-)"); break;
         case 12: 
         case 13: 
         case 14: setText("Excellent! ;-)"); break;
         default: setText("Amazing!"); break;
        
      }
       
    }

   public java.awt.Component add(java.awt.Component comp, int index)
   {
      java.awt.Component retValue;
      
      retValue = super.add(comp, index);
      return retValue;
   }
    
}
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.MalformedURLException;


public class Utility
{
    
    private static  String[] sounds = {"gong.au", "bleep_1.au", "cork.au", "ding.au", "beep_1.au"};
    private static  java.io.File currentDir = new java.io.File(System.getProperty("user.dir"));
    
    public static void pause(int ms)
    {
        try
        {
            Thread.sleep(ms);
        }
        catch (InterruptedException e)
        {
            System.out.println("thread interrupted");
        }
    }
    
    //this method can be invoked from the event dispatching thread (or elsewhere)
    //this method will play the sound whose name is stored at index num of the sounds array.
    public static void playSound(int num)
    {
        AudioClip clip = null;
        
        if (num < 0 || num > sounds.length)
            return;
        try
        {
            clip = Applet.newAudioClip(new java.net.URL(currentDir.toURL(),sounds[num]));
            clip.play();
        }
        catch (MalformedURLException e)
        {
            System.out.println("bad url " + e);
        }
        pause(250); // give the sound a chance to play
    }   
    
}

Recommended Answers

All 12 Replies

Are you just wanting it to update as the wait loop runs? Move it into the loop

private void waitForCompletePlayerSequence()
    {
        do
        {
            System.out.println("player sequence " + playerSequence);
            System.out.println("sequence length" + simonSequence.size());
            System.out.println("player length " + playerSequence.size());
            System.out.println("in waitForcompletePlayerSequence loop");
            Utility.pause(500);//note this is in the main thread
        }
        while (playerSequence.size() < simonSequence.size());
    }

No sorry, on the output screen im getting results like this

player sequence []
sequence length2
player length 0

When it should be
player sequence
sequence length2
player length 1

Put the println() statements after your while() loop if you just want to see the final result after the player turn.

private void waitForCompletePlayerSequence()
    {
        do
        {
            // these if you want to update as letters are clicked
            System.out.println("player sequence " + playerSequence);
            System.out.println("sequence length" + simonSequence.size());
            System.out.println("player length " + playerSequence.size());

            System.out.println("in waitForcompletePlayerSequence loop");
            Utility.pause(500);//note this is in the main thread
        }
        while (playerSequence.size() < simonSequence.size());

        // these if you want to see the final result
        System.out.println("player sequence " + playerSequence);
        System.out.println("sequence length" + simonSequence.size());
        System.out.println("player length " + playerSequence.size());
    }

Thank you so much

I was wondering if you could tell me where you got the "smile.gif" icon. Is it a file on your computer? How would I include that in my code? Thanks!

hey lesmith543
you have to put the file into C:\Users\abode\Documents\NetBeansProjects\JavaApplication6\src\javaapplication6

sorry ^_^
u can start from documents

How come errors appear when I run it?

Because you did something wrong.

the error says: class, interface or enum expected under utility

"under utility" tells us nothing, especially when the text utility does not appear anywhere in the original program.
You need to post the complete exact error message (not just your version of it) and the exact line of the source code that it refers to.

commented: do you know how to fix the restart button. its not working +0

the restart button is not working :(((((((((

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.