-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRenderer.java
More file actions
589 lines (573 loc) · 22.4 KB
/
Renderer.java
File metadata and controls
589 lines (573 loc) · 22.4 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
import java.util.Random;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.ListIterator;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import javax.swing.JPanel;
import javax.swing.JFrame;
/**
* This is the class to manage rendering and game objects.
* Also handle keyboard events
* @see java.awt.event.KeyListener
* @see javax.swing.JFrame
*/
public class Renderer implements KeyListener
{
// variables related to the window
private JFrame myFrame = null;
private MyPanel myPanel = null;
private final int frameWidth = 600;
private final int frameHeight = 600;
// game status and properties
private boolean gameExit = false;
private boolean gameStart = false;
private int maxPosX, maxPosY;
private final int fps = 60;
// UP DOWN LEFT RIGHT SHOOT
private boolean[] control = {false, false, false, false, false};
private int score = 0; // how many enemies defeated
private int scoreRound = 0; // how many rounds survived
// game objects
private GameObject.FPSController objFPSController;
private GameObject.Background objBackground;
private GameObject.MyShip objMyShip;
private GameObject.RecoveryPack objRecovery;
private LinkedList<GameObject.SpaceShip> objEnemies;
private LinkedList<GameObject.Bullet> objBullets;
private final int maxEnemiesSpawned = 5; // how many enemies can be spawned at most
private final int minEnemiesSpawned = 1; // how many enemies can be spawned at least
private Random enemyRand;
public Renderer(int level)
{
// initalize JPanel
myPanel = new MyPanel();
myPanel.setPreferredSize(new Dimension(frameWidth, frameHeight));
maxPosX = frameWidth / myPanel.chrWidth - 1;
maxPosY = frameHeight / myPanel.chrHeight - 1;
// initialize new JFrame
myFrame = new JFrame("Space Invader");
myFrame.add(myPanel);
myFrame.setResizable(false);
myFrame.addKeyListener(this);
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myFrame.pack();
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);
myFrame.setBackground(Color.BLACK);
myFrame.setAlwaysOnTop(true);
// initialize game objects
enemyRand = new Random(System.currentTimeMillis());
objFPSController = new GameObject.FPSController(fps);
objBackground = new GameObject.Background(maxPosX, maxPosY);
objMyShip = new GameObject.MyShip(level, maxPosX / 2, maxPosY - 1, maxPosX, maxPosY);
objRecovery = new GameObject.RecoveryPack(maxPosX, maxPosY);
objEnemies = new LinkedList<>();
objBullets = new LinkedList<>();
}
/**
* The main game loop
*/
public void loop()
{
// first render the start screen
while(!gameStart)
{
myPanel.addCommand(new RenderCommand(maxPosX / 2 - 12, maxPosY / 2, "Welcome to Space Invader!"));
myPanel.addCommand(new RenderCommand(maxPosX / 2 - 10, maxPosY / 2+1, "Press ENTER to start"));
myPanel.repaint();
objFPSController.pause();
}
myPanel.addCommand(new RenderCommand(maxPosX / 2 - 12, maxPosY / 2, " "));
myPanel.addCommand(new RenderCommand(maxPosX / 2 - 10, maxPosY / 2+1, " "));
myPanel.repaint();
boolean frame = false; // use this variable to slow down drawing
while(!gameExit)
{
objFPSController.update();
render(frame);
renderUI();
frame = !frame;
myPanel.repaint(); // refresh the frame to update content
}
objFPSController.finalPause();
}
/**
* Create render commands to render UI
*/
private void renderUI()
{
String myHP = "HP = " + String.format("%02d", objMyShip.d_HP);
String myScore = "Score = " + score;
String myRound = "Round = " + scoreRound;
myPanel.addCommand(new RenderCommand(1, 0, myHP));
myPanel.addCommand(new RenderCommand(1, 1, myScore));
myPanel.addCommand(new RenderCommand(1, 2, myRound));
}
/**
* Collect render command and send to JPanel
* @param frame
*/
private void render(boolean frame)
{
ArrayList<RenderCommand> commands = new ArrayList<>();
commands.addAll(objBackground.update());
if(frame)
processLogic();
else
{
commands.addAll(objMyShip.update(GameObject.MoveDirection.DIR_NONE));
for(GameObject.SpaceShip ship : objEnemies)
commands.addAll(ship.update(GameObject.MoveDirection.DIR_NONE));
}
for(GameObject.Bullet bullet : objBullets)
commands.addAll(bullet.update(frame));
commands.addAll(objRecovery.update(frame));
myPanel.addCommand(commands);
}
/**
* Process internal game logic (body movements, bullet hit, random spawned enemies)
*/
private void processLogic()
{
ArrayList<RenderCommand> commands = new ArrayList<>();
// update my ship direction based on control input
if(control[0]) commands.addAll(objMyShip.update(GameObject.MoveDirection.DIR_UP));
else if(control[1]) commands.addAll(objMyShip.update(GameObject.MoveDirection.DIR_DOWN));
else if(control[2]) commands.addAll(objMyShip.update(GameObject.MoveDirection.DIR_LEFT));
else if(control[3]) commands.addAll(objMyShip.update(GameObject.MoveDirection.DIR_RIGHT));
else commands.addAll(objMyShip.update(GameObject.MoveDirection.DIR_NONE));
if(control[4]) objBullets.addAll(objMyShip.shoot());
// process recovery pack
if(!objRecovery.exist())
{
if(enemyRand.nextInt(100) < 1) // 1/100 possibility to appear
commands.add(objRecovery.appear());
}
else
{
if(Math.abs((int)Math.floor(objRecovery.xPos) + 2 - objMyShip.xPos) < (objMyShip.offsetX + 3) &&
Math.abs((int)Math.floor(objRecovery.yPos) - objMyShip.yPos) < (objMyShip.offsetY + 1))
{
objMyShip.recover();
commands.add(objRecovery.disappear());
}
}
// process enemies
if(objEnemies.size() <= 0)
{
// randomly spawn enemies if num enemy is 0
scoreRound++;
if(scoreRound % 5 == 0)
{
// every 5 rounds, spawn a boss fight
objEnemies.add(new GameObject.EnemyD(maxPosX / 2, 5, maxPosX, maxPosY));
}
else
{
int num = enemyRand.nextInt((maxEnemiesSpawned - minEnemiesSpawned) + 1) + minEnemiesSpawned;
for(int i = 0; i < num; i++)
{
int enemyType = enemyRand.nextInt(1000); // [0, 50) - Enemy C, [50, 400) - Enemy B, [400, 1000) - Enemy A
if(enemyType < 50)
{
// set offsets of Ship C
int offsetX = 4; int offsetY = 2;
int maxTry = 10;
while(maxTry > 0)
{
int posX = enemyRand.nextInt((maxPosX-8)+1) + 4; // [4, maxPosX - 4]
int posY = enemyRand.nextInt((maxPosY/2-1)+1) + 1; // [1, maxPosY / 2]
boolean goodPos = true;
for(GameObject.SpaceShip ship : objEnemies)
{
if(Math.abs(ship.xPos - posX) < (ship.offsetX + offsetX + 1) && Math.abs(ship.yPos - posY) < (ship.offsetY + offsetY + 1))
{
// overlap detected
goodPos = false;
break;
}
}
if(goodPos)
{
objEnemies.add(new GameObject.EnemyC(posX, posY, maxPosX, maxPosY));
break;
}
maxTry--;
}
}
else if(enemyType < 400)
{
// set offsets of Ship B
int offsetX = 2; int offsetY = 1;
int maxTry = 10;
while(maxTry > 0)
{
int posX = enemyRand.nextInt((maxPosX-8)+1) + 4; // [4, maxPosX - 4]
int posY = enemyRand.nextInt((maxPosY/2-1)+1) + 1; // [1, maxPosY / 2]
boolean goodPos = true;
for(GameObject.SpaceShip ship : objEnemies)
{
if(Math.abs(ship.xPos - posX) < (ship.offsetX + offsetX + 1) && Math.abs(ship.yPos - posY) < (ship.offsetY + offsetY + 1))
{
// overlap detected
goodPos = false;
break;
}
}
if(goodPos)
{
objEnemies.add(new GameObject.EnemyB(posX, posY, maxPosX, maxPosY));
break;
}
maxTry--;
}
}
else
{
// set offsets of Ship A
int offsetX = 1; int offsetY = 0;
int maxTry = 10;
while(maxTry > 0)
{
int posX = enemyRand.nextInt((maxPosX-8)+1) + 4; // [4, maxPosX - 4]
int posY = enemyRand.nextInt((maxPosY/2-1)+1) + 1; // [1, maxPosY / 2]
boolean goodPos = true;
for(GameObject.SpaceShip ship : objEnemies)
{
if(Math.abs(ship.xPos - posX) < (ship.offsetX + offsetX + 1) && Math.abs(ship.yPos - posY) < (ship.offsetY + offsetY + 1))
{
// overlap detected
goodPos = false;
break;
}
}
if(goodPos)
{
objEnemies.add(new GameObject.EnemyA(posX, posY, maxPosX, maxPosY));
break;
}
maxTry--;
}
}
}
}
}
ListIterator<GameObject.SpaceShip> enemyIter = objEnemies.listIterator();
while(enemyIter.hasNext())
{
// randomly move on Y axis
// move following my ship on X axis
GameObject.SpaceShip ship = enemyIter.next();
// check if alive
if(!ship.isAlive())
{
score++;
commands.addAll(ship.explode());
enemyIter.remove(); // remove dead ship
continue;
}
int horiOrVert = enemyRand.nextInt(2);
GameObject.MoveDirection finalChoice = GameObject.MoveDirection.DIR_NONE;
// 50% possibility to stay still, to reduce unnatural movements
if(enemyRand.nextInt(2) > 0)
{
if(horiOrVert == 0)
{
// move horizontally
int desiredDir = (objMyShip.xPos >= ship.xPos) ? 1 : -1; // move towards my ship
// check validity
boolean validDir = true;
boolean validOppositeDir = true;
for(GameObject.SpaceShip otherShip : objEnemies)
{
if(otherShip != ship)
{
if(Math.abs(ship.xPos + desiredDir - otherShip.xPos) < (otherShip.offsetX + ship.offsetX + 1) &&
Math.abs(ship.yPos - otherShip.yPos) < (otherShip.offsetY + ship.offsetY + 1))
{
// overlap detected
validDir = false;
break;
}
if(Math.abs(ship.xPos - desiredDir - otherShip.xPos) < (otherShip.offsetX + ship.offsetX + 1) &&
Math.abs(ship.yPos - otherShip.yPos) < (otherShip.offsetY + ship.offsetY + 1))
validOppositeDir = false; // not valid to move opposite way
}
}
if(validDir)
finalChoice = (desiredDir < 0) ? GameObject.MoveDirection.DIR_LEFT : GameObject.MoveDirection.DIR_RIGHT;
else if(validOppositeDir)
{
// only 1/5 possibility to stay still
if(enemyRand.nextInt(5) > 0)
finalChoice = (desiredDir > 0) ? GameObject.MoveDirection.DIR_LEFT : GameObject.MoveDirection.DIR_RIGHT;
}
}
else
{
// move vertically
int desiredDir = (enemyRand.nextInt(2) > 0) ? 1 : -1; // 50% possibility
// check validity
boolean validDir = true;
boolean validOppositeDir = true;
for(GameObject.SpaceShip otherShip : objEnemies)
{
if(otherShip != ship)
{
if(Math.abs(ship.yPos + desiredDir - otherShip.yPos) < (otherShip.offsetY + ship.offsetY + 1) &&
Math.abs(ship.xPos - otherShip.xPos) < (otherShip.offsetX + ship.offsetX + 1))
{
// overlap detected
validDir = false;
break;
}
if(Math.abs(ship.yPos - desiredDir - otherShip.yPos) < (otherShip.offsetY + ship.offsetY + 1) &&
Math.abs(ship.xPos - otherShip.xPos) < (otherShip.offsetX + ship.offsetX + 1))
validOppositeDir = false; // not valid to move opposite way
}
}
if(validDir)
finalChoice = (desiredDir < 0) ? GameObject.MoveDirection.DIR_UP : GameObject.MoveDirection.DIR_DOWN;
else if(validOppositeDir)
{
// only 1/5 possibility to stay unmoved
if(enemyRand.nextInt(5) > 1)
finalChoice = (desiredDir > 0) ? GameObject.MoveDirection.DIR_UP : GameObject.MoveDirection.DIR_DOWN;
}
}
}
commands.addAll(ship.update(finalChoice));
// randomly trigger shoot
if(enemyRand.nextInt(10) > 2)
objBullets.addAll(ship.shoot());
}
// process bullets
ListIterator<GameObject.Bullet> bulletIter = objBullets.listIterator();
while(bulletIter.hasNext())
{
GameObject.Bullet bullet = bulletIter.next();
// check if bullet is outside of screen
if(bullet.yPos < 0 || bullet.yPos > maxPosY)
{
commands.add(bullet.explode());
bulletIter.remove();
continue;
}
// process by type
boolean hit = false;
if(bullet.isEnemy())
{
if(Math.abs(bullet.xPos - objMyShip.xPos) <= (objMyShip.offsetX) && Math.abs(bullet.yPos - objMyShip.yPos) <= (objMyShip.offsetY))
{
commands.addAll(objMyShip.hit());
hit = true;
}
}
else
{
for(GameObject.SpaceShip ship : objEnemies)
{
if(Math.abs(bullet.xPos - ship.xPos) <= (ship.offsetX) && Math.abs(bullet.yPos - ship.yPos) <= (ship.offsetY))
{
commands.addAll(ship.hit());
hit = true;
break;
}
}
}
if(hit)
{
commands.add(bullet.explode());
bulletIter.remove();
}
}
// if my ship is not alive, set it to null
if(!objMyShip.isAlive())
{
commands.addAll(objMyShip.explode());
gameExit = true;
}
myPanel.addCommand(commands);
}
/**
* Send close window event
* @return String, final summary
*/
public String close()
{
myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
String summary = "Your final score = " + score;
summary += "\nYou have played for " + scoreRound + " rounds";
return summary;
}
@Override
public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_ESCAPE:
gameExit = true;
break;
case KeyEvent.VK_UP:
case KeyEvent.VK_W:
control[0] = true;
break;
case KeyEvent.VK_DOWN:
case KeyEvent.VK_S:
control[1] = true;
break;
case KeyEvent.VK_LEFT:
case KeyEvent.VK_A:
control[2] = true;
break;
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_D:
control[3] = true;
break;
case KeyEvent.VK_SPACE:
control[4] = true;
break;
case KeyEvent.VK_ENTER:
gameStart = true;
break;
default: break;
}
}
@Override
public void keyReleased(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_ESCAPE:
gameExit = false;
break;
case KeyEvent.VK_UP:
case KeyEvent.VK_W:
control[0] = false;
break;
case KeyEvent.VK_DOWN:
case KeyEvent.VK_S:
control[1] = false;
break;
case KeyEvent.VK_LEFT:
case KeyEvent.VK_A:
control[2] = false;
break;
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_D:
control[3] = false;
break;
case KeyEvent.VK_SPACE:
control[4] = false;
break;
default: break;
}
}
@Override
public void keyTyped(KeyEvent e) {}
/**
* This class handles the real text rendering, by the render commands received.
* @see javax.swing.JPanel
*/
public class MyPanel extends JPanel
{
static final long serialVersionUID = 1234L;
static final int fontSize = 12;
private ArrayList<RenderCommand> commands;
private Font myFont = new Font(Font.MONOSPACED, Font.PLAIN, fontSize);
public int chrHeight = 0;
public int chrWidth = 0;
private int chrDescent = 0;
public MyPanel()
{
commands = new ArrayList<>();
// set font properties
FontMetrics metrics = getFontMetrics(myFont);
chrHeight = metrics.getHeight();
chrWidth = metrics.charWidth(' ');
chrDescent = metrics.getMaxDescent();
}
@Override
public void paintComponent(Graphics g)
{
g.setFont(myFont);
for(RenderCommand command : commands)
{
// fill background with black
g.setColor(Color.BLACK);
g.fillRect(command.getX()*chrWidth, command.getY()*chrHeight + chrDescent, command.getData().length()*chrWidth, chrHeight);
// draw actual data
g.setColor(command.getColor());
g.drawString(command.getData(), command.getX()*chrWidth, (command.getY()+1)*chrHeight);
}
// clear drawing commands
commands.clear();
this.revalidate();
}
/**
* Add a single command
* @param posX
* @param posY
* @param data
*/
public void addCommand(int posX, int posY, String data)
{
commands.add(new RenderCommand(posX, posY, data));
}
/**
* Add a single command
* @param cmd
*/
public void addCommand(RenderCommand cmd)
{
commands.add(cmd);
}
/**
* Add a list of commands
* @param cmds
*/
public void addCommand(ArrayList<RenderCommand> cmds)
{
commands.addAll(cmds);
}
}
/**
* This class stores a single render command
*/
public static class RenderCommand
{
private int posX;
private int posY;
private String data;
private Color color = Color.WHITE;
RenderCommand()
{
this.posX = 0;
this.posY = 0;
this.data = "";
}
RenderCommand(int posX, int posY, String data)
{
this.posX = posX;
this.posY = posY;
this.data = data;
}
RenderCommand(int posX, int posY, String data, Color color)
{
this.posX = posX;
this.posY = posY;
this.data = data;
this.color = color;
}
public int getX(){return posX;}
public int getY(){return posY;}
public String getData(){return data;}
public Color getColor(){return color;}
public void setX(int m){this.posX = m;}
public void setY(int m){this.posY = m;}
public void setData(String data){this.data = data;}
}
}