forked from asweigart/inventwithpython3rded
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdodger.html
More file actions
449 lines (381 loc) · 13 KB
/
Copy pathdodger.html
File metadata and controls
449 lines (381 loc) · 13 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
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dodger</title>
<script src="../jsgame0.js"></script>
<style type="text/css" media="screen">
body {
background-color: white;
color: black;
}
.hidden {
display: none;
}
#original {
margin-left: 1em;
}
</style>
</head>
<body>
<section id="imageLoader" class="hidden">
<img class="hidden" src="images/baddie.png" alt="baddie" data-name="baddie">
<img class="hidden" src="images/player.png" alt="player" data-name="player">
</section>
<section id="soundLoader" class="hidden">
<audio class="hidden" controls preload="auto" src="sounds/gameover.wav" data-name="gameover">Your browser does not support the audio element.</audio>
</section>
<main>
<h1>Dodger</h1>
<canvas id="screen">
The game screen appears here if your browser supports the Canvas API.
</canvas>
<section id="controls">
<button type="button" id="reset">Reset</button>
<button type="button" id="pause">Pause</button>
</section>
<p>jsgame0 cannot play midi.</p>
<h2>Attribution</h2>
<p>From chapter 20.</p>
<p>Licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/us/legalcode">Creative Commons BY-NC-SA</a>.</p>
<h2>Original Python code</h2>
<pre id="original"><code>
import pygame, random, sys
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 1
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
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: # pressing escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
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('Dodger')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
# set up images
playerImage = pygame.image.load('player.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('baddie.png')
# show the "Start" screen
drawText('Dodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
# set up the start of the game
baddies = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop runs while the game part is playing
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
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
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
if event.type == MOUSEMOTION:
# If the mouse moves, move the player where the cursor is.
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)),
}
baddies.append(newBaddie)
# 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)
# Move the mouse cursor to match the player.
pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
# Move the baddies down.
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)
# Delete baddies that have fallen past the bottom.
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
# Draw the player's rectangle
windowSurface.blit(playerImage, playerRect)
# Draw each baddie
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
topScore = score # set new top score
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
</code></pre>
</main>
<script>
WIDTH = 600;
HEIGHT = 600;
TITLE = 'Dodger';
const FONT_SIZE = 48;
const TEXTCOLOR = [255, 255, 255];
const BACKGROUNDCOLOR = [0, 0, 0];
const BADDIEMINSIZE = 10;
const BADDIEMAXSIZE = 40;
const BADDIEMINSPEED = 1;
const BADDIEMAXSPEED = 8;
const ADDNEWBADDIERATE = 6;
const PLAYERMOVERATE = 5;
/*
* Return a random integer N such that min <= N < max.
*/
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor((Math.random() * (max - min)) + min);
}
const State = Object.freeze({
START: 1,
PLAY: 2,
GAME_OVER: 3
});
var state, player, topScore, baddies, score, baddieAddCounter;
function reset() {
state = State.START;
player = new Actor('player');
topScore = localStorage.getItem('topScore');
if (topScore == null) {
topScore = 0;
}
else {
topScore = parseInt(topScore, 10);
}
// set up the start of the game
baddies = [];
score = 0;
player.topleft = [WIDTH / 2, HEIGHT - 50];
baddieAddCounter = 0;
}
function draw() {
// Draw the game world on the window.
screen.fill(BACKGROUNDCOLOR);
if (state === State.START) {
// show the "Start" screen
screen.draw.text('Dodger', {
fontsize: FONT_SIZE,
color: TEXTCOLOR,
topleft: [Math.floor(WIDTH / 3), Math.floor(HEIGHT / 3)]
});
screen.draw.text('Press a key to start.', {
fontsize: FONT_SIZE,
color: TEXTCOLOR,
topleft: [Math.floor(WIDTH / 3) - 30, Math.floor(HEIGHT / 3) + 50]
});
}
else if (state === State.PLAY) {
// Draw the score and top score.
screen.draw.text('Score: ' + score, {
fontsize: FONT_SIZE,
color: TEXTCOLOR,
topleft: [10, 0]
});
screen.draw.text('Top Score: ' + topScore, {
fontsize: FONT_SIZE,
color: TEXTCOLOR,
topleft: [10, 40]
});
// Draw the player's rectangle
player.draw();
// Draw each baddie
for (let b of baddies) {
screen.blit('baddie', b);
}
}
else if (state === State.GAME_OVER) {
// Stop the game and show the "Game Over" screen.
screen.draw.text('GAME OVER', {
fontsize: FONT_SIZE,
color: TEXTCOLOR,
topleft: [Math.floor(WIDTH / 3), Math.floor(HEIGHT / 3)]
});
screen.draw.text('Press a key to play again.', {
fontsize: FONT_SIZE,
color: TEXTCOLOR,
topleft: [Math.floor(WIDTH / 3) - 80, Math.floor(HEIGHT / 3) + 50]
});
}
}
function update() {
if (state !== State.PLAY) {
return;
}
score += 1; // increase score
let reverseCheat = keyboard[keys.Z],
slowCheat = keyboard[keys.X];
// Add new baddies at the top of the screen, if needed.
if ((!reverseCheat) && (!slowCheat)) {
baddieAddCounter += 1;
}
else {
// Reset the score when the player is using cheats
score = 0;
}
if (baddieAddCounter === ADDNEWBADDIERATE) {
baddieAddCounter = 0;
let baddieSize = getRandomInteger(BADDIEMINSIZE, BADDIEMAXSIZE + 1),
newBaddie = new Rect(getRandomInteger(0, WIDTH - baddieSize + 1), 0 - baddieSize, baddieSize, baddieSize);
newBaddie.speed = getRandomInteger(BADDIEMINSPEED, BADDIEMAXSPEED + 1);
baddies.push(newBaddie);
}
// Move the player around.
if ((keyboard[keys.LEFT] || keyboard[keys.A]) && (player.left > 0)) {
player.left -= PLAYERMOVERATE;
}
if ((keyboard[keys.RIGHT] || keyboard[keys.D]) && (player.right < WIDTH)) {
player.right += PLAYERMOVERATE;
}
if ((keyboard[keys.UP] || keyboard[keys.W]) && (player.top > 0)) {
player.top -= PLAYERMOVERATE;
}
if ((keyboard[keys.DOWN] || keyboard[keys.S]) && (player.bottom < HEIGHT)) {
player.top += PLAYERMOVERATE;
}
// Move the baddies down.
for (let b of baddies) {
if ((!reverseCheat) && (!slowCheat)) {
b.move_ip(0, b.speed);
}
else if (reverseCheat) {
b.move_ip(0, -5);
}
else if (slowCheat) {
b.move_ip(0, 1);
}
}
// Delete baddies that have fallen past the bottom.
baddies = baddies.filter(b => (b.top <= HEIGHT));
// Check if any of the baddies have hit the player.
for (let b of baddies) {
if (player.colliderect(b)) {
state = State.GAME_OVER;
if (score > topScore) {
topScore = score; // set new top score
localStorage.setItem('topScore', topScore);
}
sounds.gameover.play();
return;
}
}
}
function on_key_down(key, mod, unicode) {
if (state !== State.PLAY) {
state = State.PLAY;
// set up the start of the game
baddies = [];
score = 0;
player.topleft = [WIDTH / 2, HEIGHT - 50];
baddieAddCounter = 0;
}
}
window.addEventListener('load', (event) => {
screen.init();
});
</script>
</body>
</html>