1. 전체적인 구조
GameWindow 클래스
게임 창을 생성하고 게임 루프를 실행하는 데 사용된다.
JComponent를 상속하며, 게임 화면을 렌더링하고 업데이트하기 위한 기능을 제공한다.
* 참고
Jcomponent : https://bayleaf07.tistory.com/358
1. 멤버 변수
Game m_game: 게임 객체를 저장
2. 생성자
private GameWindow(Game game) | 게임 객체를 받음 새로운 GameWindow 인스턴스를 생성함 게임의 크기에 맞는 창 크기를 설정 |
3. 정적 메서드
public static void newWindow(Game game) | 게임 창을 생성하고 게임 루프를 시작함 이 루프는 게임 업데이트와 렌더링을 담당 적절한 시간 간격으로 게임을 업데이트하고 다시 그린다 적절한 시간 간격인 이유는, 게임의 프레임 속도를 유지하기 위해서이다. |
4. 게임 루프
while(true) | 무한 루프를 실행하여 게임을 업데이트하고 다시 그린다 |
game.update() | 게임을 업데이트 함 |
frame.repaint() | 창을 다시 그림 |
Thread.sleep(1) | 1ms (밀리세컨드) 동안 스레드를 일시중지 ( 루프의 반복을 일정하게 유지하기 위해 ) |
5. 그리기 메서드
public void paint(Graphics g) | 게임 창을 그리는 메서드 |
- 전체 코드
더보기
package engine;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
/**
*
* @author santi
*/
public class GameWindow extends JComponent {
Game m_game;
private GameWindow(Game game) {
m_game = game;
setPreferredSize(new Dimension((int)m_game.getWidth(),(int)m_game.getHeight()));
}
public static void newWindow(Game game) {
/*
Creates a Java window of the appropriate size to render the game:
*/
JFrame frame = new JFrame("Steering");
GameWindow c = new GameWindow(game);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(c, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.repaint();
/*
Game loop: this updates and redraws the game at the appropriate frequency
to achieve the desired frames per second.
*/
long next_update = System.currentTimeMillis();
int interval = 1000 / game.getFPS();
while(true) {
try {
long current_time = System.currentTimeMillis();
if (current_time>=next_update) {
game.update();
frame.repaint();
next_update += interval;
if (current_time>=next_update + interval*10) next_update = current_time + interval;
}
/*
this is necessary if you don't want this game to use 100% of the CPU,
even if it only needs a tiny fraction.
*/
Thread.sleep(1);
}catch(Exception e) {
e.printStackTrace();
}
}
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0, getWidth(), getHeight());
m_game.draw(g2d);
}
}
'Game AI & Unity > Java Steering game' 카테고리의 다른 글
[Game AI][Steering Behavior] 10. engine.Marker (0) | 2024.03.20 |
---|---|
[Game AI][Steering Behavior] 9. JComponent (0) | 2024.03.20 |
[Game AI][Steering Behavior] 7. engine.GameObject.java (0) | 2024.03.20 |
[Game AI][Steering Behavior] 6. engine.Game.java (0) | 2024.03.20 |
[Game AI][Steering Behavior] 5. engine.Car.java (0) | 2024.03.20 |