如何向游戏显示时间

时间:2017-01-19 17:25:54

标签: java swing time

我正在制作一款正在下降的方形游戏。我需要有一个分数系统,但我不知道如何整合并将其显示在游戏框架上。

我的问题是如何制作一个向上计数的计时器并将其实时显示在我的游戏框架上。

我的代码:

package GamePackage;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import javax.swing.ImageIcon;

public class Game extends JPanel { 

    //changing these values will change the size of the game, while still remaining functional
    //within the size limit specified.
    public static final int WINDOW_WIDTH = 875;
    public static final int WINDOW_HEIGHT = 720;
    private Timer countdownTimer;

    private javax.swing.JLabel lblTimer;
    private String Highscore = "";

    private int count;
    int Health  = 1;

    //Creates a Square object Array
    Square[] squareArray = new Square[20];
    //Triangle[] TriangleArray = new Triangle[10];

   Player thePlayer = new Player();


    public Game() {

        //initializes square objects

        for (int i = 0; i < squareArray.length; i++)
            squareArray[i] = new Square();


    }

     public static void music(){
        try{
            AudioStream Music = new AudioStream (new FileInputStream("/SplashDemoPackage/URF.wav"));
            AudioPlayer.player.start(Music);
        }catch (IOException error){}
    }

   private void StartGame(){
               count = 14;
         countdownTimer = new Timer(1000,new ActionListener() {
             public void actionPerformed(ActionEvent e) {
               lblTimer.setText(Integer.toString(count));
               count = count -1;
               if(count<0){
               lblTimer.setText("0");
               }
         }
    });
    countdownTimer.start();
   }


    public void paint(Graphics graphics) {


        graphics.setColor(Color.WHITE); 
        graphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

        //paints square objects to the screen


        for (Square aSquareArray : squareArray) {
            aSquareArray.paint(graphics);    
        }

      //   for (Triangle aTriangleArray : TriangleArray) {
      //      aTriangleArray.paint(graphics);    
       // }

        thePlayer.paint(graphics); 

  //      if(Highscore.equals("")){
//            Highscore = this.GetHighScore();
   //     }

    }

  //  public void DrawScore(Graphics g){
   //     g.drawString("Score: " + score, 0, B);
  //      g.drawString("HighScore: " + HighScore, 0,);
  //  }

    public void update() {

       // calls the Square class update method on the square objects
         if(Health > 0){

         for (Square aSquareArray : squareArray) aSquareArray.update();
         }

            // if(Health > 0){

        // for (Triangle aTriangleArray : TriangleArray) aTriangleArray.update();
        // }

    }



      private void mouseMove(MouseEvent evt) {
          if(Health > 0){
          thePlayer.PlayerMove(evt);  
         }
    } 


   public void collision(){
     Rectangle rectangle1 = thePlayer.bounds();//player rectangle 
     for (Square square: squareArray) { 
        if(square.GetBounds().intersects(rectangle1)){//testing all squares vs player
            Health = Health - 1;
           System.out.println("HIT");

             if (Health == 0){
                    System.out.println("LOST");

             }
        }  
    } 

      //    for (Triangle triangle: TriangleArray) { 
    //   if(triangle.GetBounds().intersects(rectangle1)){//testing all triangles vs player
     //       Health = Health - 1;
      //     System.out.println("HIT");

       //      if (Health == 0){
        //            System.out.println("LOST");

       //      }
      //  }  
   // } 

 }

 private static void GUI() throws InterruptedException {

        Game game = new Game();
        Player thePlayer = new Player();

        JLabel lblStart = new JLabel();
        JFrame frame = new JFrame();
        frame.add(game); 
        frame.setVisible(true);
        frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Dodge The Squares");
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);





         BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);

// Create a new blank cursor.
Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
    cursorImg, new Point(0, 0), "blank cursor");

// Set the blank cursor to the JFrame.
frame.getContentPane().setCursor(blankCursor);



              frame.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                mouseMove(evt); 
            } 

            private void mouseMove(MouseEvent evt){
                game.mouseMove(evt); 
            }
        });


        while (true) {
            game.update();
            game.repaint();  
            game.collision();


            Thread.sleep(10);
        }

 }

  public void DrawScore(Graphics g) throws InterruptedException{

        while (true) {
            int time = 0; 
           time = time + 1;
            g.drawString("Score: " + time, 0, WINDOW_WIDTH * WINDOW_HEIGHT + 10); 

            Thread.sleep(1000);
        }

  }

    public static void main(String[] args) throws InterruptedException {
         new Scoreboards().setVisible(true); 
        music(); 
            GUI();

    }       
}

1 个答案:

答案 0 :(得分:0)

对于游戏用法,我建议System.currentTimeMillis()因为它比System.nanoTime()更好的性能。一个如何跟踪游戏时间的示例:

public class Stopwatch {
    private long startTime;

    public void start() {
        startTime = System.currentTimeMillis();
    }

    public float getElapsedTimeSeconds() {
        return (System.currentTimeMillis() - startTime) / 1000f;
    }
}

用法:

Stopwatch stopwatch = new Stopwatch();
stopwatch.start();
Thread.sleep(5000);
System.out.println("Time elapsed in seconds: " + stopwatch.getElapsedTimeSeconds());