-
Notifications
You must be signed in to change notification settings - Fork 1
/
GameFrame.java
113 lines (97 loc) · 2.76 KB
/
GameFrame.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import javax.imageio.ImageIO;
import javax.swing.*;
public class GameFrame extends JPanel implements ActionListener, Runnable{
Timer mainTimer;
GameObject[] objects = new GameObject[15];
final int originalTile =16;
final int scale=3;
final int tileSize= originalTile*scale;
final int maxScreenCol=16;
final int maxScreenRow=12;
final int screenWidth= tileSize*maxScreenCol;
final int screenHeight= tileSize* maxScreenRow;
SecureRandom random = new SecureRandom();
Thread gameThread;
Player player;
BufferedImage treeImg;
public GameFrame() {
this.setPreferredSize(new Dimension(screenWidth, screenHeight));
this.setBackground(Color.black);
this.setDoubleBuffered(true);
for(int i = 0; i < objects.length; i++) {
objects[i] = new GameObject(random.nextInt(screenWidth*2), random.nextInt(screenHeight*2), "tree.png");
}
setFocusable(true);
player = new Player(screenWidth/2,screenHeight/2);
addKeyListener(new KeyAdapt(player));
mainTimer = new Timer(10,this);
mainTimer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
//g2d.drawImage(testImg, testX, testY, null);
player.draw(g2d);
for(int i=0; i<objects.length; i++) {
objects[i].drawObject(g2d);
}
}
public void update() {
player.update();
System.out.println(player.direction);
for(int i=0; i<objects.length; i++) {
objects[i].update(player);
//objects[i].isTouchingPlayer(player);
}
// player.draw();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//player.update();
update();
repaint();
}
public void startGameThread() {
gameThread= new Thread(this);
gameThread.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
double drawInterval = 1000000000/60;
double nextDraw= System.nanoTime()+drawInterval;
double delta=0;
long lastTime=System.nanoTime();
long currentTime;
while (gameThread!=null) {
update();
repaint();
try {
double remaining= nextDraw-System.nanoTime();
remaining= remaining/1000000;
if(remaining<0) {
remaining=0;
}
Thread.sleep((long)remaining);
nextDraw+=drawInterval;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}