-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameScene.java
More file actions
752 lines (637 loc) · 20.7 KB
/
Copy pathGameScene.java
File metadata and controls
752 lines (637 loc) · 20.7 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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.ArrayList;
import java.awt.event.*;
import java.io.File;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.sound.sampled.*;
/**
The game scene - runs the game
@author Jack Humphries
@version 4/1/2014
*/
public class GameScene extends JComponent implements KeyListener
{
/** the distance between the pipes */
public static final double PIPE_DISTANCE = 350;
/** the top possible y coordinate of the top of clouds */
public static final int TOP_CLOUD_Y = 150;
/** the bottom possible y coordinate of the top of clouds */
public static final int BOTTOM_CLOUD_Y = 30;
/** the x coordinate of the bird */
public static final int BIRD_X = 200;
/** the amount of time in milliseconds that the timer waits before
moving each object on screen (changing this number will speed up
or slow down the entire game) */
public static final int MOVEMENT_TIME = 5;
/** the amount of time in milliseconds that the timer waits before
redrawing all of the objects on the screen */
public static final int ANIMATION_TIME = 20;
/** the amount of red in the color of the background (RGB) */
public static final double BACKGROUND_COLOR_R = 0;
/** the amount of green in the color of the background (RGB) */
public static final double BACKGROUND_COLOR_G = 198.0;
/** the amount of blue in the color of the background (RGB) */
public static final double BACKGROUND_COLOR_B = 255.0;
/** the width of the scene */
private int width;
/** the height of the scene */
private int height;
/** the timer that coordinates when objects will be moved on screen */
private Timer movementTimer;
/** the timer that coordinates when objects will be redrawn on screen */
private Timer animationTimer;
/** the bird used in the game */
private Bird bird;
/** the pipes in the game */
private ArrayList<Pipe> pipes;
/** the ground */
private Ground ground;
/** the current score */
private int score;
/** the score display */
private ScoreDisplay scoreDisplay;
/** specifies if the score has changed */
private boolean scoreUpdated;
/** the background of the scene */
private Rectangle background;
/** the instructions shown in the game */
private BufferedImage instructionsImage;
/** the x coordinate of the instructions image */
private double instructionsX;
/** the y coordinate of the instructions image */
private double instructionsY;
/** the clouds in the scene */
private Clouds clouds;
/** specifies if the game is playing
- true if game is playing, else false */
private boolean playing;
/** specifies if the user has released the space bar before pressing it
again, this helps to prevent the user from holding down the space bar
to fly up continuously */
private boolean spaceBarReleased;
/** the main class */
private Main mainClass;
/**
draws the scene
@param g the graphics object
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
//turn on anti-aliasing
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
float backgroundRed = (float)(BACKGROUND_COLOR_R/255.0);
float backgroundGreen = (float)(BACKGROUND_COLOR_G/255.0);
float backgroundBlue = (float)(BACKGROUND_COLOR_B/255.0);
Color backgroundColor = new Color(backgroundRed,
backgroundGreen, backgroundBlue);
g2.setColor(backgroundColor);
g2.fill(background);
clouds.redrawClouds(g2);
if (!playing)
{
g2.drawImage(instructionsImage,
(int)instructionsX, (int)instructionsY, null);
}
if (pipes.size() > 0)
{
for (Pipe pipe : pipes)
{
pipe.redrawPipe(g2);
}
}
bird.redrawBird(g2);
ground.redrawGround(g2);
if (playing)
{
int scoreX = (width / 2) - (scoreDisplay.getWidth() / 2);
int scoreY = ((height / 4) * 1) - (scoreDisplay.getHeight() / 2);
scoreDisplay.drawScore(g2, scoreX, scoreY);
}
}
/**
moves/updates the objects on screen
*/
private void moveAndUpdateObjects()
{
clouds.moveClouds();
bird.moveBird();
ground.moveGround();
if (pipes.size() > 0)
{
checkPipes();
for (Pipe pipe : pipes)
{
pipe.setX(pipe.getPipeXPosition() - 1);
}
if (playing)
{
detectCollision();
detectPass();
}
}
generateScoreLabel();
}
/**
starts moving objects in the scene and animating the scene
*/
private void run()
{
//animation and movement of objects are done on separate threads,
//this should help resolve the "slow down" issue where objects would
//start moving more slowly as the game was restarted and played for
//a long time
//everything should stay moving at nearly the same rate, even if the
//frame rate decreases
Thread movementThread = new Thread(
new Runnable()
{
public void run()
{
startMovingObjects();
}
});
Thread animationThread = new Thread(
new Runnable()
{
public void run()
{
startAnimating();
}
});
movementThread.start();
animationThread.start();
}
/**
responsible for moving objects every MOVEMENT_TIME milliseconds
*/
private void startMovingObjects()
{
movementTimer = new Timer(MOVEMENT_TIME,
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
moveAndUpdateObjects();
}
});
movementTimer.start();
}
/**
responsible for calling the repaint method
every ANIMATION_TIME milliseconds
*/
private void startAnimating()
{
animationTimer = new Timer(ANIMATION_TIME,
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
});
animationTimer.start();
}
/**
generates the instructions
*/
private void generateInstructions()
{
File instructionsPath = new File("images/instructions.png");
try
{
instructionsImage = ImageIO.read(instructionsPath);
}
catch (Exception exception)
{
}
instructionsX = (width / 3) * 2 - (instructionsImage.getWidth() / 2);
instructionsY = (height / 2) - (instructionsImage.getHeight() / 2);
}
/**
generates the background
*/
private void generateBackground()
{
background = new Rectangle(0, 0, width, height);
}
/**
generates the clouds
*/
private void generateClouds()
{
clouds = new Clouds(width, TOP_CLOUD_Y, BOTTOM_CLOUD_Y);
}
/**
generates the ground
*/
private void generateGround()
{
ground = new Ground(width, height - Ground.HEIGHT);
}
/**
generates the score label
*/
private void generateScoreLabel()
{
if (scoreDisplay == null)
{
scoreDisplay = new ScoreDisplay(score);
}
if (scoreUpdated)
{
scoreDisplay.setScore(score);
scoreUpdated = false;
}
}
/**
start playing the game - the user pressed the space bar for the first time
*/
private void play()
{
playing = true;
bird.startPlaying();
bird.flyUp();
playFlySound();
createPipe();
}
/**
adds a point to the score
*/
private void addPoint()
{
score++;
scoreUpdated = true;
}
/**
checks the location of the pipes to see if a pipe should be removed from
the scene or if one should be added to the scene
*/
private void checkPipes()
{
Pipe front = pipes.get(0);
double frontPipeX = front.getPipeXPosition();
int frontPipeWidth = front.getPipeWidth();
Pipe back = pipes.get(pipes.size() - 1);
double backPipeX = back.getPipeXPosition();
int backPipeWidth = back.getPipeWidth();
//remove the first pipe when it is completely off the left of the screen
if (frontPipeX <= 0 - frontPipeWidth)
{
pipes.remove(0);
}
//add a new pipe when the last one is at least PIPE_DISTANCE from the
//right of the screen
if (backPipeX <= width - PIPE_DISTANCE)
{
createPipe();
}
}
/**
creates a pipe and adds it to the pipes array
*/
private void createPipe()
{
Pipe pipe = new Pipe(width, height);
pipes.add(pipe);
}
/**
creates the bird
*/
private void createBird()
{
bird = new Bird(BIRD_X, height / 2 - Bird.HEIGHT / 2, 0);
}
/**
detects a collision between the bird and the pipes/ground
*/
private void detectCollision()
{
//collision detection is run on a separate thread
Thread thread = new Thread(
new Runnable()
{
public void run()
{
double birdX = bird.getXPosition();
double birdY = bird.getYPosition();
int birdWidth = bird.getWidth();
int birdHeight = bird.getHeight();
Rectangle birdRect = new Rectangle((int)birdX, (int)birdY,
birdWidth, birdHeight);
//make a copy of the pipes array to go through to prevent
//a ConcurrentModificationException from being thrown,
//clone() makes a shallow copy, so this
//is not memory intensive
ArrayList<Pipe> pipesCopy = (ArrayList<Pipe>)pipes.clone();
for (Pipe pipe : pipesCopy)
{
if (detectPipeCollision(bird, birdRect, pipe))
{
endGame();
}
}
if (birdY + birdHeight >= height - Ground.HEIGHT)
{
//the bird has collided with the ground, end the game
endGame();
}
}
});
if (playing)
{
thread.start();
}
}
/**
detects if there is a collision between the bird and the pipe (called by
the detectCollision() method)
(pipe collision code adapted from http://stackoverflow.com/questions/23332096/how-to-detect-if-two-images-collide-in-java)
@param theBird the bird that is checked to see if it collides with the pipe
@param birdRect the bounds of the bird
@param thePipe the pipe that is checked to see if it collides with the bird
@return true if the bird and pipe collide, else false
*/
private boolean detectPipeCollision(Bird theBird, Rectangle birdRect,
Pipe thePipe)
{
boolean foundCollision = false;
double pipeX = thePipe.getPipeXPosition();
int pipeWidth = thePipe.getPipeWidth();
int pipeHeight = thePipe.getPipeHeight();
int holeY = thePipe.getHoleY();
int holeHeight = thePipe.getHoleHeight();
int bottomPipeY = holeY + holeHeight;
Rectangle topPipeRect = new Rectangle((int)pipeX, 0, pipeWidth, holeY);
Rectangle bottomPipeRect = new Rectangle((int)pipeX, bottomPipeY,
pipeWidth, pipeHeight - bottomPipeY);
if (birdRect.intersects(topPipeRect)
|| birdRect.intersects(bottomPipeRect))
{
//the bird rectangle has collided with a pipe,
//check to see if the bird pixel that collided
//with the pipe is black (because both the bird and
//the pipe are outlined by black pixels)
//if so, end the game (only
//black pixel collisions should end the game)
Rectangle pipeRect = new Rectangle();
boolean hitTopPartOfPipe = false;
if (birdRect.intersects(topPipeRect))
{
pipeRect = topPipeRect;
hitTopPartOfPipe = true;
}
else if (birdRect.intersects(bottomPipeRect))
{
pipeRect = bottomPipeRect;
hitTopPartOfPipe = false;
}
Rectangle bounds = getCollision(birdRect, pipeRect);
if (!bounds.isEmpty())
{
for (int x = bounds.x; x < bounds.x + bounds.width
&& !foundCollision; x++)
{
for (int y = bounds.y; y < bounds.y + bounds.height
&& !foundCollision; y++)
{
if (collision(x, y, bird, thePipe, hitTopPartOfPipe))
{
//the bird has collided with a pipe,
//end the game
foundCollision = true;
}
}
}
}
}
return foundCollision;
}
/**
returns a rectangle of the intersection area of the bird and the pipe
(code from http://stackoverflow.com/questions/23332096/how-to-detect-if-two-images-collide-in-java)
@param rect1 the first rectangle (such as the bird)
@param rect2 the second rectangle (such as the pipe)
@return a rectangle of the intersection area of the bird and the pipe
*/
private Rectangle getCollision(Rectangle rect1, Rectangle rect2)
{
Area a1 = new Area(rect1);
Area a2 = new Area(rect2);
a1.intersect(a2);
return a1.getBounds();
}
/**
detects if black pixels at the location (x, y)
collide in the bird and the pipe (because the bird and the pipe are
both outlined by black pixels)
(code adapted from http://stackoverflow.com/questions/23332096/how-to-detect-if-two-images-collide-in-java)
@param x the x coordinate to check
@param y the y coordinate to check
@param theBird the bird object to check
@param thePipe the pipe object to check
@param hitTopPartOfPipe specifies if the bird rectangle collided with
the top part of the pipe or the bottom part
@return true if the bird and pipe are colliding at a black pixel,
else false if they are not colliding
*/
private boolean collision(int x, int y, Bird theBird,
Pipe thePipe, boolean hitTopPartOfPipe)
{
boolean collision = false;
Rectangle birdBounds = new Rectangle();
birdBounds.setSize(bird.getWidth(), bird.getHeight());
birdBounds.setLocation((int)bird.getXPosition(),
(int)bird.getYPosition());
Rectangle pipeBounds = new Rectangle();
int pipeSegmentHeight = thePipe.getPipeSegmentHeight(hitTopPartOfPipe);
pipeBounds.setSize(thePipe.getPipeWidth(), pipeSegmentHeight);
int pipeSegmentY = thePipe.getPipeSegmentYPosition(hitTopPartOfPipe);
pipeBounds.setLocation((int)thePipe.getPipeXPosition(), pipeSegmentY);
int birdPixel = theBird.getRGB(x - birdBounds.x, y - birdBounds.y);
int birdPixelR = birdPixel << 16 & 0x000000FF;
int birdPixelG = birdPixel << 8 & 0x000000FF;
int birdPixelB = birdPixel << 0 & 0x000000FF;
int pipePixel = thePipe.getRGB(x - pipeBounds.x, y - pipeBounds.y,
hitTopPartOfPipe);
int pipePixelR = pipePixel << 16 & 0x000000FF;
int pipePixelG = pipePixel << 8 & 0x000000FF;
int pipePixelB = pipePixel << 0 & 0x000000FF;
//check to see if the bird pixel and the pipe pixel are both
//black (r = 0, g = 0, b = 0), because both objects are
//surrounded by a black outline of pixels
if ((birdPixelR == 0 && birdPixelG == 0 && birdPixelB == 0)
&& (pipePixelR == 0 && pipePixelG == 0 && pipePixelB == 0))
{
collision = true;
}
return collision;
}
/**
detects if the bird has successfully moved through an uncleared pipe,
if the bird has, the score is increased by 1
*/
private void detectPass()
{
double birdX = bird.getXPosition();
//make a copy of the pipes array to go through to prevent
//a ConcurrentModificationException from being thrown,
//clone() makes a shallow copy, so this
//is not memory intensive
ArrayList<Pipe> pipesCopy = (ArrayList<Pipe>)pipes.clone();
for (Pipe pipe : pipesCopy)
{
double pipeX = pipe.getPipeXPosition();
int pipeWidth = pipe.getPipeWidth();
int rightSidePipeX = (int)pipeX + pipeWidth;
if (birdX > rightSidePipeX && !pipe.getPipeCleared())
{
pipe.setPipeCleared();
addPoint();
playPointSound();
}
}
}
/**
plays a sound when the user successfully moves through a pipe
and earns a point
*/
private void playPointSound()
{
playSound("sounds/point.aif");
}
/**
plays a sound when the user collides with a pipe or the ground, and dies
*/
private void playCollisionSound()
{
playSound("sounds/collision.aiff");
}
/**
plays a sound when the user hits the space bar to make the bird fly up
*/
private void playFlySound()
{
playSound("sounds/fly.aiff");
}
/**
plays the sound file located at the file path
@param file the path of the sound file to play
(code adapted from http://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java)
*/
private void playSound(String file)
{
try
{
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream
= AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream(file));
clip.open(inputStream);
clip.start();
}
catch (Exception exception)
{
}
}
/**
ends the game (when the bird collides with a pipe or the ground)
*/
private void endGame()
{
if (playing)
{
playing = false;
movementTimer.stop();
animationTimer.stop();
playCollisionSound();
mainClass.displayGameOverScene(score);
}
}
/**
detects when the space bar is released (so that the user cannot
hold down the space bar to fly up continuously)
@param e the keystroke event
*/
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
spaceBarReleased = true;
}
}
/**
detects when the space bar is pressed and starts the game/makes
the bird fly up
@param e the keystroke event
*/
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
if (spaceBarReleased)
{
spaceBarReleased = false;
if (!playing)
{
play();
}
else
{
if (bird.flyUp())
{
playFlySound();
}
}
}
}
}
/**
this method is not used - it is part of the KeyListener interface
@param e the keystroke event
*/
public void keyTyped(KeyEvent e)
{
}
/**
resets the game scene so that the game can be replayed
*/
public void reset()
{
score = 0;
scoreUpdated = true;
pipes = new ArrayList<Pipe>();
generateScoreLabel();
playing = false;
bird.reset();
movementTimer.start();
animationTimer.start();
}
public GameScene(int theWidth, int theHeight, Main theMainClass)
{
width = theWidth;
height = theHeight;
mainClass = theMainClass;
spaceBarReleased = true;
scoreUpdated = false;
pipes = new ArrayList<Pipe>();
score = 0;
generateBackground();
createBird();
generateInstructions();
generateClouds();
generateGround();
generateScoreLabel();
setDoubleBuffered(true);
addKeyListener(this);
run();
}
}