-
Notifications
You must be signed in to change notification settings - Fork 0
/
crazy_spin_pvc.py
614 lines (512 loc) · 19.9 KB
/
crazy_spin_pvc.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
import math
import os
import pygame
import random
import time
os.chdir(os.path.join(os.path.abspath(os.path.curdir), u'assets'))
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
grey = (185, 185, 185)
olivedrab = (51, 51, 0)
green = (0, 204, 0)
yellow = (255, 204, 0)
red = (255, 0, 0)
light_green = (0, 255, 0)
light_yellow = (255, 219, 77)
light_red = (255, 102, 102)
brown = (153, 102, 51)
blue = (51, 102, 255)
light_blue = (77, 166, 255)
smallFont = pygame.font.SysFont("comicsansms", 25)
medFont = pygame.font.SysFont("comicsansms", 40)
largeFont = pygame.font.SysFont("comicsansms", 80)
display_width = 800
display_height = 600
# create display surface
gameDisplay = pygame.display.set_mode([display_width, display_height])
# name the window
pygame.display.set_caption("Crazy Spin PvC")
# set icon
iconImg = pygame.image.load("icon.png")
pygame.display.set_icon(iconImg)
# load background image
backgroundImg = pygame.image.load("background_image.png")
pygame.transform.scale(backgroundImg, [display_width, display_height])
# load sounds
padBounceSound = pygame.mixer.Sound("pad_bounce.wav")
edgeBounceSound = pygame.mixer.Sound("edge_bounce.wav")
cheerSound = pygame.mixer.Sound("cheer.wav")
whistleSound = pygame.mixer.Sound("whistle.wav")
backgroundMusic = pygame.mixer.music.load("background_music.wav")
clock = pygame.time.Clock()
# game wide constants
pad_length = int(display_height / 6) # 100
pad_width = int(display_width / 45) # 17
ball_size = int(display_height / 40) # 15
effect_size = 30
pad_speed = int(display_height / 45) # 13
ball_speed_init = int(display_height / 50) # 12
ball_speed_rate = 1.05
ball_spin_effect = 1.1
ball_spin_fade = 0.008
edge_bounce_limit = 10
win_condition = 10
FPS = 45
# ball reflection lambdas
def x_reflect(x): return 360 - x
def y_reflect(x): return 180 - x
def dumb(): return random.randint(1, 10) == 1
# create text objects
def text_objects(msg, color, size):
if size == "small":
screen_text = smallFont.render(msg, True, color)
elif size == "medium":
screen_text = medFont.render(msg, True, color)
elif size == "large":
screen_text = largeFont.render(msg, True, color)
return screen_text, screen_text.get_rect()
# display mmessage
def displayMsg(msg, color, y_displace=0, size="small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (display_width / 2, display_height / 2 + y_displace)
gameDisplay.blit(textSurf, textRect)
# display score of players
def displayDetail(left_score, right_score, edge_bounce):
scoreSurf, scoreRect = text_objects(
str(left_score)+" : "+str(right_score), black, "small")
scoreRect.center = (display_width / 2, 30)
gameDisplay.blit(scoreSurf, scoreRect)
if right_score != win_condition and left_score != win_condition:
if right_score == win_condition - 1:
msg = "Game Point"
bounceSurf, bounceRect = text_objects(msg,
black,
"small")
bounceRect.center = (display_width / 2 + 100, 30)
gameDisplay.blit(bounceSurf, bounceRect)
if left_score == win_condition - 1:
msg = "Game Point"
bounceSurf, bounceRect = text_objects(msg,
black,
"small")
bounceRect.center = (display_width / 2 - 100, 30)
gameDisplay.blit(bounceSurf, bounceRect)
if edge_bounce >= edge_bounce_limit - 3:
msg = "Ball respawn after "+str(
edge_bounce_limit-edge_bounce)+" edge bounce"
bounceSurf, bounceRect = text_objects(msg, black, "small")
bounceRect.center = (display_width / 2, 60)
gameDisplay.blit(bounceSurf, bounceRect)
# display text for buttons
def buttonText(msg, color, location, size="small"):
button_x, button_y, button_width, button_height = location
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (
(button_x + button_width/2), (button_y + button_height/2))
gameDisplay.blit(textSurf, textRect)
# display responsive button
def displayButton(
text,
location, unfocus_color, focus_color, text_color=black, action=None):
bX, bY, bWidth, bHeight = location
cursor = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if bX + bWidth > cursor[0] > bX and bY + bHeight > cursor[1] > bY:
pygame.draw.rect(gameDisplay, focus_color, location)
if click[0]:
action()
else:
pygame.draw.rect(gameDisplay, unfocus_color, location)
buttonText(text, text_color, location)
def displayBackground():
gameDisplay.fill(white)
gameDisplay.blit(backgroundImg, [0, 0])
pygame.draw.rect(
gameDisplay, light_blue, [0, 0, pad_width, display_height])
pygame.draw.rect(gameDisplay, light_blue, [display_width - pad_width,
0,
pad_width,
display_height])
# display player pads
def displayPad(x, y, length):
pygame.draw.rect(gameDisplay, black, [x, y, pad_width, length])
# display ball
def displayBall(x, y):
pygame.draw.rect(gameDisplay, red, [x, y, ball_size, ball_size])
# reset ball position and variables
def ballReset(side):
if side == "left":
ball_dir = random.randint(130, 230)
x_adjust = 0.3
ball_x = int((display_width - ball_size) / 2 + display_width * 0.3)
ball_y = int((display_height - ball_size) / 2)
ball_speed = ball_speed_init
ball_spin = 0
elif side == "right":
ball_dir = random.randint(-50, 50)
ball_x = int((display_width - ball_size) / 2 - display_width * 0.3)
ball_y = int((display_height - ball_size) / 2)
ball_speed = ball_speed_init
ball_spin = 0
time.sleep(2)
return ball_x, ball_y, ball_dir, ball_speed, ball_spin
# reset pad position and variables
def padReset():
temp = int((display_height - pad_length) / 2)
return temp, temp
# work out the coordination of the actual hit point
def hit_point(cur_x, cur_y, dir, hit_x=None, hit_y=None):
if hit_x is not None and hit_y is None:
return cur_y - (cur_x - hit_x) * math.tan(math.radians(dir))
elif hit_x is None and hit_y is not None:
return cur_x - (cur_y - hit_y) / math.tan(math.radians(dir))
else:
raise ValueError("only one of hit_x and hit_y should be given.")
# game initiate window
def gameInit():
pygame.mixer.music.play(-1)
# check response
gameStart = False
while not gameStart:
# display initiate window
gameDisplay.blit(backgroundImg, [0, 0])
displayMsg("Pong PvC", olivedrab, -170, "large")
displayMsg(
"Move the pads to bouce the ball and guard the goal", brown, -70)
displayMsg("hit while moving you pad to add spin.", brown, -40)
displayMsg("First one to 10 wins!", brown, -10)
displayMsg("Player defualt - W and S", brown, 20)
# display bottons
displayButton(
"Play", [150, 400, 100, 50], green, light_green, action=gameLoop)
displayButton(
"Settings",
[350, 400, 100, 50], yellow, light_yellow, action=gameSettings)
displayButton(
"Quit", [550, 400, 100, 50], red, light_red, action=gameQuit)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameQuit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
gameLoop()
elif event.key == pygame.K_s:
gameSettings()
elif event.key == pygame.K_q:
gameQuit()
clock.tick(FPS)
# game initiate window
def gameSettings():
with open("settings.qgd", 'r') as f:
data = [int(line.replace('\n', '')) for line in f.readlines()]
# check response
while True:
# display title and instructions
gameDisplay.blit(backgroundImg, [0, 0])
displayMsg("Settings", olivedrab, -230, "large")
displayMsg(
"Please do not modify settings with text editor!", brown, -140)
# display sound settings
displayMsg("Game-time music", brown, -110)
if data[4]:
displayMsg("On [press B]", brown, -80)
else:
displayMsg("Off [Press B]", brown, -80)
displayMsg("Sound effects", brown, -50)
if data[5]:
displayMsg("On [Press V]", brown, -20)
else:
displayMsg("Off [Press V]", brown, -20)
# display key set settings
cursor_x, cursor_y = pygame.mouse.get_pos()
if cursor_y <= display_height/2:
setKeyName = "Pad moves Up"
setKeyNo = 0
else:
setKeyName = "Pad moves Down"
setKeyNo = 1
displayMsg(
"Move the cursor to upper or lower side to change key.", brown, 10)
displayMsg("You can not use key that are pre-defined!", brown, 40)
displayMsg("Set Key for: " + setKeyName, brown, 70)
displayMsg(
"Current Key: " + pygame.key.name(data[setKeyNo]), brown, 100)
# back button
click = pygame.mouse.get_pressed()
if 350 + 100 > cursor_x > 350 and 480 + 50 > cursor_y > 480:
pygame.draw.rect(gameDisplay, light_green, [350, 480, 100, 50])
if click[0]:
with open('settings.qgd', 'w') as f:
f.write('\n'.join(map(str, data)))
return
else:
pygame.draw.rect(gameDisplay, green, [350, 480, 100, 50])
buttonText("Back", black, [350, 480, 100, 50])
# renew display
pygame.display.flip()
# check for key set
for event in pygame.event.get():
if event.type == pygame.QUIT:
with open('settings.qgd', 'w') as f:
f.write('\n'.join(map(str, data)))
gameQuit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
gameLoop()
elif event.key == pygame.K_q:
with open('settings.qgd', 'w') as f:
f.write('\n'.join(map(str, data)))
gameQuit()
elif event.key == pygame.K_b:
data[4] = 0 if data[4] else 1
elif event.key == pygame.K_v:
data[5] = 0 if data[5] else 1
elif event.key not in data:
data[setKeyNo] = event.key
clock.tick(FPS)
# game pausing window
def gamePause():
# stop music and sound effects
pygame.mixer.music.pause()
pygame.mixer.stop()
pygame.mouse.set_visible(True)
displayMsg("Paused", red, -100, "large")
displayMsg("Don't want to have fun with your mates?", black, 25, "medium")
pygame.display.flip()
# wait for response
gamePaused = True
while gamePaused:
cursor = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if 200 + 100 > cursor[0] > 200 and 380 + 50 > cursor[1] > 380:
pygame.draw.rect(gameDisplay, light_green, [200, 380, 100, 50])
if click[0]:
pygame.mouse.set_visible(False)
return
else:
pygame.draw.rect(gameDisplay, green, [200, 380, 100, 50])
buttonText("Continue", black, [200, 380, 100, 50])
displayButton(
"Quit", [500, 380, 100, 50], red, light_red, action=gameQuit)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameQuit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameQuit()
elif event.key == pygame.K_p:
pygame.mixer.music.unpause()
pygame.mouse.set_visible(False)
gamePaused = False
clock.tick(FPS)
# game over window
def gameOver(side):
pygame.mixer.Sound.play(cheerSound)
pygame.mouse.set_visible(True)
displayMsg("Game Over", olivedrab, -150, "large")
displayMsg(side.title() + " won!", brown, -50)
displayMsg("Do you want to play again with the computer?", brown, -20)
# check response
gameStart = False
while not gameStart:
# display bottons
displayButton(
"Rematch",
[250, 380, 100, 50], green, light_green, action=gameLoop)
displayButton(
"Quit", [450, 380, 100, 50], red, light_red, action=gameQuit)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameQuit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
pygame.mixer.stop()
gameLoop()
elif event.key == pygame.K_q:
gameQuit()
clock.tick(FPS)
# main loop of the game
def gameLoop():
with open("settings.qgd", 'r') as f:
data = [int(line.replace('\n', '')) for line in f.readlines()]
# initiate using settings
pygame.mouse.set_visible(False)
gameDisplay.blit(backgroundImg, [0, 0])
displayMsg("Initiating...", black, -250, "large")
displayMsg("Please wait for a while.", red, -160)
leftPadUp, leftPadDown, rightPadUp, rightPadDown = data[:4]
backgroundMusicOn, soundEffectOn = data[4:]
if not backgroundMusicOn:
pygame.mixer.music.pause()
# initiate loop condition variables
gameExit = False
leftScore = 0
rightScore = 0
edgeBounce = 0
# initiate pad variables
leftPadX = 0
leftPadY = int((display_height - pad_length) / 2)
leftPadMove = 0
leftPadLength = pad_length
rightPadX = display_width - pad_width
rightPadY = int((display_height - pad_length) / 2)
rightPadMove = 0
rightPadLength = pad_length
# leftPadLength = display_height # test left side full-length pad
# initiate ball variables
serveSide = random.choice(["left", "right"])
ballX, ballY, ballDir, ballSpeed, ballSpin = ballReset(serveSide)
# play-time loop
while not gameExit:
# control the pads
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == leftPadUp:
leftPadMove -= pad_speed
elif event.key == leftPadDown:
leftPadMove += pad_speed
elif event.key == pygame.K_p:
gamePause()
elif event.type == pygame.KEYUP:
if event.key == leftPadUp:
leftPadMove += pad_speed
elif event.key == leftPadDown:
leftPadMove -= pad_speed
# computer intelligence
if not dumb():
if ballY - ball_size <= rightPadY:
rightPadMove = -pad_speed
elif ballY >= rightPadY + pad_length:
rightPadMove = pad_speed
else:
rightPadMove = 0
# ball right and left edge and pad bounce
if ballX <= pad_width:
ballSpin *= -1
edgeBounce = 0
if (ballY + ball_size < leftPadY or
ballY > leftPadY + leftPadLength):
pygame.display.flip()
if soundEffectOn:
pygame.mixer.Sound.play(whistleSound)
serveSide = "left"
ballX, ballY, ballDir, ballSpeed, ballSpin = ballReset(
serveSide)
leftPadY, rightPadY = padReset()
rightScore += 1
else:
if soundEffectOn:
pygame.mixer.Sound.play(padBounceSound)
ballSpin += leftPadMove / pad_speed
ballDir = y_reflect(ballDir)
ballSpeed *= ball_speed_rate
elif ballX >= display_width - pad_width - ball_size:
ballSpin *= -1
edgeBounce = 0
if (ballY + ball_size < rightPadY or
ballY > rightPadY + rightPadLength):
if soundEffectOn:
pygame.mixer.Sound.play(whistleSound)
serveSide = "right"
ballX, ballY, ballDir, ballSpeed, ballSpin = ballReset(
serveSide)
leftPadY, rightPadY = padReset()
leftScore += 1
else:
if soundEffectOn:
pygame.mixer.Sound.play(padBounceSound)
ballSpin += rightPadMove / pad_speed
ballDir = y_reflect(ballDir)
ballSpeed *= ball_speed_rate
# ball upper and lower edge bounce
if ballY <= 0 or ballY >= display_height - ball_size:
if soundEffectOn:
pygame.mixer.Sound.play(edgeBounceSound)
edgeBounce += 1
ballDir = x_reflect(ballDir)
# ball spin and move ball
ballDir += ballSpin * ball_spin_effect
ballSpin *= 1 - ball_spin_fade
ballX += int(math.cos(math.radians(ballDir)) * ballSpeed)
ballY += int(math.sin(math.radians(ballDir)) * ballSpeed)
# move pads
leftPadY += leftPadMove
rightPadY += rightPadMove
# pad hit edge
if leftPadY < 0:
leftPadY = 0
elif leftPadY > display_height - leftPadLength:
leftPadY = display_height - leftPadLength
if rightPadY < 0:
rightPadY = 0
elif rightPadY > display_height - rightPadLength:
rightPadY = display_height - rightPadLength
# ball over move rewind
if ballY <= 0:
ballX = hit_point(ballX, ballY, ballDir, hit_y=0)
ballY = 0
elif ballY >= display_height - ball_size:
ballX = hit_point(
ballX, ballY, ballDir, hit_y=display_height - ball_size)
ballY = display_height - ball_size
if ballX <= pad_width:
ballX = pad_width
ballY = hit_point(ballX, ballY, ballDir, hit_x=pad_width)
elif ballX >= display_width - pad_width - ball_size:
ballX = display_width - pad_width - ball_size
ballY = hit_point(
ballX,
ballY, ballDir, hit_x=display_width - pad_width - ball_size)
# display game objects
displayBackground()
displayDetail(leftScore, rightScore, edgeBounce)
displayPad(leftPadX, leftPadY, leftPadLength)
displayPad(rightPadX, rightPadY, rightPadLength)
displayBall(ballX, ballY)
pygame.display.flip()
# edge bounce limit check
if edgeBounce >= edge_bounce_limit:
edgeBounce = 0
ballX, ballY, ballDir, ballSpeed, ballSpin = ballReset(serveSide)
leftPadY, rightPadY = padReset()
# win condition check
if leftScore >= win_condition:
gameOver("player")
elif rightScore >= win_condition:
gameOver("computer")
# frames per second
clock.tick(FPS)
# out of loop quit game
gameQuit()
# combo quit
def gameQuit():
pygame.mixer.music.pause()
pygame.mixer.stop()
pygame.quit()
quit()
# game exception page
def gameExcept():
gameDisplay.fill(white)
displayMsg("Ops!", red, -90, "large")
displayMsg("An unexpected error occurs!", black, -10)
displayMsg("Press any key or close button to quit.", black, 30)
pygame.display.flip()
# game over waiting response
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.KEYDOWN:
gameQuit()
clock.tick(FPS)
# if __name__ == "__main__":
# try:
gameInit()
# except SystemExit:
# pass
# except:
# gameExcept()