-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGame.py
1700 lines (1322 loc) · 58.3 KB
/
Game.py
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 16 21:29:13 2014
@authors:
Sidd Singal
James Jang
Filippos Lymperopoulos
Shooter Platform
You are under attack by the military, and you must shoot them to defend
youself. The enemies maneuver around walls and try to shoot back at you.
Survive as long as you can. This game uses a physical replica gun to shoot
with in the game using openCV libraries.
"""
# Import all needed libraries
import pygame
from pygame.locals import *
import numpy as np
from os import listdir
from os.path import isfile, join
import random
import cv2
import time
'''
Camera
This class handles all of the interaction with the webcam by tracking
different colors and their sizes
'''
class Camera:
'''
__init__
Initialize the Camera class
parameters:
screen - the screen of the game
returns: none
'''
def __init__(self, screen):
# The pyGame screen
self.screen = screen
# Initialize the camera port
self.cam = cv2.VideoCapture(0)
# Initialize position of interest (where the gun is pointing)
self.x=0
self.y=0
# Camera Blue and green values
self.blue = 0
self.green = 0
# Realgreen and realblue are for the calibration
self.realgreen = 0
self.realblue = 0
'''
calibrate
Calibrate the camera to the static background by eliminating random
color noise
parameters: none
return: none
'''
def calibrate(self):
"""calibrate captures the extraneous background color"""
# Capture frame-by-frame
ret, frame = self.cam.read()
# define range of blue color in HSV
lower_green = np.uint8([40, 100, 100])
upper_green = np.uint8([70, 255, 255])
# define range of blue color in HSV
lower_blue = np.uint8([110, 100, 100])
upper_blue = np.uint8([130,255,255])
# change the BGR frame toe HSV (hue saturation value)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# inRange returns black white verison of the color bounds between the lower and upper
green = cv2.inRange(hsv, lower_green, upper_green)
blue = cv2.inRange(hsv, lower_blue, upper_blue)
# add up the all of the background for each color
self.realgreen += green
self.realblue += blue
'''
endCalibration
End the calibration and saves the background static image
'''
def endCalibration(self):
self.realgreen[np.where(self.realgreen != 0)] = 255
cv2.imwrite('initalgreen.png', self.realgreen)
self.realgreen = cv2.imread('initalgreen.png', 0)
self.realblue[np.where(self.realblue != 0)] = 255
cv2.imwrite('initalblue.png', self.realblue)
self.realblue = cv2.imread('initalgreen.png', 0)
cv2.destroyAllWindows()
'''
update
Updates the camera and sets the position and size of each color
parameters: none
returns: none
'''
def update(self):
# Capture frame-by-frame
ret, frame = self.cam.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.uint8([110, 100, 100])
upper_blue = np.uint8([130,255,255])
# define range of green color in HSV
lower_green = np.uint8([40, 100, 100])
upper_green = np.uint8([70, 255, 255])
# inRange returns black white verison of the color bounds between the lower and upper
blue = cv2.inRange(hsv, lower_blue, upper_blue)
green = cv2.inRange(hsv, lower_green, upper_green)
# moments contain the position of the color mass
moment = cv2.moments(blue)
# length of the number of pixels of green
self.green = len(np.where(green != 0)[0])
# finds the central x and y coordinates and scale it to the window
if moment['m00'] != 0:
x,y = int(moment['m10']/moment['m00']), int(moment['m01']/moment['m00'])
camWidth = self.cam.get(3)
camHeight = self.cam.get(4)
# set the x and y coordinates
self.x = int((1.0*self.cam.get(3)-x)/camWidth*self.screen.get_size()[0])
self.y = int((1.0*y)/camHeight*self.screen.get_size()[1])
# length of the number of pixels of blue
self.blue = len(np.where(blue == 255)[0])
'''
endCam
Turns off the camera
parameters: none
returns: none
'''
def endCam(self):
self.cam.release()
cv2.destroyAllWindows()
'''
HUD
Represents the heads up dispay of the game, including health and score
'''
class HUD:
'''
__init__
Initialize the HUD class
parameters:
screen - the screen of the game
returns: none
'''
def __init__(self,screen):
# The pyGame screen
self.screen = screen
# Initialize initial score and maximum health, and current health
self.score = 0
self.maxHealth = 100
self.health = self.maxHealth
# Initialize the font for any printed text
self.font = pygame.font.SysFont("Comic Sans MS", self.screen.get_size()[1]/30)
'''
scoreUp
Increase the score by 1
parameters: none
returns: none
'''
def scoreUp(self):
# Increase the score by 1
self.score+=1
'''
hurt
The user is hurt when the enemy is able to make it all the way down
to the bottom of the screen
parameters: none
returns: none
'''
def hurt(self):
# Decrease the health by 10
self.health-=10
# Display a red transparent rectangle signifying that
# the user is hurt
hurtEnem = pygame.Surface((self.screen.get_size()[0],self.screen.get_size()[1]))
hurtEnem.set_alpha(100)
hurtEnem.fill((239,66,66))
self.screen.blit(hurtEnem, (0,0))
'''
shot
The user is hurt when the enemy shoots successfully at the user
parameters: none
returns: none
'''
def shot(self):
# Decrease the health by 1
self.health-=1
# Display a red transparent rectangle signifying that
# the user is hurt
hurtEnem = pygame.Surface((self.screen.get_size()[0],self.screen.get_size()[1]))
hurtEnem.set_alpha(100)
hurtEnem.fill((239,66,66))
self.screen.blit(hurtEnem, (0,0))
'''
update
Update all the figures on the screen
parameters: none
returns: none
'''
def update(self):
# Display the health bar on the screen
pygame.draw.rect(self.screen, (255,240,130), Rect((self.screen.get_size()[0]-self.screen.get_size()[0]/4.5,self.screen.get_size()[1]/25), (self.screen.get_size()[0]/5,self.screen.get_size()[1]/70)))
pygame.draw.rect(self.screen, (103,171,216), Rect((self.screen.get_size()[0]-self.screen.get_size()[0]/4.5,self.screen.get_size()[1]/24), ((self.screen.get_size()[0]/5)*1.0*self.health/self.maxHealth,self.screen.get_size()[1]/90)))
# Display the numerical health and score
text1 = self.font.render("Score: " + str(self.score), 1, (10, 10, 10))
text2 = self.font.render("Health: " + str(100/self.maxHealth*self.health) + '%', 1, (10, 10, 10))
self.screen.blit(text1,(self.screen.get_size()[0]/12,self.screen.get_size()[1]/13))
self.screen.blit(text2,(self.screen.get_size()[0]-self.screen.get_size()[0]/5.1,self.screen.get_size()[1]/17))
'''
endGame
Displays the score at the end of the game
parameters: none
returns: none
'''
def endGame(self):
# Set the text for the score to display
text = self.font.render("Score: " + str(self.score), 1, (10, 10, 10))
# Center and display the text
textpos = text.get_rect()
textpos.centerx = self.screen.get_rect().centerx
textpos.centery = self.screen.get_rect().centery
self.screen.blit(text, textpos)
'''
pauseGame
A screen for when the game is paused
parameters: none
returns: none
'''
def pauseGame(self):
# Set text indicating where the user should click to exit pause
text = self.font.render("Continue",1, (10, 10, 10))
# Display the text on the screen
pygame.draw.rect(self.screen, (255,240,130), Rect((self.screen.get_size()[0]-self.screen.get_size()[0]/1.68,self.screen.get_size()[1]/2.5), (self.screen.get_size()[0]/5,self.screen.get_size()[1]/10)))
pygame.draw.rect(self.screen, (100,240,130), Rect((self.screen.get_size()[0]-self.screen.get_size()[0]/1.2,self.screen.get_size()[1]/2.5), (self.screen.get_size()[0]/5,self.screen.get_size()[1]/10)))
self.screen.blit(text,(self.screen.get_size()[0]/2.3,self.screen.get_size()[1]/2.34))
'''
Background
Represents the background for the game
'''
class Background:
'''
__init__
Initialize the Background class
parameters: none
returns: none
'''
def __init__(self, screen):
# The pyGame screen
self.screen = screen
# Load the background image from file
self.bgImage = pygame.transform.scale(pygame.image.load('landscape.png'),self.screen.get_size())
'''
update
Display the background on the screen
parameters: none
returns: none
'''
def update(self):
# Add the background image to the screen
self.screen.blit(self.bgImage,(0,0))
'''
Gun
Represents the gun and its current properties, and displays the crosshair
on the screen
'''
class Gun(object):
'''
__init__
Initialize the Gun class
parameters:
screen - the screen of the game
cam - the Camera input, to get its x and y values
ammo - the maximum amount of ammo in the gun
returns: none
'''
def __init__(self,screen,cam, ammo):
# The pyGame screen
self.screen = screen
# The Camera of the game
self.cam = cam
# Initiailize position of crosshair
self.x = 0
self.y = 0
# Load the image/size of the crosshair and bullet into the game
self.crosshair = pygame.image.load('target.png')
self.bullet = pygame.image.load('bullet.png').convert_alpha()
self.gunSize = self.crosshair.get_size()
# Initiailze the ammo and ammo to reload to
self.ammo = ammo
self.rAmmo = ammo
# The bullets should only be shown when the game is being played
self.bulletShow = True
# Set the font of the text
self.font = pygame.font.SysFont("Comic Sans MS", self.screen.get_size()[1]/30)
# Set the hit radius of the gun and the number of
# bullets the gun shoots
self.hitRadius = self.screen.get_size()[1]/100
self.numShot =1
'''
reloaded
Reloads the gun
parameters: none
returns: none
'''
def reloaded(self):
# Reset the ammo to the reload amount
self.ammo = self.rAmmo
'''
isEmpty
Checks if the gun is out of ammo
parameters: none
returns: True or False depending on if ammo has run out
'''
def isEmpty(self):
# If the amount of ammo is 0, then return True, else return False
if self.ammo == 0:
return True
return False
'''
update
Update the Gun class, including crosshair position and bullets
parameters: none
returns: none
'''
def update(self):
# If the game is being played, then show the bullets in the corner
if self.bulletShow:
# Show a bullet for every ammo the user's gun has
for i in range(1,self.ammo+1):
toShow = pygame.transform.scale(self.bullet, (int(0.3*(self.bullet.get_size()[0])), int(0.3*(self.bullet.get_size()[1]))))
self.screen.blit(toShow,(self.screen.get_size()[0]/30*i,self.screen.get_size()[1]/35))
# If there are no more bullets, indicate that the gun is empty
if self.isEmpty():
# Display the 'Gun is Empty' text where the bullets should be
text3 = self.font.render("Gun is Empty", 1,(240, 10, 10))
self.screen.blit(text3,(self.screen.blit(text3,(self.screen.get_size()[0]/16,self.screen.get_size()[1]/25))))
# Set the crosshair position to the position indicated by the camera
self.x = self.cam.x
self.y = self.cam.y
# Display the crosshair on the screen
self.screen.blit(self.crosshair,(self.x-self.gunSize[0]/2,self.y-self.gunSize[1]/2))
'''
Shotgun
Shotgun that extends the Gun class, with different properties as the normal
Gun class
'''
class Shotgun(Gun):
'''
__init__
Initialize the Shotgun class
parameters:
screen - the screen of the game
cam - the Camera input, to get its x and y values
ammo - the maximum amount of ammo in the gun
returns: none
'''
def __init__(self,screen,cam, ammo):
# Call init of the Gun superclass
super(Shotgun, self).__init__(screen, cam, ammo)
# Modify the hit radius, number of shots, and crosshair size
self.hitRadius = self.screen.get_size()[1]/20
self.numShot = 25
self.crosshair = pygame.transform.scale2x(pygame.image.load('target.png'))
class Bomb(Gun):
'''
__init__
Initialize the Bomb class
parameters:
screen - the screen of the game
cam - the Camera input, to get its x and y values
ammo - the maximum amount of ammo in the gun
returns: none
As with the Shotgun class, the Bomb class inherits from the Gun class.
'''
def __init__(self,screen,cam, ammo):
# Call init of the Gun superclass
super(Bomb, self).__init__(screen, cam, ammo)
# Modify the hit radius, number of shots, and crosshair size
self.hitRadius = self.screen.get_size()[1]/20
self.numShot = 25
self.crosshair = pygame.transform.scale2x(pygame.image.load('bomb1.png'))
'''
Scalar
It is used to scale different objects to different sizes depending on
where the object is down the road. This helps make a 3-D effect in the game.
'''
class Scaler:
'''
__init__
Initialize the Scalar class
parameters:
yRange - the values of two sample y values of the road
xRange1 - the values of the road beginning and ending x value
corresponding to the first yRange value
xRange2 - the values of the road beginning and ending x value
corresponding to the second yRange value
returns: none
'''
def __init__(self, yRange, xRange1, xRange2):
# Initializes the yRange, xRange1, and xRange2
self.yRange = yRange
self.xRange1 = xRange1
self.xRange2 = xRange2
'''
scale
Finds the scaling factor for a width of an object at the y=1 position
of the road for a given y position on the road
parameters:
yVal - the y value corresponding to the road position to which
the width should be scaled to
initWidth - the width of the object at y=1 of the road
returns:
The scaling factor of the object
'''
def scale(self,yVal,initWidth):
# Find scaled width at the second yRange value
wScaled=(self.xRange2[1]-self.xRange2[0])*initWidth/(self.xRange1[1]-self.xRange1[0])
# Find the relative Y coordinate multiple in relation to the second
# yRange value
relY = yVal*1.0/(self.yRange[1]-self.yRange[0])
# Find the width at the given y value and return a scaling factor
newWidth = (wScaled-initWidth)*relY+initWidth
return newWidth/initWidth
'''
findX
Finds the exact x cooridnate given the y position on the road and the
relative x position on the road
parameters:
yVal - y position on road for which x position needs to be found
relX - relative x position on road at given y value
returns:
x position on screen corresponding to given y value and rel. x
'''
def findX(self,yVal,relX):
# Find relative y distance as a scalar multiple of 2nd yRange value
relDist = 1.0*(yVal-self.yRange[0])/(self.yRange[1]-self.yRange[0])
# Find road width at given y value
newRoadWidth = 1.0*((self.xRange2[1]-self.xRange2[0])-(self.xRange1[1]-self.xRange1[0]))*relDist+(self.xRange1[1]-self.xRange1[0])
# Return absolute x position, after calculating offset from beginning
# of road and x position relative to the beginning of the road
xValOffset = newRoadWidth*relX
startX = (self.xRange2[0]-self.xRange1[0])*relDist+self.xRange1[0]
return startX + xValOffset
'''
Wall
Represents a wall that the enemies can hide behind
'''
class Wall:
'''
__init__
Initialize the Wall class
parameters:
screen - pyGame screen
pos - bottom center position of the wall
width - width of the wall
height - height of the wall
image - a picture of the wall
returns: none
'''
def __init__(self, screen, pos, width, height, image):
# The pyGame screen
self.screen = screen
# Position, width, and height of wall
self.pos = pos
self.height = height
self.width = width
# Load actual image of wall
self.image = pygame.transform.scale(image, (int(self.width),int(self.height)))
'''
isHit
Checks if wall has been hit by a bullet
parameters:
pos - position of bullet
returns:
True if wall is hit, and false otherwise
'''
def isHit(self,pos):
# Wall is not hit if the x position of pos is outside the wall boundaries
if pos[0]<self.pos[0]-self.width/2 or pos[0]>self.pos[0]+self.width/2:
return False
# Wall is not hit if the y position of pos is outside the wall boundaries
elif pos[1]<self.pos[1]-self.height or pos[1]>self.pos[1]:
return False
# Wall is hit if code reaches this far
else:
return True
'''
update
Display the wall on the screen
parameters: none
returns: none
'''
def update(self):
# Display the image of the wall on the screen and a black outline
pygame.draw.rect(self.screen,(0,0,0),Rect((int(self.pos[0]-self.width/2.0)-2,int(self.pos[1]-self.height)-2),((int(self.width)+4,int(self.height)+4))))
self.screen.blit(self.image,(int(self.pos[0]-self.width/2.0),int(self.pos[1]-self.height)))
'''
WallRow
Represents a row of walls on the road
'''
class WallRow:
'''
__init__
Initializes the WallRow class
parameters:
screen - the game screen
yPos - y position of the row of walls
height - height of the walls in the class
scalar - the scalar class to help scale walls
edged - indicates if walls touch edges of road
gapWidth - the sizes of gaps between the walls
numGaps - the number of gaps
last - indicates if this is the last wall row
wallImage - image of the wall
returns: none
'''
def __init__(self,screen,yPos,height,scaler,edged, gapWidth, numGaps, last, wallImage):
# The pyGame screen
self.screen = screen
# y position and height of wall row
self.yPos = yPos
self.height=height
# Scaler to help scale walls
self.scaler=scaler
# Determines of walls touch egdges
self.edged = edged
# Gap widths and number of gaps
self.gapWidth = gapWidth
self.numGaps = numGaps
# Is this the last wall row?
self.last = last
# image of the wall
self.wallImage = wallImage
# List to store all the walls
self.walls = []
# Lists/variable to store x positions and y position of covers and
# exits of the wall row
self.xCovers = []
self.xExits = []
self.yCover = yPos - height*.2
# If the wall row is edged, then the number of covers/exits is twice
# the number of gaps
if edged:
self.positions = range(numGaps*2)
# Otherwise it is twice one less the number of gaps
else:
self.positions = range((numGaps-1)*2)
# Find the width of the road at the y position of the wall row
roadWidth = scaler.scale(yPos,scaler.xRange1[1]-scaler.xRange1[0])*(scaler.xRange1[1]-scaler.xRange1[0])
# Find the number of walls given if the wall row is edged and
# the number of gaps
walls = 0
if edged:
walls = numGaps + 1
else:
walls = numGaps - 1
# Find the width of each wall in the wall row
wallWidth = (roadWidth - numGaps*gapWidth)/walls
# Find the x position at the beginning of the road at the given
# y value of the road
xInit = self.scaler.findX(self.yPos,0)
# If the wall row is edged
if edged:
# For each wall
for i in range(numGaps+1):
# Find the x position of the wall and add it to the list of walls
xPos = i*wallWidth+i*gapWidth+wallWidth/2+xInit
self.walls.append(Wall(self.screen,(xPos,self.yPos),wallWidth, self.height, self.wallImage))
# Add the x positions of all the covers and exits of the wall
# row, depending on if the wall is on the ends or in the
# middle
if i==0:
self.xCovers.append((xPos+wallWidth/4.0-xInit)/roadWidth)
self.xExits.append((xPos+wallWidth/2.0+gapWidth/4.0-xInit)/roadWidth)
elif i==numGaps:
self.xCovers.append((xPos-wallWidth/4.0-xInit)/roadWidth)
self.xExits.append((xPos-wallWidth/2.0-gapWidth/4.0-xInit)/roadWidth)
else:
self.xCovers.append((xPos-wallWidth/4.0-xInit)/roadWidth)
self.xCovers.append((xPos+wallWidth/4.0-xInit)/roadWidth)
self.xExits.append((xPos-wallWidth/2.0-gapWidth/4.0-xInit)/roadWidth)
self.xExits.append((xPos+wallWidth/2.0+gapWidth/4.0-xInit)/roadWidth)
# But if the wall is not edged
else:
# For each wall
for i in range(numGaps-1):
# Find the x position of the wall and add it to the list of walls
xPos = i*wallWidth+i*gapWidth+wallWidth/2+gapWidth+xInit
self.walls.append(Wall(self.screen,(xPos,self.yPos),wallWidth, self.height, self.wallImage))
# Add the x positions of the covers and exits
self.xCovers.append((xPos-wallWidth/4.0-xInit)/roadWidth)
self.xCovers.append((xPos+wallWidth/4.0-xInit)/roadWidth)
self.xExits.append((xPos-wallWidth/2.0-gapWidth/4.0-xInit)/roadWidth)
self.xExits.append((xPos+wallWidth/2.0+gapWidth/4.0-xInit)/roadWidth)
'''
isHit
Checks to see if any of the walls in the wall row is hit
parameters:
pos - position of bullet
returns:
True if any walls are hit, and false otherwise
'''
def isHit(self,pos):
# Check if any of the walls are hit
for wall in self.walls:
if wall.isHit(pos):
return True
# If none of the walls are hit, return False
return False
'''
update
Display all the walls in the wall row
'''
def update(self):
# Display each wall in the wall row
for wall in self.walls:
wall.update()
'''
Enemy
Represents all the enemies in the game
'''
class Enemy:
'''
__init__
Initializes the Enemy class
parameters:
screen - the game screen
pos - the position of the enemy
relPos - relative position of enemy in relation to wallRow
cover index
level - the level wallRow the enemy is at
images - sprites for the enemies
scalar - to help scale the enemy sizes
returns: none
'''
def __init__(self, screen, pos, relPos, level, images, scaler):
# The pyGame screen
self.screen=screen
# The initial position of the enemy. The y position of the enemy is
# stored as the pixel position on the screen, and the x position is
# stored as a value from [0,1], depending on how far along the enemy
# is on the road
self.pos=pos
# Position of enemy in terms of cover index and wallRow index
self.relPos = relPos
self.level = level
# Images to visually represent enemies
self.images = images
# Scaler to help scale the enemy sizes on the screen
self.scaler = scaler
# Initial width and speed of enemies
self.initWidth = 25.0
self.initSpeed = 2.0
# Store the height and width of enemy so other classes can access it
self.height = 0
self.width = 0
# Resetting the directions given to the enemy, and making him
# available for instructions. This includes a queue of instructions,
# current status of enemy, its direction, and its target
self.queue = []
self.status = 'available'
self.direction = 'none'
self.oldDirection = self.direction
self.target = -1
# Specifically to limit time enemy shoots for
self.shootingTimer = -1
# Variables to control changing of enemy pictures so they are
# animated. Timer will store current time of program, wait stores
# time between picture changes
self.currentPic = 'front2'
self.timer = -1
self.wait = .1
# To handle enemies succesfully shooting at user
self.hurtUser = False;
self.hurtUserProb = .01
'''
updatePosition
Update the wallRow cover index and wallRow level index
parameters:
relPos - new wallRow cover index
level - new wallRow level index
returns: none
'''
def updatePosition(self,relPos,level):
# Set new relPos and level
self.relPos = relPos
self.level = level
'''
updateQueue
Allows other classes to update the queue of the enemy so it knows what
to do
parameters:
directions - list of instructions for enemy
returns: none
'''
def updateQueue(self,directions):
# Add the given directions to the enemy's queue
self.queue.extend(directions)
'''
getImage
Finds the correct image of the enemy to display on the screen
parameters: none
returns:
An image representing the enemy's state to display on the screen
'''
def getImage(self):
# If the direction has changed
if self.oldDirection!=self.direction:
# Reset the timer
self.timer = time.time()
# Set the default picture based on the new direction of the enemy
if self.direction == 'forward':
self.currentPic = 'front1'
elif self.direction == 'left':
self.currentPic = 'left1'
elif self.direction == 'right':
self.currentPic = 'right1'
elif self.direction == 'shoot':
self.currentPic = 'shoot1'
# If the enemy is not given a direction, then default to forward
# facing image
else:
self.currentPic = 'front2'
# If the direction has stayed the same, but too much time has passed
# on a single image being displayed on the screen
elif time.time() - self.timer > self.wait:
# Switch between walking forward images
if self.currentPic == 'front1':
self.currentPic = 'front3'
elif self.currentPic == 'front3':
self.currentPic = 'front1'
# Switch between walking left images
elif self.currentPic == 'left1':
self.currentPic = 'left3'
elif self.currentPic == 'left3':
self.currentPic = 'left1'
# Switch between walking right images
elif self.currentPic =='right1':
self.currentPic = 'right3'
elif self.currentPic =='right3':
self.currentPic = 'right1'
# Switch between shooting images
elif self.currentPic =='shoot1':
# Randomly determine if enemy has succesfully shot user
if random.random() < self.hurtUserProb:
self.hurtUser = True
self.currentPic = 'shoot2'
elif self.currentPic =='shoot2':
self.currentPic = 'shoot1'
# Reset the timer
self.timer = time.time()
# Set oldDirection variable to compare for next iteration
self.oldDirection = self.direction
# Return appropriate image
return self.images[self.currentPic]
'''
move
Moves the enemy depending on the instructions it has in its queue
parameters: none
returns: none
'''
def move(self):
# If the enemy is not avaiable for new instructions
if self.status != 'available':
# Find the speed of the enemy based on its y position
speed = .2*(self.initSpeed*self.scaler.scale(self.pos[1],self.initSpeed))**2
# If the enemy's current direction is forward
if self.direction=='forward':
# Update the position of the enemy so he walks forward
self.pos = (self.pos[0],self.pos[1]+speed)
# If the enemy has reached its target, reset his status and
# make him available for new instructions
if self.pos[1] > self.target:
self.pos = (self.pos[0],self.target)
self.status='available'
self.direction='none'
self.target=-1
# If the enemy's current direction is left
elif self.direction=='left':