2017-01-19 7 views
-3

저는 현재 떨어지는 사각형 게임을 사용하고 있습니다. 스코어 시스템이 필요하지만 게임 프레임에이를 통합하여 디스플레이하는 방법을 모르겠습니다.내 게임 시간을 어떻게 표시 할 수 있습니까?

제 질문은 어떻게하면 위쪽으로 세고 타이머를 만들어 내 게임의 프레임에 실시간으로 표시 할 수 있습니까?

내 코드 :

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

    }  
} 
+0

'에 System.currentTimeMillis()'와'System.nanoTime()가'될 것입니다 당신의 가장 친한 친구 on out;) – CraigR8806

답변

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

'Thread.sleep (5000);'은 신중하게 사용하지 않으면 GUI를 멈출 것이다. Swing 기반의 Timer를 사용하여 GUI를 정기적으로 업데이트하는 것이 더 좋습니다. –

+0

나는 sleep (5000)이 필요하거나 필요하지 않다는 데 동의하지만,이 타이머는 별도로 필요하지 않습니다. 프로그램은 이미 10ms 정도마다 GUI를 업데이트하고 있습니다. –

+0

모호성에 대해 사과드립니다. Thread.sleep 호출은 StopWatch 기능을 데모하기위한 것이 었습니다. – abstractx1

관련 문제