Alright this consists of two problems I have with my recreation of Snake game in GUI. The first is that when the game ends, I want a pop up that gives the users the option to replay or quit. However, when the snake hits the tail or board, the message continually pops up. So in essence, the gameOver method repeats itself over and over.
private void checkDotCollision () { for (int z = dots; z > 0; z--) { if ((z > 2) && (x[0] == x[z]) && (y[0] == y[z])) { inGame = false; gameOver (); } } if (y[0] == screenHeight) { inGame = false; gameOver (); } if (y[0] == 0) { inGame = false; gameOver (); } if (x[0] == screenWidth) { inGame = false; gameOver (); } if (x[0] == 0) { inGame = false; gameOver (); } } private void gameOver () { if (inGame == false) { JFrame gameOverFrame = new JFrame(); gameOverFrame.setVisible(true); JTextField gameOverPrompt = new JTextField(30); gameOverPrompt.setText("Game Over. Would you like to play again?"); gameOverPrompt.setEditable(false); JButton buttonReplay = new JButton("Replay"); buttonReplay.addActionListener( // New actionListener which has an // inner class and method within it. new ActionListener() { public void actionPerformed(ActionEvent e) { Initialize(); } }); JButton buttonQuit = new JButton("Quit"); buttonQuit.addActionListener( // New actionListener which has an // inner class and method within it. new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit (0); } }); gameOverFrame.add (gameOverPrompt); gameOverFrame.add (buttonReplay); gameOverFrame.add (buttonQuit); gameOverFrame.setLayout(new FlowLayout()); gameOverFrame.pack (); inGame = true; }else if (inGame == true) { } }
Also it seems that when I do hit the replay button, the snake seems to speed up and I'm not sure whether it's a timer issue or not. When I replay the game (jumping back to the Initialize method), the snake seems to move faster every time.
private void Initialize () { //sets the amounts of dots on screen to start at 1 dots = 1; for (int z = 0; z < dots; z++) { x[z] = 50 - z * 10; y[z] = 50; } //jumps to randomEdibleDot method randomEdibleDot (); //starts the timer to set the speed at which the snakeHead travels timer = new Timer (delay, this); timer.start (); }
I am a beginner at coding and any help is appreciated. Thanks.