Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Simon game, still not working 2 months in.

  1. #1
    Junior Member
    Join Date
    Jan 2014
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Angry Simon game, still not working 2 months in.

    Working on simon says game in java. Program compiles fine, but when playing game, gameplay is not working as intended. I've been trying to find the problem for more than two weeks, but I can't find it. I've added code to the program to print to the console when the problematic parts of the program are running. I have done everything I know to do, and I'm really frustrated. Can someone PLEASE take a look, and see if they can help me? I put the entire program so that you can run it yourselves while looking.



        package simon2;
     
        import javax.swing.*;
        import javax.swing.Timer;
        import java.util.*;
        import java.awt.*;
        import java.awt.Color.*;
        import java.awt.event.*;
        import java.io.File;
        import javax.imageio.ImageIO;
        import java.io.IOException;
     
        // TODO:
        // ICON IMAGE TESTING
        // Button sounds.
     
        /**
         * Main Class.
         * Just creates GUI.
         * 
         */
        public class Simon2 
        {
            public static void main(String[] args) 
            {
                // Creating main game window.
                JFrame gameWindow = new JFrame("Simon  -  Created by Chris Mailloux");
                gameWindow.setVisible(true);
                gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                gameWindow.setSize(600, 600);
                gameWindow.setResizable(true);
                gameWindow.setLocation(DEFAULT_HORIZONTAL_LOCATION, DEFAULT_VERTICAL_LOCATION);
     
                // Creating panel to support border layout.
                JPanel borderPanel = new JPanel();
                borderPanel.setLayout(new BorderLayout());
                gameWindow.add(borderPanel);
     
                // Creating menu panel.
                JPanel menuPanel = new JPanel();
                borderPanel.add(menuPanel, BorderLayout.NORTH);
                menuPanel.setBackground(Color.BLACK);
                // Adding buttons to menu panel.
                menuPanel.add(startButton);
                menuPanel.add(scoreDisplay);
                menuPanel.add(highScoreDisplay);
                // Configuring buttons
                scoreDisplay.setEnabled(false);
                highScoreDisplay.setEnabled(false);
                startButton.setFocusable(false);
                // Styling buttons
                startButton.setBackground(Color.BLUE);
                scoreDisplay.setBackground(Color.BLACK);
                highScoreDisplay.setBackground(Color.BLACK);
                startButton.setForeground(Color.WHITE);
     
                // Creating buttonsPanel.
                JPanel buttonsPanel = new JPanel();
                borderPanel.add(buttonsPanel, BorderLayout.CENTER);
                buttonsPanel.setBackground(Color.BLACK);
                buttonsPanel.setLayout(new GridLayout(2, 2, 20, 20));
                // Adding game buttons.
                buttonsPanel.add(greenButton);
                buttonsPanel.add(redButton);
                buttonsPanel.add(blueButton);
                buttonsPanel.add(yellowButton);
                // Disabling button focus ability.
                greenButton.setFocusable(false);
                redButton.setFocusable(false);
                blueButton.setFocusable(false);
                yellowButton.setFocusable(false);
                // Styling buttons.
                greenButton.setBackground(Color.GREEN);
                redButton.setBackground(Color.RED);
                blueButton.setBackground(Color.BLUE);
                yellowButton.setBackground(Color.YELLOW);
                // Attaching actionListeners to buttons
                startButton.addActionListener(startButtonListener);
                greenButton.addActionListener(greenButtonListener);
                redButton.addActionListener(redButtonListener);
                blueButton.addActionListener(blueButtonListener);
                yellowButton.addActionListener(yellowButtonListener);
     
            }
     
                    // Creating ActionListeners for buttons.
                // Start button.
                static ActionListener startButtonListener = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evtStart)
                    {
                        ButtonActions.startAction();
                    }
                };
                // Green button.
                static ActionListener greenButtonListener = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evtGreen)
                    {
                        ButtonActions.greenAction();
                    }
                };
                // Red button.
                static ActionListener redButtonListener = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evtRed)
                    {
                        ButtonActions.redAction();
                    }
                };
                // Blue button.
                static ActionListener blueButtonListener = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evtBlue)
                    {
                        ButtonActions.blueAction();
                    }
                };
                // Yellow button.
                static ActionListener yellowButtonListener = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evtYellow)
                    {
                        ButtonActions.yellowAction();
                    }
                };
     
     
     
            // Class methods
     
            // Accessor Methods
            static String getCurrentScore()
            {
                return String.valueOf(Game.currentScore);
            }
            static String getHighScore()
            {
                return String.valueOf(Game.highScore);
            }
     
     
     
            // End class methods
     
     
            // Button objects creation
            static JButton startButton = new JButton("Start");
            static JButton scoreDisplay = new JButton
                ("Current score: " + getCurrentScore());
            static JButton highScoreDisplay = new JButton
                ("High Score: " + getHighScore());
            static JButton greenButton = new JButton();
            static JButton redButton = new JButton();
            static JButton blueButton = new JButton();
            static JButton yellowButton = new JButton();
     
     
     
            // Class variables
            private static final Dimension screenSize = 
                    Toolkit.getDefaultToolkit().getScreenSize();
            private static final int DEFAULT_HORIZONTAL_LOCATION = 
                    ((screenSize.width - 600) / 2);
            private static final int DEFAULT_VERTICAL_LOCATION = 
                    ((screenSize.height - 600) / 2);
     
     
        }
     
        /**
         * Handles actions of buttons.
         * Creates timers and ActionListeners for each button to add delay.
         */
        class ButtonActions
        {
            static int delay = 400;
     
            // Start Button
            static void startAction()
            {        
                Game.startGame();
            }
            // Green Button
            static void greenAction()
            {
                ActionListener delayer1 = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evt1)
                    {
                        Simon2.greenButton.setBackground(Color.GREEN);
                        if (Game.isPlayerTurn)
                        {
                            Simon2.greenButton.setEnabled(true);
                        }
                    }
                };
                Timer timer1 = new Timer(delay, delayer1);
                timer1.setRepeats(false);
                Simon2.greenButton.setEnabled(false);
                Simon2.greenButton.setBackground(Color.WHITE);
                if (Game.isPlayerTurn)
                {
                    Game.check("Green");
                                System.out.println("Passing green to check method.");
                }
                timer1.start();
            }
            // Red Button
            static void redAction()
            {
                ActionListener delayer2 = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evt2)
                    {
                        Simon2.redButton.setBackground(Color.RED);
                        if (Game.isPlayerTurn)
                        {
                            Simon2.redButton.setEnabled(true);
                        }
                    }
                };
                Timer timer2 = new Timer(delay, delayer2);
                timer2.setRepeats(false);    
                Simon2.redButton.setEnabled(false);
                Simon2.redButton.setBackground(Color.WHITE);
                if (Game.isPlayerTurn)
                {
                    Game.check("Red");
                                System.out.println("Passing red to check method.");
                }
                timer2.start();
            }
            // Blue Button
            static void blueAction()
            {
                ActionListener delayer3 = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evt3)
                    {
                        Simon2.blueButton.setBackground(Color.BLUE);
                        if (Game.isPlayerTurn)
                        {
                            Simon2.blueButton.setEnabled(true);
                        }
                    }
                };
                Timer timer3 = new Timer(delay, delayer3);
                timer3.setRepeats(false);
                Simon2.blueButton.setEnabled(false);
                Simon2.blueButton.setBackground(Color.WHITE);
                if (Game.isPlayerTurn)
                {
                    Game.check("Blue");
                                System.out.println("Passing Blue to check method");
                }
                timer3.start();
            }
            // Yellow Button
            static void yellowAction()
            {
                ActionListener delayer4 = new ActionListener()
                {
                    public void actionPerformed(ActionEvent evt4)
                    {
                        Simon2.yellowButton.setBackground(Color.YELLOW);
                        if (Game.isPlayerTurn)
                        {
                            Simon2.yellowButton.setEnabled(true);
                        }
                    }
                };
                Timer timer4 = new Timer(delay, delayer4);
                timer4.setRepeats(false);
                Simon2.yellowButton.setEnabled(false);
                Simon2.yellowButton.setBackground(Color.WHITE);
                if (Game.isPlayerTurn)
                {
                    Game.check("Yellow");
                                System.out.println("Passing yellow to check method.");
                }
                timer4.start();
            }
     
        }
     
        /**
         * Handles game logic.
     
         */
        class Game
        {
            static Timer simonTurnTimer;
     
            static void startGame()
            {
                pattern.clear();
                isPlayerTurn = false;
                currentScore = 0;
                gamePlay();
            }
     
            static void gamePlay()
            {
                if (isPlayerTurn == true)
                {
                    playerTurn();
                }
                else if (isPlayerTurn == false)
                {
                    simonTurn();
                }
                else
                {
                    System.out.println("Error: Player turn has not been assigned,"
                            + " or has value other than a boolean.");
                }
                return; // test
            }
     
            private static void playerTurn()
            {
                System.out.println("PlayerTurn");
                // First, make sure buttons are enabled.
                Simon2.greenButton.setEnabled(true);
                Simon2.redButton.setEnabled(true);
                Simon2.blueButton.setEnabled(true);
                Simon2.yellowButton.setEnabled(true);
                // Since this should only be called once per turn, 
                // set iterator to 0 to initialize turn.
                iterator = 0;
            }
     
            // Test.
            static  void delayTurn()
            {
                System.out.println("Delaying turn");
                simonTurnTimer = new Timer(simonTurnDelay, simonListener);
                simonTurnTimer.setRepeats(false);
                simonTurnTimer.start();
            }
     
            private static void simonTurn()
            {
                System.out.println("Simon's turn");
                // First, disable buttons.
                Simon2.greenButton.setEnabled(false);
                Simon2.redButton.setEnabled(false);
                Simon2.blueButton.setEnabled(false);
                Simon2.yellowButton.setEnabled(false);
                // Initialize...
                iterator = 0;
                // Simon adds random color to pattern
                randInt = (int) (Math.random() * 4);
                System.out.println("RandInt: " + randInt);
                if (randInt == 0)
                {
                    pattern.add("Green");
                    System.out.println("Adding green");
                }
                else if (randInt == 1)
                {
                    pattern.add("Red");
                    System.out.println("Adding red");
                }
                else if (randInt == 2)
                {
                    pattern.add("Blue");
                    System.out.println("Adding blue");
                }
                else if (randInt == 3)
                {
                    pattern.add("Yellow");
                    System.out.println("Adding yellow");
                }
                else
                {
                    System.out.println("Error: Random generation has failed.");
                }
                // Simon shows the new pattern...
                showPattern();
                System.out.println("Called showpattern.");
                // Now, it is the player's turn.
                isPlayerTurn = true;
                gamePlay();
            }
     
            // Just kinda thrown in here randomly, must reorganize.
     
            static ActionListener simonListener = new ActionListener()
            {
              public void actionPerformed(ActionEvent simonTurnDelayEvent)
              {
                  simonTurn();
              }
            };
     
                // BUGNOTE: Not sure if need to repaint currentScore and/or highScore
            static void check(String lastInput)
            {
                if (lastInput.equals(pattern.get(iterator)))
                {
                    iterator++;
                    currentScore++;
                    System.out.println("Updating current score and iterator");
                    Simon2.scoreDisplay.repaint(); 			// Possibly unneccessary
                    if (currentScore > highScore)
                    {
                        highScore++;
                        System.out.println("Updated highscore?");
                        Simon2.highScoreDisplay.repaint(); 	// Possibly unneccessary
                    }
                    if (iterator == getPatternLength())
                    {
                        delayTurn(); // test
                        isPlayerTurn = false;
                    }
                }
                else
                {
                    gameOver();          
                }
            }
            static int getPatternLength()
            {
                patternLength = pattern.size();
                System.out.println("Get pattern length method"
                        + " called. Length : " + patternLength);
                return patternLength;
            }
     
            static void showPattern()
            {
                iterator = 0;
                // Activate each button based on pattern and iterator traversal.
                while (iterator < getPatternLength())
                {
                    if (pattern.get(iterator) == "Green")
                    {
                        ButtonActions.greenAction();
                        System.out.println("Called greenAction from show");
                    }
                    else if (pattern.get(iterator) == "Red")
                    {
                        ButtonActions.redAction();
                        System.out.println("Called redAction from show");
                    }
                    else if (pattern.get(iterator) == "Blue")
                    {
                        ButtonActions.blueAction();
                        System.out.println("Called blueAction from show");
                    }
                    else if (pattern.get(iterator) == "Yellow")
                    {
                        ButtonActions.yellowAction();
                        System.out.println("Called yellowAction from show");
                    }
                    else
                    {
                        System.out.println("Error: showPattern method has failed. Possible bad value.");
                    }
                iterator++;
                }
            }
     
            static void gameOver()
            {
                System.out.println("Game over");
                // Need to play gameOver sound
                // Need to write highscore to file
            }
     
            // Class variable declarations.
            static ArrayList<String> pattern = new ArrayList<String>();
            private static int patternLength;
            static int simonTurnDelay = 1000; // test
            static int randInt;
            static int iterator;
            static int currentScore;
            static int highScore;
            static boolean isPlayerTurn;
     
        }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Simon game, still not working 2 months in.

    Welcome to the forum!

    Can you please describe what's wrong? What should it do that it's not doing? What does it do that it shouldn't? Give us something to work with.

  3. The Following User Says Thank You to GregBrannon For This Useful Post:

    HCBPshenanigans (January 29th, 2014)

  4. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Simon game, still not working 2 months in.

    "not working" is not a helpful description of the problem. What exactly is happening? What should be happening? Can you provide us with the output log?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    HCBPshenanigans (January 29th, 2014)

  6. #4
    Junior Member
    Join Date
    Jan 2014
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Simon game, still not working 2 months in.

    It's supposed to start by generating a random color, adding to pattern and then showing the pattern before passing control to the player. It (seems) to do this fine. The player then makes a move, but it appears the function to check input ends up running twice at this point, and the game does not continue.

    I know I'm not explaining it well, but It will make plenty more sense if you throw the code into a file and run it. Really tired, so sorry if some answers are incoherent or leave out key stuff, I will answer any questions in an attempt to get this working.

  7. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Simon game, still not working 2 months in.

    I'm going to take a shot in the dark and assume what you are really doing here is not what you intend to do:
    if (pattern.get(iterator) == "Green")
    Compare Strings with .equals() not ==
    if (pattern.get(iterator).equals("Green"))
    Change that on all of your if statements, and tell me if anything changes.


    EDIT:
    Also, the final else statement in this section is unreachable (meaning you don't need it, because you can never get there):
    if (isPlayerTurn == true)
                {
                    playerTurn();
                }
                else if (isPlayerTurn == false)
                {
                    simonTurn();
                }
                else // <----- You don't need this else block, isPlayerTurn can only be true or false
                {
                    System.out.println("Error: Player turn has not been assigned,"
                            + " or has value other than a boolean.");
                }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. The Following User Says Thank You to aussiemcgr For This Useful Post:

    HCBPshenanigans (January 29th, 2014)

  9. #6
    Junior Member
    Join Date
    Jan 2014
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Simon game, still not working 2 months in.

    Now, its working better. It is now showing the pattern, but it is not pausing in between flashing each button, (all are just flashing at once), and I have code that should handle that, but apparently it isn't. Also, highScore and currentScore displays are not updating.

    --- Update ---

    Any ideas?

  10. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Simon game, still not working 2 months in.

    2 months you've been working on this and now you're so impatient. What are your thoughts?

  11. #8
    Junior Member
    Join Date
    Jan 2014
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Simon game, still not working 2 months in.

    Sorry, again, tired, so if I'm a little impatient, I apologize. My thoughts on the score displays, I have no idea. It should be working. On the timing, I know I need to implement some kind of method that delays it, but I'm not sure how to best do it.

Similar Threads

  1. Key presses in game not working.
    By AvivC in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 26th, 2014, 06:20 AM
  2. problem with enum (int to months)
    By mickey2012 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 19th, 2012, 10:59 PM
  3. numbered months
    By JavaN00b101 in forum Java Theory & Questions
    Replies: 5
    Last Post: February 8th, 2012, 01:13 PM