Search code examples
javajgrasp

How do I restart a game in java by pushing a key?


I'm a beginner at java and can't figure out how to restart my game. I've looked at other posts but none work/I can't figure out the code. How do I write the code to restart the game by pushing "y" or "n"? I've tried to use code to reset it, but it didn't understand the code. Maybe I'm not importing the right things?

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


public class Game extends JPanel
{
   private static final int FRAME = 400;
   private static final Color BACKGROUND = new Color(50, 150, 255);  
   private BufferedImage myImage;
   private Graphics myBuffer;
   private Ball ball;
   private Target tar;
   private Timer t; 
   private int hits;


   public Game()
   {

      // instantiate myImage and myBuffer
      myImage =  new BufferedImage(FRAME, FRAME, BufferedImage.TYPE_INT_RGB);
  myBuffer = myImage.getGraphics();
  myBuffer.setColor(BACKGROUND);
  myBuffer.fillRect(0, 0, FRAME,FRAME);

  // Randomly places the ball in the middle of the screen away from any edge
  int xPos = (int)(Math.random()*(FRAME-100) + 50);
  int yPos = (int)(Math.random()*(FRAME-100)+ 50);


   // instantiate the Ball object

  ball = new Ball(xPos, yPos, 50, Color.BLACK);

  // instantiate the target object
   tar = new Target();

  // instantiate the hits counter object
  hits =0;

  // instantiate the Timer object and start it
  // Screen refreshes every 5 milliseconds (1/200 second)
  t = new Timer(5, new Listener());
  t.start();
  addKeyListener(new Key());
  setFocusable(true);

   }


    /**
   * Draws the current state of the image on the screen.
   */ 
   public void paintComponent(Graphics g)
   {
     g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);  
   }




   /**
    * The target jumps around the screen, and the ball 
    * tries to catch it. Every time they collide, the hit increases
    * by one. Once the score is greater than 5, the game stops.
    */
       private class Listener implements ActionListener
   {
      public void actionPerformed(ActionEvent e)
      { 
         myBuffer.setColor(BACKGROUND);
     myBuffer.fillRect(0,0,FRAME,FRAME);
     collide(ball, tar);
     ball.draw(myBuffer);
     tar.draw(myBuffer);
     tar.bounce();
     myBuffer.setColor(Color.BLACK);
     myBuffer.setFont(new Font("Monospaced", Font.BOLD, 24));
     myBuffer.drawString("Count: " + hits, FRAME - 150, 25);
     if(hits==5)
     {
       t.stop();
     }

     repaint();
  }


    }

     private void collide(Ball b, Target tar)
   {
      double d = distance(b.getX(), b.getY(), tar.getX(), tar.getY()); 

      if (d <= b.getRadius() + tar.getRadius())
  {

    tar.jump(FRAME, FRAME);     
    hits ++;    
  } 

 }





   /**
 * Finds the distance between two points using the distance formula
 * @param x1 the x-coordinate of the first object
 * @param y1 the y-coordinate of the first object
 * @param x2 Comment...
 * @param y2 Comment...
 * @return
 */
       private double distance(double x1, double y1, double x2, double y2)
   {
      double dist = 0;      

      dist = Math.sqrt( Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));


      return dist;   
   }

 //keys move the ball
  private class Key extends KeyAdapter
 {
  public void keyPressed(KeyEvent e)
  {

    if(ball.getY() > 15)
     {
      if(e.getKeyCode() == KeyEvent.VK_W)
      ball.setY( ball.getY()-30 );
     }
    if(ball.getY() < 385)
    {
      if(e.getKeyCode() == KeyEvent.VK_S)
      ball.setY( ball.getY()+30 );
    } 
    if(ball.getX() > 15)
    {
      if(e.getKeyCode() == KeyEvent.VK_A)
      ball.setX( ball.getX()-30 );
    } 
    if(ball.getX() < 385)
    {
      if(e.getKeyCode() == KeyEvent.VK_D)
      ball.setX( ball.getX()+30 );
    } 

      }
    }
 }

Solution

  • I would advise you to use a Keyboard class. Here is an old one from me:

    package FishGame;
    
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    /**
     *
     * @author alexr
     */
    public class Keyboard implements KeyListener {
        private static boolean[] keys = new boolean[1024];
    
        public static boolean isKeyDown(int keyCode) {
            if(0 <= keyCode && keyCode < keys.length) 
                return keys[keyCode];
    
            return false;
        }
    
        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if(0 <= keyCode && keyCode < keys.length) 
                keys[keyCode] = true;
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if(0 <= keyCode && keyCode < keys.length) 
                keys[keyCode] = false;
        }
    
        @Override
        public void keyTyped(KeyEvent e) {}
    
    }
    

    And import the few keys you use in your game like so:

    import static java.awt.event.KeyEvent.VK_R;
    

    And then use it in your gamestate:

    if(Keyboard.isKeyDown(VK_R) && Main.state != Main.STATE.MENU) 
        Main.restartGame();