-3

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 );
    } 

      }
    }
 }
Mia
  • 3
  • 1
  • Why won't you implement another KeyListener? – xenteros May 07 '18 at 19:19
  • What is your game about? Could you also provide Target and Ball implementation? – Sergei Sirik May 07 '18 at 19:20
  • Hey - welcome to SO. Could you describe what you've tried in a little more detail? E.g. "I've tried to use code to reset it" - what did you try, and why didn't it work? – MyStackRunnethOver May 07 '18 at 19:21
  • Side issue: Fix your paintComponent method -- call the `super.paintComponent(g);` on the first line of your override. – Hovercraft Full Of Eels May 07 '18 at 19:23
  • @MyStackRunnethOver I've looked over pretty much all of the "how to reset java" pages and I've tried to use the code as a reference but I don't think I'm doing it correctly (probably because the code is more complicated than I can understand) and I usually get the error "cannot find symbol". I found on one page code that said: void restartGame() { panel = new GamePanel(); remove(panel); add(panel); revalidate(); but that just gave me the error I previously spoke about. – Mia May 07 '18 at 19:33
  • These statements suggest that you're trying to do an advanced corner of Java -- event-driven GUI programs before understanding the basics well, especially that you're getting a cannot-find-symbol error. Do go through your Java text, notes and tutorials. It won't be wasted effort. As for "resetting the GUI" that all depends on how the program is wired together. You will want to get it back to its initial conditions somehow. There is no one-size-fits-all solution here. – Hovercraft Full Of Eels May 07 '18 at 19:43
  • @xenteros What would implementing another KeyListener do? – Mia May 07 '18 at 19:43
  • @MyStackRunnethOver I wish I had java notes, but unfortunately, the class I'm in doesn't have notes and doesn't really explain important parts of java so I'm just left trying to figure these things out on my own, but thanks for your help! – Mia May 07 '18 at 19:48

1 Answers1

-1

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();
LordScrat
  • 180
  • 1
  • 10
  • Thank you for your code!! I put it in, but I'm getting a "cannot find symbol" for the variable "Keyboard". Do you know how to fix this? – Mia May 07 '18 at 19:42
  • you have to add it as a key listener in your frame. `frame.addKeyListener(new Keyboard());` – LordScrat May 07 '18 at 21:09
  • Super sorry to be asking another question but how do I add it as a key listener? I added that line right below my timer and I am still getting the error "cannot find symbol" for the "frame" and "keyboard". Did I miss importing something? edit: I tried instantiating the keyboard like a timer to see if that'd work but it gave me the same error. – Mia May 08 '18 at 03:25
  • You have to use your own frame for that, in this case its the game itself, the JPanel, so you probably have to do something like `this.addKeyListener(new Keyboard());` in your constructor. But I'm not sure in your case, cause I used javafx instead of swing and awt. – LordScrat May 08 '18 at 05:51
  • I'm still confused on what code I'm supposed to be adding and where. Could you explain a little more. Thanks – Mia May 09 '18 at 03:22