-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameEngine.java
More file actions
314 lines (233 loc) · 12.2 KB
/
GameEngine.java
File metadata and controls
314 lines (233 loc) · 12.2 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import java.awt.Color;
import java.awt.event.*;
import java.util.*;
//Abstract class which handles the fundamental properties and actions
//for a Scrolling game.
//************************************************************************************
//* *
//* *
//* YOU ARE NOT ALLOWED TO MODIFY THIS CLASS *
//* (though you'll need to read, trace, and use the methods in it) *
//* *
//* *
//************************************************************************************
public abstract class GameEngine {
//******** KEYBOARD KEY VALES ********
//The Java API stores the values for various keys on the keyboard
//as integer values. These values are used by the keyPress methods
//in order to determine which key(s) the player has pressed. The KeyEvent
//class stores a large collection of finals for all the different keys.
//See the following API page for more info:
//https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
public static final int KEY_QUIT_GAME = KeyEvent.VK_ESCAPE;//quit the game
public static final int KEY_PAUSE_GAME = KeyEvent.VK_P;//pause the game
public static final int KEY_TOGGLE_DEBUG = KeyEvent.VK_D;//toggle debug mode on/off
public static final int KEY_SHOOT = KeyEvent.VK_SPACE;
public static final int SPEED_DOWN_KEY = KeyEvent.VK_MINUS;//make game run slower
public static final int SPEED_UP_KEY = KeyEvent.VK_EQUALS;//make game run faster
public static final int UP_KEY = KeyEvent.VK_UP;//move the player up
public static final int DOWN_KEY = KeyEvent.VK_DOWN;//.... down
public static final int LEFT_KEY = KeyEvent.VK_LEFT;//.... left
public static final int RIGHT_KEY = KeyEvent.VK_RIGHT;//.... right
//A collection of all the movement keys
public static final int[] MOVEMENT_KEYS = {UP_KEY, DOWN_KEY, LEFT_KEY, RIGHT_KEY};
//************************************************
//Dimensions of game window
private static final int DEFAULT_WIDTH = 900;
private static final int DEFAULT_HEIGHT = 600;
//tracks if the game is currently paused or not.
protected boolean isPaused;
//Number of ticks (ie, iterations of the game loop) since the game started running
private int ticksElapsed;
//the graphical window where the game is played and the entities are drawn
private GameWindow window;
//A List of entities to be drawn on the screen
//Whatever is in this List is drawn to the game window
//on each call to window.refresh();
//
//Entities are drawn in order of appearance in the Lists.
//First element is drawn beneath all entities, last element ontop of all entities.
protected List<Entity> displayList = new LinkedList<Entity>();
//A collection of entities to be garbage collected on the next tick.
//At the end of each tick:
// -Any Entity in this Collection is removed from displayList (no longer drawn in the window)
// -This collection is cleared
protected Collection<Entity> toBeGC = new HashSet<Entity>();
//determines if the game should pause while a splash screen is displayed.
//if set to false, the game will continue running underneath the splash screen
protected boolean pauseOnSplash;
public GameEngine(){
this(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
//Constructor, taking the width and height of the game window (in pixels)
public GameEngine(int gameWidth, int gameHeight){
initGame(gameWidth, gameHeight);
}
//Initializes the game and window, performed before the game launches
private void initGame(int gameWidth, int gameHeight){
//We need to pass GameWindow a reference to our displayList at instantation
this.window = new GameWindow(gameWidth, gameHeight, displayList);
this.pauseOnSplash = true;
this.isPaused = false;
this.ticksElapsed = 0;
}
//Runs the game once, start to finish
public void playGame(){
pregame(); //perform any pre-game tasks
gameLoop(); //play the game
postgame(); //perform any post-game tasks
window.endGame();//ends the game
}
//Plays the game.
//This is the "heart" of your Scrolling Game code.
private void gameLoop(){
//This is our game loop. It keeps iterating until the game is over (player
//wins or loses). One iteration of this loop is referred to as a "tick".
//Each tick the game updates the state of the game by reacting to user input and
//advancing the game state/redrawing the graphics accordingly.
while(!isGameOver()){
//react to keyboard/mouse input
captureInput();
//determine if the game state is updated
//note: the game typically pauses while a splash screen is displayed.
// however, if pauseOnSplash == false, the game keeps running behind
// the splash screen
if (!isPaused && (getSplashImage() == null || !pauseOnSplash)){
//update the state of the game (scroll, deal with collisions, etc)
updateGame();
ticksElapsed++;
}
//Garbage Collects any Entities to be removed from the game window
gcEntities();
//redraws the game window (including everything in displayList)
window.refresh();
}
}
//Removes all Entities to be garbage collected from the displayList
//Clears the to-be-GC'd collection afterwards
private void gcEntities(){
displayList.removeAll(toBeGC);
toBeGC.clear();
}
//Handles reacting to any keyboard keys the player has pressed on the keyboard
//and/or mouse clicks.
private void captureInput(){
//Returns a Collection of all the keys pressed.
//The player could be pressing multiple keys simultaneously, ex: moving diagonally.
Collection<Integer> keysPressed = window.getKeysPressed();
for(Integer key : keysPressed)
this.reactToKey(key); //handle each key individually
//...also handle any mouse clicks
MouseEvent click = window.getLastMousePress();
if (click != null)
reactToMouseClick(click);
}
//Returns the width of the game window, in pixels
public int getWindowWidth(){
return window.getWidth();
}
//Returns the height of the game window, in pixels
public int getWindowHeight(){
return window.getHeight();
}
//retrieves the background image currently being drawn in the window.
//returns the filename of the background image, or null if there is
//no background image currently being drawn.
public String getBackgroundImage(){
return window.getBackgroundImage();
}
//Sets the background image of the window to the argument image.
//Background is draw UNDERNEATH all the entities
//Argument passed is the filename of the image file.
public void setBackgroundImage(String imageFilename){
window.setBackgroundImage(imageFilename);
}
//Sets the splashscreen image drawn in tFhe window to the argument image.
//Splash is drawn ON TOP of all the entities.
//Argument passed is the filename of the image file.
public void setSplashImage(String splashFilename){
window.setSplashImage(splashFilename);
}
//Gets the splash screen image of the window.
//returns the filename of the splash screen image, or null if there is no background.
public String getSplashImage(){
return window.getSplashImage();
}
//Gets the current background color of the game window.
//This background color will only be visible if there is no background
//image, or if the background image has transparency.
public Color getBackgroundColor(Color bgColor){
return window.getBackgroundColor();
}
//Sets the background color of the game window to the argument Color.
//This background color will only be visible if there is no background
//image, or if the background image has transparency.
public void setBackgroundColor(Color bgColor){
window.setBackgroundColor(bgColor);
}
//Checks for a collision in the game window at the argument coordinate.
//This method returns a Collection containing any Entities that are being
//drawn at the argument x,y coordinate
protected Collection<Entity> findCollisions(int x, int y){
Collection<Entity> collisions = new HashSet<Entity>();
for (Entity e : displayList){
if (e.containsPoint(x, y))
collisions.add(e);
}
return collisions;
}
//Checks to see if the argument entity is colliding with ANYTHING in the game window.
//This method returns a Collection containing any Entities that are colliding with
//the argument Entity
protected Collection<Entity> findCollisions(Entity toCheck){
Collection<Entity> collisions = new HashSet<Entity>();
for (Entity e : displayList){
//the argument Entity won't be detected as colliding with
//itself if it is currently in the displayList
if (e != toCheck && e.isCollidingWith(toCheck))
collisions.add(e);
}
return collisions;
}
//Sets the title text to the argument String.
//This text is drawn in the top bar of the game window.
protected void setTitleText(String text){
window.setTitle(text);
}
//Returns the current game speed.
//The game speed is represented as integer indicating a percentage.
//a value of 100 indicates the game is running at 100% speed, ie the default game speed.
//150 and 50 would indicate game running 50% faster and 50% slower, respectively.
public int getGameSpeed(){
return window.getGameSpeed();
}
//Returns the number of iterations of the game loop since the game has been runninng.
//Used by child classes to govern timing of certain game events
protected int getTicksElapsed(){
return this.ticksElapsed;
}
//Sets the current game speed to the argument percentage.
//The game speed is represented as integer indicating a percentage.
//a value of 100 indicates the game is running at 100% speed, ie the default game speed.
//150 and 50 would indicate game running 50% faster and 50% slower, respectively.
public void setGameSpeed(int newGameSpeed){
if (newGameSpeed <= 0)
throw new IllegalStateException("ERROR! Game speed set to invalid value: " + newGameSpeed);
window.setGameSpeed(newGameSpeed);
}
//******** Abstract methods to be implemented by child classes ********
//called on each "tick" (if not paused) to update the state of the game
protected abstract void updateGame();
//called once before the game starts
protected abstract void pregame();
//called once after the game ends
protected abstract void postgame();
//Returns a boolean indicating whether the game is over (true) or not (false).
//Does not indicate if the player won or lost the game.
protected abstract boolean isGameOver();
//Handles reacting to a single key the player has pressed on the keyboard.
protected abstract void reactToKey(int keyCode);
//Handles reacting to a single mouse click in the game window
protected abstract MouseEvent reactToMouseClick(MouseEvent click);
//*********************************************************************
}