-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab8_1.py
More file actions
306 lines (266 loc) · 10.4 KB
/
Lab8_1.py
File metadata and controls
306 lines (266 loc) · 10.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
# racer
import pygame, random, sys, os, time
from pygame.locals import *
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 6
BADDIEMAXSPEED = 10
ADDNEWBADDIERATE = 15
ADDNEWCOINRATE = 40
ADDSPECIALCOINRATE = 175
PLAYERMOVERATE = 5
count = 3
cscore = 0
touch = 0
score = 0
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
def playerHasHitCoin(playerRect, coins):
for b in coins:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('car race')
pygame.mouse.set_visible(False)
# fonts
font = pygame.font.SysFont(None, 30)
# sounds
direct = "IGRA/"
gameOverSound = pygame.mixer.Sound(os.path.join(direct, "SOUNDS/music_crash.wav"))
pygame.mixer.music.load(os.path.join(direct, "SOUNDS/music_car.wav"))
laugh = pygame.mixer.Sound(os.path.join(direct, "SOUNDS/music_laugh.wav"))
gameOverSound.set_volume(0.1)
laugh.set_volume(0.1)
# images
playerImage = pygame.image.load(os.path.join(direct, "PICTURES/car1.png"))
car3 = pygame.image.load(os.path.join(direct, "PICTURES/car3.png"))
car4 = pygame.image.load(os.path.join(direct, "PICTURES/car4.png"))
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load(os.path.join(direct, "PICTURES/car2.png"))
sample = [car3, car4, baddieImage]
wallLeft = pygame.image.load(os.path.join(direct, "PICTURES/left.png"))
wallRight = pygame.image.load(os.path.join(direct, "PICTURES/right.png"))
coin = pygame.image.load(os.path.join(direct, "PICTURES/coin.png"))
coin2 = pygame.image.load(os.path.join(direct, "PICTURES/coin2.png"))
# "Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3) + 30)
pygame.display.update()
waitForPlayerToPressKey()
zero = 0
if not os.path.exists(os.path.join(direct, "DATA/save.dat")):
f = open(os.path.join(direct, "DATA/save.dat"), 'w')
f.write(str(zero))
f.close()
v = open(os.path.join(direct, "DATA/save.dat"), 'r')
topScore = int(v.readline())
v.close()
while (count > 0):
# start of the game
baddies = []
coins = []
coins2 = []
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
coinAddCounter = 0
specialcoinAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.1)
while True: # the game loop
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
if event.key == ord('x'):
slowCheat = False
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
# Add new baddies at the top of the screen
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize = 30
newBaddie = {'rect': pygame.Rect(random.randint(140, 485), 0 - baddieSize, 23, 47),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface': pygame.transform.scale(random.choice(sample), (23, 47)),
}
baddies.append(newBaddie)
sideLeft = {'rect': pygame.Rect(0, 0, 126, 600),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface': pygame.transform.scale(wallLeft, (126, 599)),
}
baddies.append(sideLeft)
sideRight = {'rect': pygame.Rect(497, 0, 303, 600),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface': pygame.transform.scale(wallRight, (303, 599)),
}
baddies.append(sideRight)
if not reverseCheat and not slowCheat:
coinAddCounter += 1
if coinAddCounter == ADDNEWCOINRATE:
coinAddCounter = 0
coinSize = 15
newCoin = {'rect': pygame.Rect(random.randint(140, 485), 0 - coinSize, 15, 15),
'speed': 8,
'surface': pygame.transform.scale(coin, (23, 23)),
}
coins.append(newCoin)
if not reverseCheat and not slowCheat:
specialcoinAddCounter += 1
if specialcoinAddCounter == ADDSPECIALCOINRATE:
specialcoinAddCounter = 0
newCoin2 = {'rect': pygame.Rect(random.randint(140, 485), 0 - coinSize, 15, 15),
'speed': 8,
'surface': pygame.transform.scale(coin2, (23, 23)),
}
coins2.append(newCoin2)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
for b in coins:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
for b in coins[:]:
if b['rect'].top > WINDOWHEIGHT:
coins.remove(b)
for b in coins2:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
for b in coins2[:]:
if b['rect'].top > WINDOWHEIGHT:
coins2.remove(b)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 128, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 128, 20)
drawText('Rest Life: %s' % (count), font, windowSurface, 128, 40)
drawText('Coin score: %s' % (cscore), font, windowSurface, 600, 0)
windowSurface.blit(playerImage, playerRect)
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
for b in coins:
windowSurface.blit(b['surface'], b['rect'])
for b in coins2:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the car have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
g = open(os.path.join(direct, "DATA/save.dat"), 'w')
g.write(str(score))
g.close()
topScore = score
break
for b in coins:
if playerHasHitCoin(playerRect, coins):
coins.remove(b)
cscore += 1
BADDIEMAXSPEED +=1
for b in coins2:
if playerHasHitCoin(playerRect, coins2):
coins2.remove(b)
cscore += 3
BADDIEMAXSPEED +=3
mainClock.tick(FPS)
# "Game Over" screen.
pygame.mixer.music.stop()
count = count - 1
gameOverSound.play()
time.sleep(1)
if (count == 0):
laugh.play()
drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 30)
pygame.display.update()
time.sleep(2)
waitForPlayerToPressKey()
count = 3
BADDIEMAXSPEED = 10
cscore = 0
score=0
gameOverSound.stop()