【问题标题】:How can I display Time to my game如何在我的游戏中显示时间
【发布时间】:2017-06-04 12:27:34
【问题描述】:

我目前正在制作一个下降方块游戏。我需要一个评分系统,但我不知道如何将它集成到游戏框架上。

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

我的代码:

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

    }       
}

【问题讨论】:

  • System.currentTimeMillis()System.nanoTime() 将从现在开始成为你最好的朋友 ;)

标签: java swing time


【解决方案1】:

对于游戏用途,我建议使用 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());

【讨论】:

  • 如果不小心使用 Thread.sleep(5000); 将冻结 GUI。最好使用基于 Swing 的 Timer 定期更新 GUI。
  • 我同意您不需要或不需要睡眠(5000),但我认为您不需要单独的计时器 - 程序已经每 10 毫秒更新一次 GUI左右。
  • 抱歉含糊不清,Thread.sleep 调用只是为了演示 StopWatch 功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多