-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstarlight.py
356 lines (326 loc) · 11.3 KB
/
starlight.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
import aubio
import audioop
import math
import numpy
import os
import pyaudio
import pygame as pg
import random
# from sense_hat import SenseHat
import time
import threading
from typing import List
# some global variable
main_dir = os.path.split(os.path.abspath(__file__))[0]
SCREENRECT = pg.Rect(0, 0, 640, 360)
OBSTACLE_RELOAD_FRAME = 120
SCORE = 0
DISTANCE = 0
# sense = SenseHat()
# sense.low_light = True
W = (255, 255, 255)
P = (0, 0, 0)
R = (255, 0, 0)
G = (0, 255, 0)
Y = (255, 255, 0)
B = (0, 0, 255)
def move_marble(pitch, x, y):
if pitch >= 360:
new_y = 0
elif pitch < 50:
new_y = 6
else:
new_y = pitch / 50
new_y = math.floor(new_y)
new_y = 6 - new_y
return x, new_y
def move_food(maze, foodx, foody, notex, notey, counter):
#when food ate
randomFood = False
score = 0
if ((foodx == notex) and (foody == notey)):
randomFood = True
score = 1
if(foodx <= 0):
randomFood = True
elif(foodx > 0):
if counter == 5:
foodx -= 1
#spawn new food
if randomFood:
foodx = 7
foody = random.randint(3, 7)
maze[foody][foodx] = B
return maze, foodx, foody, score
def marble(maze, notex, notey, pitch):
notex, notey = move_marble(pitch, notex, notey)
if pitch == 1:
maze[notey][notex] = W
elif pitch == 2:
maze[notey][notex] = R
else:
maze[notey][notex] = Y
# maze[foodPosY][foodPosX] = R
return maze, notex, notey
def load_image(file):
"""loads an image, prepares it for play"""
file = os.path.join(main_dir, "data", file)
try:
surface = pg.image.load(file)
except pg.error:
raise SystemExit(f'Could not load image "{file}" {pg.get_error()}')
return surface.convert_alpha()
def load_sound(file):
"""because pygame can be compiled without mixer."""
if not pg.mixer:
return None
file = os.path.join(main_dir, "data", file)
try:
sound = pg.mixer.Sound(file)
return sound
except pg.error:
print(f"Warning, unable to load, {file}")
return None
def load_music(file):
"""because pygame can be compiled without mixer."""
if not pg.mixer:
return None
file = os.path.join(main_dir, "data", file)
try:
music = pg.mixer.music.load(file)
pg.mixer.music.play(-1)
return music
except pg.error:
print(f"Warning, unable to load, {file}")
return None
def microphone_setup():
pa = pyaudio.PyAudio()
stream = pa.open(format = pyaudio.paFloat32,channels=1,rate=44100,input_device_index=1,input=True,frames_per_buffer=1024)
pDetection = aubio.pitch("default", 4096, 1024, 44100)
pDetection.set_unit("Hz")
pDetection.set_silence(-30)
return pa, stream, pDetection
class Obstacle(pg.sprite.Sprite):
"""Player needs to get over it, XD"""
speed = -15
images: List[pg.Surface] = []
def __init__(self, *groups):
pg.sprite.Sprite.__init__(self, *groups)
self.image = self.images[0]
self.rect = self.image.get_rect(center=(640, (60+random.random()*300)))
def update(self):
"""called every loop"""
self.rect.move_ip(self.speed, 0)
if self.rect.right <= 0:
self.kill()
class Hadouken(pg.sprite.Sprite):
"""Hadouken will be generated by player, should be cool"""
speed = 20
images: List[pg.Surface] = []
def __init__(self, pos, *groups):
pg.sprite.Sprite.__init__(self, *groups)
self.image = self.images[0]
self.rect = self.image.get_rect(center=pos)
def update(self):
"""called every loop"""
self.rect.move_ip(self.speed, 0)
if self.rect.left >= 720:
self.kill()
class Explosion(pg.sprite.Sprite):
"""Just an explosion"""
total_frame = 12
cycle = 3
images: List[pg.Surface] = []
def __init__(self, actor, *groups):
pg.sprite.Sprite.__init__(self, *groups)
self.image = self.images[0]
self.rect = self.image.get_rect(center=actor.rect.center)
self.life = self.total_frame
def update(self):
"""Show the animation frame by frame"""
self.life = self.life - 1
self.image = self.images[self.life // self.cycle % 2]
if self.life <= 0:
self.kill()
class Player(pg.sprite.Sprite):
"""0 for idle, 1 for moving, 2 for jumping"""
hadouken_offset = 0
images: List[pg.Surface] = []
def __init__(self, *groups):
pg.sprite.Sprite.__init__(self, *groups)
self.image = self.images[0]
self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
self.reloading = 0
self.origtop = self.rect.top
self.facing = -1
self.moving = False
# print("hello madafaka player, why I cant see you")
def rest(self):
self.image = self.images[0]
self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
self.moving = False
#print("resting")
def move(self):
"""actually move the background"""
self.image = self.images[1]
self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
self.moving = True
print("moving")
def jump(self):
"""show state change"""
self.image = self.images[2]
self.moving = True
print("jumping")
def jump_volume(self, value):
"""move upward and downward"""
self.image = self.images[2]
self.rect.top = 324 - value
self.moving = True
print("jumping")
def groups(self):
# pos = self.facing * self.hadouken_offset + self.rect.centerx
pos = self.rect.centerx
# return pos, self.rect.right
return pos, self.rect.centery
def main(winstyle=0):
"""audio input setup"""
pa, stream, pDetection = microphone_setup()
"""program flow"""
obstacle_reload = OBSTACLE_RELOAD_FRAME
running = True
pg.init()
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
"""SCORE & DISTANCE"""
SCORE = 0
DISTANCE = 0
token = 0
"""senseHat setting"""
notex, notey, foodx, foody = 3, 6, 7, 3
maze = [[P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P],
[P, P, P, P, P, P, P, P],
[G, G, G, G, G, G, G, G]]
"""display setup"""
winstyle = 0 #window
bestdepth = pg.display.mode_ok(SCREENRECT.size, winstyle, 32)
screen = pg.display.set_mode(SCREENRECT.size, winstyle, bestdepth)
# pg.display.flip()
"""resource initiazation after screen setup"""
Player.images = [load_image(im) for im in ("idle.jpg", "move.webp", "jump.bmp")]
Hadouken.images = [load_image("hadouken-removebg-preview.png")]
Hadouken.images[0] = pg.transform.scale(Hadouken.images[0] , (32,32))
Obstacle.images = [load_image("wall.bmp")]
Obstacle.images[0] = pg.transform.scale(Obstacle.images[0] , (32,128))
img = load_image("explosion1.gif")
Explosion.images = [img, pg.transform.flip(img, 1, 1)]
# create the background, tile the background image if needed
bgdtile = load_image("yasuhati_bg.bmp")
background = pg.Surface(SCREENRECT.size)
for x in range(0 , SCREENRECT.width, bgdtile.get_width()):
background.blit(bgdtile, (x, 0))
screen.blit(bgdtile, (0, 0))
pg.display.update()
"""Sound effects and bgm"""
hadouken_sound = load_sound("hadouken.mp3")
death_sound = load_sound("sf_death.mp3")
theme_song = load_music("sf_theme.mp3")
"""Initialize Game Groups"""
hadoukens = pg.sprite.Group()
obstacles = pg.sprite.Group()
"""initial obstacle reload parameter"""
clock = pg.time.Clock()
clock_div = 0
"""set player """
all = pg.sprite.RenderUpdates()
player = Player(all)
last_pitch = 0.0
while player.alive():
clock.tick(30)
for event in pg.event.get():
if event.type == pg.QUIT:
return
keystate = pg.key.get_pressed()
# jump = keystate[pg.K_SPACE]
modern_command = keystate[pg.K_p]
# print(command)
if (not player.moving) and (not player.reloading) and modern_command:
Hadouken(player.groups(), hadoukens, all)
hadouken_sound.play()
player.reloading = modern_command
# check volume
raws=stream.read(1024, exception_on_overflow = False)
samples=numpy.frombuffer(raws, dtype=numpy.float32)
numpy.set_printoptions(threshold=numpy.inf)
# rms = audioop.rms(samples, 2)
pitch = pDetection(samples)[0]
# print(rms)
if (pitch - last_pitch) > 360:
pitch = last_pitch
else:
last_pitch = pitch
if pitch > 200:
adjusted = pitch - 200
player.jump_volume(adjusted)
DISTANCE = DISTANCE + 1
maze, notex, notey = marble(maze, notex, notey,adjusted)
print(pitch)
elif pitch > 10:
player.move()
DISTANCE = DISTANCE + 1
maze, notex, notey = marble(maze, notex, notey, 2)
print(pitch)
else:
player.rest()
maze, notex, notey = marble(maze, notex, notey, 1)
if clock_div == 5:
clock_div = 0
else:
clock_div = clock_div + 1
maze, foodx, foody, token = move_food(maze, foodx, foody, notex, notey, clock_div)
SCORE = SCORE + token
# sense.set_pixels(sum(maze,[]))
maze[notey][notex] = P
maze[foody][foodx] = P
# scroll da background
i = 0
# Create new obstacle
if obstacle_reload:
obstacle_reload = obstacle_reload - 1
elif not int(random.random() * 20):
Obstacle(obstacles, all)
obstacle_reload = OBSTACLE_RELOAD_FRAME
# hadouken is good
for obstacle in pg.sprite.groupcollide(hadoukens, obstacles, 1,1):
Explosion(obstacle, all)
# GG sumida
for obstacle in pg.sprite.spritecollide(player, obstacles, 1):
if pg.mixer and death_sound is not None:
death_sound.play()
Explosion(player, all)
result = (str(DISTANCE))
result += "M, "
result += (str(SCORE))
result += "FOOD"
# sense.show_message(result,text_colour=R)
player.kill()
pg.display.flip()
# clear/erase the last drawn sprites
all.clear(screen, background)
# update all the sprites
all.update()
dirty = all.draw(screen)
pg.display.update(dirty)
# draw the elements
pg.mixer.music.stop()
# call the "main" function
if __name__ == "__main__":
main()
pg.quit()
# sense.clear()