forked from vojtapolasek/united_guards
-
Notifications
You must be signed in to change notification settings - Fork 0
/
united_guards.py
executable file
·309 lines (281 loc) · 10.3 KB
/
united_guards.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
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#version 0.2 alpha, released on September 03, 2012 by Vojtěch Polášek <[email protected]>
#This is the first testing version of my first game, so nothing is guaranteed actually
#see included README file for more info
#initialisation
import time
import pygame
import os.path
import random
import sys
import gettext
import locale
import menu
import speech
#gettext initialisation
gettext.bindtextdomain('messages', 'lang')
gettext.textdomain('messages')
_ = gettext.gettext
#pygame initialisation
pygame.init()
pygame.display.set_mode((320, 200))
pygame.display.set_caption ('United guards')
#pygame.event.set_allowed([pygame.QUIT, pygame.KEYUP, pygame.KEYDOWN])
#initialisation of speech
try:
lang=locale.getdefaultlocale()[0]
except AtributeError, IndexError:
lang=None
if lang and (os.path.exists(os.path.normpath("lang/" + lang)) or os.path.exists(os.path.normpath("lang/" + lang.split("_")[0]))):
lang=lang.split("_")[0]
else:
lang="en"
s =speech.Speaker(language=lang)
#pass needed functions to menu module
menu.s = s
#menu._ = gettext.gettext
#define menus
#define main menu
start = menu.menuitem(_("Start the game"), "__main__.g.startgame(5, 3)")
instructions = menu.menuitem(_("Read instructions"), "__main__.readmanual()")
quit = menu.menuitem(_("Quit the game"), "__main__.g.quit ()")
main_menu = menu.menu(_("Welcome to the main menu. Use up and down arrows to select an item, enter to confirm and escape to quit."), [start, instructions, quit])
#define pause game prompt
continuegame = menu.menuitem(_("Continue the game"), "__main__.g.resumegame()")
abort = menu.menuitem(_("Abort the game and return to the main menu."), "__main__.g.abortgame()")
abortprompt = menu.menu(_("Do you really want to abort the game?"), [continuegame, abort])
#channel initialisation
pygame.mixer.set_reserved(2)
chan=pygame.mixer.Channel(0)
mgchan = pygame.mixer.Channel(1)
class game:
def __init__(self):
self.lives = None
self.delay = None #delay between attacks
self.rand = None #used in generating of direction and checking user input
self.score = 0
self.target_falling = False #True when attack is pending
self.previous = None #stores last needed time
self.remaining = None #stores time when game is paused
self.paused = False
self.pressed = False
self.menu_active = None #indicates if we are in menu
self.game_active = None #indicates if we are in actual game
self.running = True #indicates if main loop is running
self.current_menu = None
self.initSounds()
def position(self):
"""sets random positionn of falling sound."""
self.target_falling = True
self.previous = time.time()
self.rand = random.randrange(0, 3)
if self.rand == 0:
self.left = 1
self.right = 0.1
elif self.rand == 1:
self.left = 1
self.right = 1
elif self.rand == 2:
self.left = 0.1
self.right = 1
self.planenum = random.randrange (0, self.planeCount)
self.cutplane = self.soundcut(self.planeSounds[self.planenum], self.orig_delay - self.delay)
chan.play(self.cutplane)
chan.set_volume(self.left, self.right)
def check(self, input):
"""checks user input"""
self.pressed = True
if input == self.rand and time.time() < self.previous + self.delay:
self.score += 100 * round ((time.time () - self.previous), 3)
self.missileSounds[input].play()
pygame.time.delay(250)
mgchan.play(self.planehitSounds[0])
mgchan.set_volume(self.left, self.right)
chan.fadeout (200)
self.rand=None
self.delay -= 0.05
self.previous = time.time() + self.delay * 1.2
self.target_falling = False
else:
self.missileSounds[input].play ()
pygame.time.delay(int(self.missileSounds[input].get_length()*1000))
self.die()
self.lives -= 1
self.previous = time.time()
self.target_falling = False
self.previous = time.time() + self.cutplane.get_length() - (time.time() - self.previous)
def die(self):
rand = random.randrange (0, self.mgCount)
mgchan.play (self.mgSounds[rand])
mgchan.set_volume (self.left, self.right)
for i in range (3):
randvar = random.randrange (0, self.ricochetCount)
self.ricochetSounds[randvar].play()
pygame.time.delay(100)
for i in range (2):
randvar = random.randrange (0, self.bhitCount)
self.bhitSounds[randvar].play()
pygame.time.delay(100)
randvar = random.randrange (0, self.deadCount)
self.deadSounds[randvar].play()
def soundcut (self, sound, time_to_cut):
"""Accepts pygame sound object and cuts time_to_cut from its beginning, using numpy array slicing. Returns pygame sound object."""
length = sound.get_length()
snd_array = pygame.sndarray.array(sound)
frame_rate = len(snd_array) / length
cut_frames = frame_rate * time_to_cut
result = snd_array [cut_frames:]
soundresult = pygame.sndarray.make_sound (result)
return soundresult
def startgame(self, lives, delay):
"""starts game and initialises variables."""
self.previous = time.time()
self.lives = lives
self.orig_delay = self.delay = delay
self.score = 0
self.target_falling = False
self.rand = None
self.remaining = None
self.pressed = False
self.game_active = True
self.menu_active = False
self.position()
def loop(self):
"""main game loop."""
while self.running == True:
pygame.time.delay(1)
event = pygame.event.poll ()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
if self.game_active == True:
self.pausegame()
elif event.key == pygame.K_RETURN:
if self.menu_active == True:
self.current_menu.select()
elif event.key == pygame.K_LEFT:
if self.game_active == True:
if self.pressed == False:
self.check(0)
elif event.key == pygame.K_UP:
if self.menu_active == True:
self.current_menu.moveup()
elif self.game_active == True:
if self.pressed == False:
self.check(1)
elif event.key == pygame.K_RIGHT:
if self.game_active == True:
if self.pressed == False:
self.check(2)
elif event.key == pygame.K_DOWN:
if self.menu_active == True:
self.current_menu.movedown()
elif event.key == pygame.K_s:
if self.game_active == True:
s.say(_("Your score is {0}.").format(self.score), 1)
elif event.key == pygame.K_l:
if self.game_active == True:
s.say (_("You have {0} lives remaining.").format(self.lives), 1)
elif event.key == pygame.K_LCTRL or event.key == pygame.K_RCTRL:
s.stop()
if self.game_active == True:
#print "game part"
if self.lives <= 0:
pygame.time.delay(1000)
s.say (_("Game Over. Your final score is {0}.").format(self.score), 1)
self.current_menu = main_menu.init ()
self.game_active = False
self.menu_active = True
if (time.time() >= self.previous + self.delay - self.aimSounds[0].get_length()) and self.target_falling == True:
# print "aiming"
mgchan.play (self.aimSounds[0])
# mgchan.set_volume (self.left, self.right)
if (time.time() >= self.previous + self.delay) and self.target_falling == True:
self.pressed = True
mgchan.stop()
self.die()
self.previous = time.time() + self.cutplane.get_length() - self.delay
self.lives -=1
self.target_falling = False
elif (time.time() >= self.previous) and self.target_falling == False:
# print "next plane"
self.position()
self.pressed = False
def pausegame(self):
pygame.mixer.pause()
self.remaining = time.time() - (self.previous + self.delay)
self.game_active = False
self.menu_active = True
self.current_menu = abortprompt.init()
def resumegame(self):
self.previous = time.time() + self.remaining
pygame.mixer.unpause()
self.menu_active = False
self.game_active = True
def abortgame(self):
pygame.mixer.stop()
self.remaining = None
self.current_menu = main_menu.init()
def quit (self):
s.say (_("Exiting now."), 1)
s.quit ()
pygame.quit ()
sys.exit ()
def initSounds(self):
self.planehitSounds = [
pygame.mixer.Sound (os.path.normpath("sounds/planehit.ogg"))
]
self.aimSounds =[
pygame.mixer.Sound(os.path.normpath("sounds/aim.ogg"))
]
staticSounds =[
"planehit.ogg",
"aim.ogg"
]
self.planeSounds=[]
self.mgSounds=[]
self.missileSounds=[]
self.deadSounds=[]
self.bhitSounds=[]
self.ricochetSounds=[]
dir="sounds"
for fileName in os.listdir(dir):
if not os.path.isfile(os.path.normpath("%s/%s"%(dir,fileName))) and not fileName.endswith(".ogg") or fileName in staticSounds:
continue
if fileName.startswith("plane"):
self.planeSounds.append(pygame.mixer.Sound(os.path.normpath("%s/%s"%(dir,fileName))))
continue
if fileName.startswith("mg"):
self.mgSounds.append(pygame.mixer.Sound(os.path.normpath("%s/%s"%(dir,fileName))))
continue
if fileName.startswith("aim"):
self.aimSounds.append(pygame.mixer.Sound(os.path.normpath("%s/%s"%(dir,fileName))))
continue
if fileName.startswith("missile"):
self.missileSounds.append(pygame.mixer.Sound(os.path.normpath("%s/%s"%(dir,fileName))))
continue
if fileName.startswith("dead"):
self.deadSounds.append(pygame.mixer.Sound(os.path.normpath("%s/%s"%(dir,fileName))))
continue
if fileName.startswith("bhit"):
self.bhitSounds.append(pygame.mixer.Sound(os.path.normpath("%s/%s"%(dir,fileName))))
continue
if fileName.startswith("ricoch"):
self.ricochetSounds.append(pygame.mixer.Sound(os.path.normpath("%s/%s"%(dir,fileName))))
continue
self.planeCount=len(self.planeSounds)
self.mgCount=len(self.mgSounds)
self.missileCount=len(self.missileSounds)
self.deadCount=len(self.deadSounds)
self.bhitCount=len(self.bhitSounds)
self.ricochetCount=len(self.ricochetSounds)
print("ricochet sounds %d"%self.ricochetCount)
def readmanual():
s.say (_("This is very simple. Listen for incoming planes and press corresponding arrow (Left, Up or Right) to launch a missile in given direction.\nPress L to announce number of remaining lives and S to announce your score.\nPress ESCAPE to pause the game.\nHave fun!"), 1)
if __name__ == "__main__":
s.say(_("Welcome to the game."), 1)
g = game()
g.current_menu = main_menu.init()
g.menu_active = True
g.game_active = False
g.loop()