def __init__(self, name): self.name = name self.curr_cursor_idx = SCREENS[name]["default_cursor_idx"] self.cursor_positions = SCREENS[name]["cursor_positions"] self.num_cursor_positions = len(self.cursor_positions) self.bg = SCREENS[name]["path"] self.audio = Sound()
def __init__( self, grid_size=3, humans=0, bots=2, testing=False, difficulty=1, ): self.width = 800 self.height = 600 self.determine_grid_size(grid_size) self.create_screen() self.audio = Sound() self.out_of_bounds_length = 50 self.x_boundary = (self.width // 2) - self.out_of_bounds_length self.y_boundary = (self.height // 2) - self.out_of_bounds_length self.grid = self.create_grid() self.humans = humans self.bots = bots self.difficulty = difficulty self.players = [] self.particles = [] self.game_on = True self.testing = testing self.create_assets()
def main(): com = Communication() sound = Sound() try: executor = concurrent.futures.ThreadPoolExecutor(max_workers=2) # start MIDI as a concurrent executor sound.quit_midi = False midi_sender = executor.submit(send_midi, sound) # init serial communication # ser = com.init_serial() com.init_serial() # start serial as a concurrent executor quit_recv = False serial_receiver = executor.submit(recv_serial, com, sound) # start video stream video_stream(com , sound) # this block is for stoping process with terminating receive after video_stream()finished while True: try: key = input() time.sleep(1) # wait for checking input if(key == KEY_RECEIVER_STOP): print("accepted f command for stopping \n") break # if anything from standard input, write back to AVR. key += "\n" com.ser.write(str.encode(key)) except: print(traceback.format_exc()) print("\nstop receiver and midi sender thread\n") exit(1) except concurrent.futures.CancelledError: print(traceback.format_exc()) print("executor is cancelled\n") except: print(traceback.format_exc()) finally: print("main is waiting for stopping threas") # do not wait the queue empty as AVR is working asynchronouly # serial_q.join() com.quit_recv = True sound.quit_midi = True # wait until executor(receiver) finishes while not serial_receiver.done(): time.sleep(1) while not midi_sender.done(): time.sleep(1) print("main finished") exit(0)
class Tower(object): def __init__(self, imagePath, x, y, hp=100): self.image = pygame.image.load(imagePath) self.health = hp self.x = x self.y = y self.h = self.image.get_height() self.w = self.image.get_width() self.hitSound = Sound(SOUND_PATH_EXPLOSION, False) self.hitSound.set_volume(0.4) def getRect(self): return pygame.Rect(self.x, self.y, self.w, self.h) def draw(self, surface): surface.blit(self.image, (self.x, self.y)) def checkDestroyed(self): if self.health <= 0: self.x = DEFAULT_VALUE self.y = DEFAULT_VALUE def update(self, surface, enemy): if self.getRect().colliderect(enemy.getRect()): self.health -= 10 self.hitSound.play() enemy.health = 0 enemy.dispose()
def main(): """ Main function, we set volume to minimum start time :return: """ global logger global counter global timer timer = time.perf_counter() keyboard.on_press(on_press_reaction) while True: current_time = time.perf_counter() if current_time - timer > 1: """ Rotate deque and put new value on end""" logger.pop(0) logger.append(counter) counter = 0 timer = current_time value = sum(logger) / len(logger) volume = (value + (((MAX_WPM * 5) / 60) * MIN_VOLUME)) / ((MAX_WPM * 5) / 60) if volume > MAX_VOLUME: volume = MAX_VOLUME volume = floor(volume * 100) Sound.volume_set(volume)
def toggle_radio (self, on): if Touchevent.event(): # brightness control Sound.play(CONFIG.CLICK_SOUND) request = CONFIG.RADIO.BASE_URL request += "showapp" if on else "radiooff" self.call_url(request)
class HandStateMachine: IN = 0 OUT = 1 def __init__(self, wav_file, delay_frames): self.state = self.OUT self.wav_file = wav_file self.sound = Sound(wav_file) self.delay_frames = delay_frames self.frame_cnt = 0 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.sound.shutdown() def state_in(self): if self.state == self.OUT and self.frame_cnt is 0: self.sound.play() self.frame_cnt = self.delay_frames pass self.state = self.IN self.frame_cnt = max(self.frame_cnt - 1, 0) def state_out(self): self.state = self.OUT self.frame_cnt = max(self.frame_cnt - 1, 0)
def __init__(self, outfile): super(Board, self).__init__() self.filename = outfile self.coord = { 'center' :((config.BOARD_DIM+1)//2, (config.BOARD_DIM+1)//2), 'arrow_up' :(0, (config.BOARD_DIM+1)//2), 'arrow_down' :(config.BOARD_DIM+1, (config.BOARD_DIM+1)//2), 'arrow_left' :((config.BOARD_DIM+1)//2, 0), 'arrow_right' :((config.BOARD_DIM+1)//2, (config.BOARD_DIM+1)), 'corner_top_left' :(1, 1), 'corner_top_right' :(1, config.BOARD_DIM), 'corner_bottom_left' :(config.BOARD_DIM, 1), 'corner_bottom_right':(config.BOARD_DIM, config.BOARD_DIM), 'previous_move':(), 'current_move':(), 'last_correct':(), } if os.path.isfile(self.filename): print('warning: file "%s" exists and will be erased' % self.filename) os.remove(self.filename) self.reset_vars() if config.ARDUINO_USED: self.arduino = Arduino() self.sound = Sound() self.time = Time() self.grid = QtWidgets.QGridLayout() self.draw_board() self.draw_arrows() self.set_ui_elements()
def __init__(self, width, height): super().__init__(width, height) self.width = width self.height = height arcade.set_background_color(arcade.color.BLACK) self.on_menu = True # self.on_menu = False self.menu_selecting = 0 self.max_menu = 2 self.selector_sprite = arcade.Sprite('images/selector.png') self.selector_sprite.set_position(200, 255) self.menu_screen = arcade.Sprite('images/menu.png') self.menu_screen.set_position(width/2, height/2) self.menu_keys = [] self.instruction_screen = arcade.Sprite('images/instruction.jpg') self.instruction_screen.set_position(width/2, height/2) self.on_instruction = False self.menu_prop = arcade.Sprite('images/planet3-6.png') self.menu_prop_x = 650 self.menu_prop_y = 150 self.menu_prop_direction = 'up' self.menu_prop.set_position(self.menu_prop_x, self.menu_prop_y) self.gameover_screen = arcade.Sprite('images/gameover.jpg') self.gameover_screen.set_position(width/2, height/2) self.gameover = False self.gameover_selecting = 0 self.gameover_keys = [] self.max_gameover_menu = 2 self.sound = Sound() self.pause = False
def stopsound(): # Sound.say_tts("") Sound.stop_sound() global socialscript_t if socialscript_t != None: socialscript_t.stop(); return {"status": "success"}
def __init__(self): os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.mixer.pre_init(44100, -16, 2, 4096) pygame.init() if FULL_SCREEN == True: if os.name == "nt": self.screen = pygame.display.set_mode( SCREEN_SIZE, FULLSCREEN | HWSURFACE | DOUBLEBUF, COLOR_DEPTH) else: self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, COLOR_DEPTH) else: self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, COLOR_DEPTH) pygame.display.set_caption(GAME_NAME) self.clock = pygame.time.Clock() self.timer = time.time() - 5 self.game_started = False self.menu = Menu(self) self.sound = Sound() self.sprites = pygame.sprite.OrderedUpdates() self.font = pygame.font.Font( os.path.join('data', 'misc', 'coopbl.ttf'), 28) self.initialize_game()
def start_game(self): self.level.reset() level_map = self.level.get_level() self.game_over = False self.stats = GameStats(settings=self.settings) self.sb = Scoreboard(settings=self.settings, screen=self.screen, stats=self.stats) self.sound = Sound() self.maze = Maze(settings=self.settings, screen=self.screen) self.maze.get_maze() self.grid_pts = Grid_Pnts_Group(settings=self.settings, screen=self.screen, txt_file=level_map["mazename"]) self.foods = FoodGroup(settings=self.settings, screen=self.screen, food_file=level_map["foodname"]) self.pacman = Pacman(game=self, settings=self.settings, screen=self.screen, grid_pts=self.grid_pts, foods=self.foods, sb=self.sb) self.ghosts = Ghost_Group(game=self, settings=self.settings, screen=self.screen, grid_pts=self.grid_pts) self.pellets_eaten = 0 self.settings.pacman_lives = self.settings.starting_lives self.fruit = None self.pause.force(True)
def __init__(self): pygame.display.set_caption("Visualizer") self.window = pygame.display.set_mode(size=(WIDTH, HEIGHT)) self.window.fill([0, 0, 0]) self.running = True self.top_pixels, self.bot_pixels = [], [] # Top pixel self.top_color = Color(rgb=WHITE) self.top_pixel = Pixel(CENTER[0], CENTER[1], RADIUS, self.top_color, facing='RIGHT', win=self.window) # Bottom pixel self.bot_color = Color(rgb=BLUE) self.bot_pixel = Pixel(CENTER[0], CENTER[1], RADIUS, self.bot_color, facing='LEFT', win=self.window) self.sound = Sound()
def run(self): self.__loadConfigs() self.player = pyaudio.PyAudio() # hacky solution, but in this way the console will only print the error once for ii in range(self.player.get_device_count()): self.player.get_device_info_by_index(ii) self.__dailTone = Sound(self.player, './music/kiestoon.wav') self.__dailTone.repeat = True self.rotator = Rotator( self.config.get('DialerRedGpio', self.DAILER_STEP_PIN_DEFAULT), self.config.get('DialerYellowGpio', self.DAILER_ISON_PIN_DEFAULT) ) self.rotator.when_dailed = self.dailed self.hook = gpiozero.Button(self.config.get('HookGpio', self.HOOK_PIN_DEFAULT)) self.hook.when_released = self.offHook self.hook.when_pressed = self.onHook print('t65 started') if not self.hook.is_pressed: # start offHook when it's already of the hook self.offHook() self.__mainLoop()
def update_volume(): line = ser.readline() deco = line.decode("utf-8") sensor_value = int(deco) target_volume = min(4 * sensor_value, 100) Sound.volume_set(target_volume) print("Target volume is : {0}".format(target_volume)) return str(target_volume)
def __init__(self, ipc): self.ipc = ipc self.Log = Logger("SoundHandler") self.sound = Sound() #add callback to ipc handler self.ipc.add_message_callback(self.on_message) self.ipc.start()
def reset_counter(self): """resets the timer and switches alarm off""" if Touchevent.event(): # brightness control Sound.play(CONFIG.CLICK_SOUND) self.reset_event = True countdown.reset() self.timer.set("") self.timerdisplay.pack_forget()
def alarm(): duration = 3500 # millisecond freq = 8000 # Hz if Sound.is_muted(): Sound.mute() Sound.volume_max() winsound.Beep(freq, duration) return "alarm sounded"
def __init__(self, host, port, media_path): self.media = Sound() self.loop = asyncio.get_event_loop() self.server = Server(host, port, self.background_tasks, self.shutdown_tasks) self.dir = media_path self.server.on_post('media', 'play', self.handle_play) self.server.on_post('media', 'stop', self.handle_stop) self.server.on_get('media', self.handle_get_media)
def toggle (self): if Touchevent.event(): # brightness control Sound.play(CONFIG.CLICK_SOUND) try: urlopen(CONFIG.URL_ANTEROOM_CONTROL, timeout=2) except (HTTPError, URLError): Log("HTTPError, URLError: {0[0]} {0[1]}".format(sys.exc_info())) except socket.timeout: Log("socket.timeout: {0[0]} {0[1]}".format(sys.exc_info()))
class Controller: def __init__(self): user_dir = Path.home() data_path = Path.joinpath(user_dir, '.' + FILE_NAME) self.is_raspberry_pi = is_raspberry_pi() self.model = Model(data_path) self.sound = Sound(self.model) self.root = Tk.Tk() self.view = View(self.model, self) def run(self): gpio_polling_thread = threading.Thread(target=self.start_gpio_polling) # set as deamon such that the thread is killed when the main thread is killed gpio_polling_thread.setDaemon(True) gpio_polling_thread.start() self.root.title(NAME) self.root.deiconify() self.root.mainloop() def play_sound(self, sound_number): self.sound.play(sound_number) def start_gpio_polling(self): if self.is_raspberry_pi: GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) pressed = {} # setup pins for bcm_number in self.model.bcm_pin_numbers: GPIO.setup(bcm_number, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) pressed[bcm_number] = False # poll pins while True: for assigned_bcm_number in self.model.get_assigned_bcm_numbers( ): if GPIO.input(assigned_bcm_number) == GPIO.HIGH: pressed[assigned_bcm_number] = True time.sleep(0.1) self.sound.play( self.model.get_sound_number_for_bcm_number( assigned_bcm_number)) while GPIO.input(assigned_bcm_number) == GPIO.HIGH: pass time.sleep(0.01) def quit(self): self.root.quit()
def start(): for i in range(int(100*44100/1024)): Sound.volume_set(100) data = np.fromstring(stream.read(CHUNK),dtype=np.int16) peak=np.average(np.abs(data))*2 bars="#"*int(50*peak/2**16) print("%04d %05d %s"%(i,peak,bars)) if len(bars)>15: pause()
def sound(q): """ sound takes a Queue and runs forever running commands. """ print "sound starting up" snd = Sound() while True: cmd = q.get() print "sound: {}".format(cmd) snd.handle_command(cmd) q.task_done()
def initGameObjects(self): self.prevGameState = self.gameState self.inp = Input() self.gameBoard = GameBoard(self) self.shipMan = ShipManager(self.screen, GameBoard.BOTTOM) self.hitMan = HitManager(self.screen) self.opponent = Opponent(self.screen, OpponentType.AI) self.helpergui = Helpergui(self) self.sound = Sound(self.screen)
def play(self, station_url): if Touchevent.event(): # brightness control Sound.play(CONFIG.CLICK_SOUND) Log(f"Playing {station_url}") if self.radio_process is not None: self.stop_play() self.radio_process = subprocess.Popen(["cvlc", station_url])
class Main: def __init__(self, host, port, media_path): self.media = Sound() self.loop = asyncio.get_event_loop() self.server = Server(host, port, self.background_tasks, self.shutdown_tasks) self.dir = media_path self.server.on_post('media', 'play', self.handle_play) self.server.on_post('media', 'stop', self.handle_stop) self.server.on_get('media', self.handle_get_media) async def handle_play(self, entity, item, action, data): print('handling play') filepath = self.get_path(item) print('file path: %s' % filepath) code = 200 if not exists(filepath): print('media not found: %s' % filepath) code = 404 else: print('playing %s' % item) if self.media.playing_file != filepath: await self.media.play(filepath) return (code, None) async def handle_stop(self, entity, item, action, data): filepath = self.get_path(item) code = 200 if not exists(filepath): print('media not found: %s' % filepath) code = 404 else: print('stopping %s' % item) await self.media.stop() return (code, None) async def handle_get_media(self, entity, attr, data): # tiny bug, file names get case lowered if attr == 'is_playing': is_playing, item = await self.media.is_playing() is_playing = str(is_playing).lower() return (200, '{"result": %s, "item": "%s"}' % (is_playing, item)) else: return (404, '{"result": "not found"}') def get_path(self, item): return abspath(join(self.dir, item)) async def background_tasks(self, app): asyncio.ensure_future(self.media.background_check()) async def shutdown_tasks(self, app): asyncio.ensure_future(self.media.on_shutdown()) def run(self): self.server.run()
def __init__(self): # 初始化 pygame pygame.init() # 初始化時間,遊戲幀數為每秒60幀 self.mainClock = pygame.time.Clock() self.mainClock.tick(60) self.tick = 0 # 初始化「繪圖」、「聲音」、「主角」 self.renderer = Renderer() self.character = Character() self.sound = Sound() self.bgm = Sound() '''遊戲參數初始化設定''' self.pause = False # 可控制遊戲暫停 self.quit = False # 可退出當前遊戲 self.pause_button = 0 # 遊戲暫停選單按鍵 self.game_over_button = 0 # 遊戲死亡選單按鍵 '''遊戲參數初始化設定結束''' '''遊戲精靈群組初始化''' self.allsprite = pygame.sprite.Group() # 精靈群組的總群組 self.bulletsprite = pygame.sprite.Group() # 子彈群組 self.bricksprite = pygame.sprite.Group() # 子彈邊界群組 self.bosssprite = pygame.sprite.Group() # 魔王群組 self.score_sprite = pygame.sprite.Group() self.shoes_sprite = pygame.sprite.Group() self.heart_sprite = pygame.sprite.Group() self.bonus_lst = [ self.score_sprite, self.shoes_sprite, self.heart_sprite ] # 突發class清單 self.direction = 0 self.num = 0 self.speed_adjust = 0 self.map_changex = 0 self.map_changey = 0 self.speed_up = False self.speed_up_time = 0 # 魔王加群組 self.boss = Boss() # boss = Boss(const.screen_width // 2 + self.map_changex, const.screen_height // 2 + self.map_changey) self.bosssprite.add(self.boss) '''遊戲精靈群組初始化結束''' self.volume_dct = { "v_0": pygame.image.load("images/volume/volume.png"), "v_1": pygame.image.load("images/volume/volume5.png"), "v_2": pygame.image.load("images/volume/volume4.png"), "v_3": pygame.image.load("images/volume/volume3.png"), "v_4": pygame.image.load("images/volume/volume2.png"), "v_5": pygame.image.load("images/volume/volume1.png"), "v_6": pygame.image.load("images/volume/volume0.png") } self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
def display(self, screen, topdata, currentScreenIndex): play = Sound() isPressed = (pygame.mouse.get_pressed() == (1,0,0)) top = pygame.image.load("img/top10.png") # if mosue is over back button if collides(self.back[RECT]): # display hover graphic self.back[IMG] = pygame.image.load("img/back_hover.png") if isPressed: # if mosue is pressed go back currentScreenIndex = 0 play.select() else: # else display regular back button self.back[IMG] = pygame.image.load("img/back.png") # Draw screen.blit(self.topbg[IMG], self.topbg[RECT]) screen.blit(self.back[IMG], self.back[RECT]) # Print out top 10 score for number,score in enumerate(topdata): number += 1 # display count from 1, not 0 line = 288 + (number-4)*30 # after line 4 increase line distance from top # write rank, points and date to screen rank = self.largefont.render(str(number) + '.', 1, (255,255,255)) points = self.largefont.render(score[1] + ' stig', 1, (255,255,255)) date = self.smallfont.render(score[0], 1, (255,255,255)) ''' TODO: Display name of player instead of date? ''' # display info for nr 1 if number == 1: screen.blit(points, (366, 130)) screen.blit(date, (366, 110)) # display info for nr 2 elif number == 2: screen.blit(points, (278, 148)) screen.blit(date, (278, 128)) # display info for nr 3 elif number == 3: screen.blit(points, (455, 160)) screen.blit(date, (455, 140)) # display info for nr 4-10 else: screen.blit(rank, (320, line)) screen.blit(points, (350, line)) screen.blit(date, (425, line+5)) # Send report to controller about current position return currentScreenIndex
def __init__(self): pg.init() self.settings = Settings() self.game_stats = GameStats(self.settings) self.screen = pg.display.set_mode(size=(self.settings.screen_width, self.settings.screen_height)) pg.display.set_caption("Alien Invasion") ship_image = pg.image.load('images/ship.bmp') self.ship_height = ship_image.get_rect().height self.hs = 0 self.sound = Sound(bg_music="sounds/crazy-space.wav") title = pg.image.load('images/title.bmp') # alein1 = pg.image.load('images/'alien00.bmp'') x = 200 y = 150 self.screen.blit(title, (x, y)) ali0 = pg.image.load('images/ali00.png') x = 500 y = 330 self.screen.blit(ali0, (x, y)) myfont = pg.font.SysFont("monospace", 25) label1 = myfont.render("=10 PTS", 1, (230, 230, 230)) self.screen.blit(label1, (560, 340)) ali1 = pg.image.load('images/ali10.png') x = 500 y = 380 self.screen.blit(ali1, (x, y)) myfont = pg.font.SysFont("monospace", 25) label1 = myfont.render("=20 PTS", 1, (230, 230, 230)) self.screen.blit(label1, (560, 390)) ali2 = pg.image.load('images/ali20.png') x = 500 y = 430 self.screen.blit(ali2, (x, y)) myfont = pg.font.SysFont("monospace", 25) label1 = myfont.render("=40 PTS", 1, (230, 230, 230)) self.screen.blit(label1, (560, 440)) ufo = pg.image.load('images/ufo00.png') x = 500 y = 480 self.screen.blit(ufo, (x, y)) myfont = pg.font.SysFont("monospace", 25) label1 = myfont.render("=???", 1, (230, 230, 230)) self.screen.blit(label1, (560, 490)) self.sound.play() self.sound.pause_bg() self.play_button = self.aliens = self.stats = self.sb = self.ship = None self.restart()
class Player(pygame.sprite.Sprite): def __init__(self): super(Player, self).__init__() self.surf = pygame.transform.rotate( pygame.image.load(consts.PLAYER_SHIP3), -90) self.rect = self.surf.get_rect() self.mask = pygame.mask.from_surface(self.surf) self.speed = 5 self.lives = 3 self.wait_bullet = False self.time_bullet = 0 self.waiting_time = 200 # miliseconds self.total_bullets = 5 self.bullets = [Bullet() for n in range(self.total_bullets)] self.sound = Sound() def update(self, pressed_keys): if pressed_keys[K_UP]: self.rect = self.rect.move(0, -self.speed) if pressed_keys[K_DOWN]: self.rect = self.rect.move(0, self.speed) if pressed_keys[K_LEFT]: self.rect = self.rect.move(-self.speed, 0) if pressed_keys[K_RIGHT]: self.rect = self.rect.move(self.speed, 0) if pressed_keys[K_SPACE]: if self.speed == 5: self.speed *= 2.5 else: self.speed = 5 if pressed_keys[K_LCTRL]: if not self.wait_bullet: if self.total_bullets > 0: self.sound.shoot() self.bullets[self.total_bullets - 1].enable_shooting() self.total_bullets -= 1 self.wait_bullet = True self.time_bullet = pygame.time.get_ticks() else: if pygame.time.get_ticks( ) - self.waiting_time >= self.time_bullet: self.wait_bullet = False # Keep player on the screen if self.rect.left < 0: self.rect.left = 0 if self.rect.right > consts.SCREEN_WIDTH: self.rect.right = consts.SCREEN_WIDTH if self.rect.top <= 0: self.rect.top = 0 if self.rect.bottom >= consts.SCREEN_HEIGHT: self.rect.bottom = consts.SCREEN_HEIGHT
def __init__(self, screen): ''' Initialize menu atttributes ''' self.game_active = False self.screen = screen self.num_buttons = 2 self.button_messages = ['Play', 'Quit'] self.buttons = [] self.music = Sound() self.music.loadMusic(load_sound("menu.wav")) self.prep_buttons(self.screen)
def alarm(self): """1) set the timer text to "Alarm" 2) start a tkinter timer for changing the background color of the Alarm text field (method alarm_blink()) 3) play a sound """ self.timer.set("Alarm") self.alarm_id = self.master.after( CONFIG.ALARM.DELAY, lambda: self.alarm_blink(CONFIG.ALARM.COUNT)) Sound.play(CONFIG.ALARM.SOUND, runs=3)
def three_samples(): '''Return a new sound with three samples.''' snd = Sound(samples=3) smp = snd.get_sample(0) smp.set_left(1010) smp.set_right(80) smp = snd.get_sample(1) smp.set_left(1500) smp.set_right(-4200) smp = snd.get_sample(2) smp.set_left(-65) smp.set_right(28132) return snd
def three_samples_rem_vocals(): '''Return a new sound to which vocal-removal has been applied.''' snd = Sound(samples=3) smp = snd.get_sample(0) smp.set_left(465) smp.set_right(465) smp = snd.get_sample(1) smp.set_left(2850) smp.set_right(2850) smp = snd.get_sample(2) smp.set_left(-14098) smp.set_right(-14098) return snd
def four_samples(): '''Return a new sound with four samples.''' snd = Sound(samples=4) smp = snd.get_sample(0) smp.set_left(1008) smp.set_right(80) smp = snd.get_sample(1) smp.set_left(1500) smp.set_right(-4200) smp = snd.get_sample(2) smp.set_left(64) smp.set_right(28132) smp = snd.get_sample(3) smp.set_left(148) smp.set_right(148) return snd
def four_samples_fade(): '''Return a new sound to which fade has been applied.''' snd = Sound(samples=4) smp = snd.get_sample(0) smp.set_left(0) smp.set_right(0) smp = snd.get_sample(1) smp.set_left(187) smp.set_right(-525) smp = snd.get_sample(2) smp.set_left(8) smp.set_right(3516) smp = snd.get_sample(3) smp.set_left(0) smp.set_right(0) return snd
def four_samples_fade_out(): '''Return a new sound to which fade-out has been applied.''' snd = Sound(samples=4) smp = snd.get_sample(0) smp.set_left(756) smp.set_right(60) smp = snd.get_sample(1) smp.set_left(750) smp.set_right(-2100) smp = snd.get_sample(2) smp.set_left(16) smp.set_right(7033) smp = snd.get_sample(3) smp.set_left(0) smp.set_right(0) return snd
def four_samples_fade_in(): '''Return a new sound to which a fade-in has been applied over the entire sound.''' snd = Sound(samples=4) smp = snd.get_sample(0) smp.set_left(0) smp.set_right(0) smp = snd.get_sample(1) smp.set_left(375) smp.set_right(-1050) smp = snd.get_sample(2) smp.set_left(32) smp.set_right(14066) smp = snd.get_sample(3) smp.set_left(111) smp.set_right(111) return snd
def display(self, screen, currentScreenIndex): play = Sound() # Check if left mouse button is pressed isPressed = (pygame.mouse.get_pressed() == (1,0,0)) # is mouse pointer over the play button if collides(self.play[RECT]): self.play[IMG] = pygame.image.load("img/play_hover.png") if isPressed: play.select() currentScreenIndex = PLAYSCREEN # is mouse pointer over the rules button elif collides(self.rules[RECT]): self.rules[IMG] = pygame.image.load("img/rules_hover.png") if isPressed: play.select() currentScreenIndex = RULESSCREEN # is mouse pointer over the top 10 button elif collides(self.top[RECT]): self.top[IMG] = pygame.image.load("img/top10_hover.png") if isPressed: play.select() currentScreenIndex = TOPSCREEN # is mouse pointer over the about button elif collides(self.about[RECT]): self.about[IMG] = pygame.image.load("img/about_hover.png") if isPressed: play.select() currentScreenIndex = ABOUTSCREEN # nothing of above, set all buttons to start position else: self.play[IMG] = pygame.image.load("img/play.png") self.rules[IMG] = pygame.image.load("img/rules.png") self.top[IMG] = pygame.image.load("img/top10.png") self.about[IMG] = pygame.image.load("img/about.png") # Draw all screen elements screen.blit(self.bg[IMG], self.bg[RECT]) screen.blit(self.logo[IMG], self.logo[RECT]) screen.blit(self.play[IMG], self.play[RECT]) screen.blit(self.rules[IMG], self.rules[RECT]) screen.blit(self.top[IMG], self.top[RECT]) screen.blit(self.about[IMG], self.about[RECT]) # Send report to controller about current position return currentScreenIndex
def __init__(self, imagePath, x, y, hp=100): self.image = pygame.image.load(imagePath) self.health = hp self.x = x self.y = y self.h = self.image.get_height() self.w = self.image.get_width() self.hitSound = Sound(SOUND_PATH_EXPLOSION, False) self.hitSound.set_volume(0.4)
def main(): cv.NamedWindow("original", cv.CV_WINDOW_AUTOSIZE) cam = cv2.VideoCapture(0) cam.set(cv.CV_CAP_PROP_FRAME_WIDTH, 10) cam.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 10) cam.set(cv.CV_CAP_PROP_FPS, 24) s = Sound() ret, frame = cam.read() while True: ret, frame = cam.read() r = recognition.Recognizer(frame) notes = r.get_notes() s.update(notes) if cv2.waitKey(1) == 27: # Escape code break cv2.destroyAllWindows()
def gimme_loop_handler(cls, addr, tags, data, source): # time in seconds; key between 0 (for C) and 11 (for B) pd_looper_id, required_tempo, required_key = data[0], data[1], data[2] # If the track hasn't been registered yet, we do that pd_looper_infos = cls.pd_loopers.setdefault(pd_looper_id, { 'current_loop_id': None, 'track_ids': [], 'tempo': None, }) current_loop_id = pd_looper_infos['current_loop_id'] # Picking the new loop in the pool with cls.pool_lock: # prefilter available loops (those whose track haven't been picked already) available_loops = cls.pool.values() forbidden_tracks = cls.forbidden_tracks(pd_looper_id) available_loops = filter(lambda l: l['track_id'] not in forbidden_tracks, available_loops) # Select the most suitable next loop according to the current loop. if current_loop_id is not None: def sort_key(l): timbre_dist = loop_distance(cls.old_loops[current_loop_id], l) tempo_dist = abs(1 - l['tempo'] / float(required_tempo)) * 40 return timbre_dist + tempo_dist loop_infos = sorted(available_loops, key=lambda l: sort_key)[0] else: loop_infos = available_loops[0] # Remove the loop from the pool, reserving the loop's track for this looper cls.pool.pop(loop_infos['loop_id']) pd_looper_infos['track_ids'].append(loop_infos['track_id']) pd_looper_infos['current_loop_id'] = loop_infos['loop_id'] # Adding the picked looped to `old_loops`, so that we remember it # but it cannot be used again. with cls.old_loops_lock: cls.old_loops[loop_infos['loop_id']] = loop_infos if current_loop_id is not None: cls.old_loops.pop(current_loop_id) # Preparing the loop logger.info('sending new loop %s to looper %s, left : %s' % (loop_infos['path'], pd_looper_id, len(cls.pool))) loop = Sound.from_file(loop_infos['path']) required_length = loop.length * float(required_tempo) / loop_infos['tempo'] beat_length = 60.0 / required_tempo required_length = round(required_length / beat_length) * beat_length loop = loop.time_stretch(required_length).fade(in_dur=0.002, out_dur=0.002) loop.to_file(loop_infos['path']) # Sending loop, and fill-up the pool if necessary. send_msg('/new_loop', pd_looper_id, loop_infos['path'], int(round(loop.length * 1000)), loop_infos['loop_id']) if len(LoopScraper.pool) < LoopScraper.pool_min_size: LoopScraper.wake_up_scrapers()
def process(self): self.predictions = np.zeros(self.freqsISO.size) for i, freq in enumerate(self.freqsISO): s = Sound.tone([freq], dur = self.duration, fs = self.fs) s.applyRamp(0.1) s.useDBSPL() s.normalise(self.thresholdsISO[i], 'RMS') self.predictions[i] = self.thresholdsISO[i] self.predictions[i] += self.iterator.process(s.data, self.threshold, self.tol, self.nIters)
def display(self, screen, currentScreenIndex): play = Sound() # Check if left mouse button is pressed isPressed = (pygame.mouse.get_pressed() == (1,0,0)) # is mouse pointer over the play button if collides(self.back[RECT]): self.back[IMG] = pygame.image.load("img/back_hover.png") if isPressed: currentScreenIndex = STARTSCREEN play.select() # nothing of above, set all buttons to start position else: self.back[IMG] = pygame.image.load("img/back.png") # Draw all screen elements screen.blit(self.bg[IMG], self.bg[RECT]) screen.blit(self.back[IMG], self.back[RECT]) # Send report to controller about current position return currentScreenIndex
def generatePureTones(): samplingFreqs = [32000, 44100, 48000] freqs = [50, 1000, 3000] levels = [40] durations = [1.0] for fs in samplingFreqs: for freq in freqs: for dur in durations: x = Sound.tone(freq, dur = dur, fs = fs) x.ref = 2e-5 for level in levels: x.normalise(level, "RMS") x.writeToAudioFile('./pureTone_' + str(freq) + 'Hz_' + str(level) +\ 'dBSPL_' + str(fs) + 'Hz.wav', 'float32')
def scrape(self): id_counter = 0 track_id, filename, sound_length = get_sound() # Check if the sound is long enough, and if yes we extract some loops from it. # TODO: make this less restrictive to waste a bit less if sound_length > 2 * self.sample_length: offset = 0 upper_limit = sound_length - 2 * self.sample_length while (offset + 2 * self.sample_length < upper_limit): # Calculate a random offset where the loop will start offset = random.randint(offset, int(min(offset + sound_length * 0.2, upper_limit))) # Extracting a loop and saving it to 'loop<n>.wav' sample = Sound.from_file(filename, start=offset, end=offset+self.sample_length) loops = sample.extract_loops() for loop in loops: if id_counter > 10: offset = upper_limit break id_counter += 1 loop_id = '%s_%s' % (track_id, id_counter) loop_path = self._get_free_path() logger.info('loop extracted to %s' % loop_path) loop.to_file(loop_path) #key, key_confidence, length = loop.echonest.key, loop.echonest.key_confidence, loop.length with self.pool_lock: self.pool[loop_id] = dict(loop.loop_infos, **{ 'path': loop_path, 'length': loop.length, 'loop_id': loop_id, 'track_id': track_id, 'timbre_start': loop.loop_infos['timbre_start'], 'timbre_end': loop.loop_infos['timbre_end'] #'key': (key, key_confidence) }) # Increment values for next loop offset += self.sample_length # Delete the sounds to save memory # We also have to collect manually because of a "bug" in pandas: # https://github.com/pydata/pandas/issues/2659 if 'loop' in locals(): del loop del sample gc.collect()
def __init__(self, window_width, window_height): self.frame_update = 0 self.second_count_update = time.time() self.frame_draw = 0 self.second_count_draw = time.time() #Screen settings self.screen = pygame.display.set_mode((window_width, window_height), FLAGS, DEPTH) pygame.display.set_caption("BREAKOUT ULTIMATE") #Background self.background = pygame.Surface((pygame.display.Info().current_w, pygame.display.Info().current_h)) self.background.convert() self.background.fill(pygame.Color("#000000")) #Font pygame.font.init() font_size = 16 self.fontObj = pygame.font.SysFont("courier", font_size) #Entities list (player, balls, blocks) self.entities = pygame.sprite.Group() self.items = pygame.sprite.Group() self.blocks = pygame.sprite.Group() self.player = Player() self.ball = Ball() self.entities.add(self.player) self.entities.add(self.ball) self.sound_factory = Sound() self.menu_obj = Menu() #Calculating the space between each block horizontal_spacing = 50 * (pygame.display.Info().current_w * 1.0 / 800) vertical_spacing = 40 * (pygame.display.Info().current_h * 1.0 / 640) for column in range (0, 14): for row in range (0, 5): new_block = Block(column * horizontal_spacing + (60 * (pygame.display.Info().current_w * 1.0 / 800)), row * vertical_spacing + 50, pygame.display.Info().current_w, pygame.display.Info().current_h) self.entities.add(new_block) self.blocks.add(new_block) #Game states self.game_over = False self.menu = True self.pause = True
def process(self): self.predictions = np.zeros(self.freqs.size) self.converged = np.zeros(self.freqs.size, dtype = bool) for i, freq in enumerate(self.freqs): print 'Freq: %0.2f, initial guess: %0.2f' % (freq, self.sPLs[i]) s = Sound.tone([freq], dur = self.duration, fs = self.fs) s.applyRamp(0.1) s.useDBSPL() s.normalise(self.sPLs[i], 'RMS') self.predictions[i] = self.sPLs[i] self.predictions[i] += self.iterator.process(s.data, self.targetLoudnessLevel, self.tol, self.nIters, self.alpha) self.converged[i] = self.iterator.converged
def scrape(self): track_id, pad_path, pad_length = get_sound() new_pad_path = self._get_free_path() pad_id = '%s' % (track_id) sound = Sound.from_file(pad_path, end=min(30, pad_length)) sound = sound.remove_beats() sound.to_file(new_pad_path) logger.info('pad extracted to %s' % new_pad_path) '''pad.to_file(pad_path) # Delete the sound to save memory # We also have to collect manually because of a "bug" in pandas: # https://github.com/pydata/pandas/issues/2659 del pad gc.collect()''' with self.pool_lock: self.pool[pad_id] = { 'path': new_pad_path, 'pad_id': pad_id }
def __init__(self, dimension, grid, food_score, bonus_score, snake_color, flag = 0): print ("Initializing Engine!") pygame.init() self.player = Player() self.player["color"] = snake_color self.connect(self.player, "dead", self, "player_died") self.fps = 0 self.map = Map(dimension, grid, self.player["color"], food_score, bonus_score, flag) ### Connect the map for receiving events from the Engine ### self.connect(self, "advance", self.map, "advance") self.connect(self, "direction_changed", self.map, "direction_changed") ### Engine receives events from the map ### self.connect(self.map, "food_eaten", self, "food_eaten") self.connect(self.map, "obstacle_hit", self, "obstacle_hit") ### Create Sound Class and connect the map with it ### self.sound = Sound() self.connect(self.map, "food_eaten", self.sound, "play_food_eaten_sound") self.connect(self.map, "obstacle_hit", self.sound, "play_obstacle_hit_sound") self.connect(self.map, "bonus_won", self.sound, "play_bonus_won_sound") self.connect(self.map, "bait_eaten", self.sound, "play_bait_eaten_sound") ### Connects the map with the player ### self.connect(self.map, "food_eaten", self.player, "food_eaten") self.connect(self.map, "bait_eaten", self.player, "bait_eaten") self.connect(self.map, "obstacle_hit", self.player, "obstacle_hit") self.connect(self.map, "bonus_won", self.player, "bonus_won") ### Connect the player with the view ### self.connect(self.player, "dead", self.map.view, "player_dead") self.start_new_game() self.clock = pygame.time.Clock() self.key_locked = False ### Used for locking key for the next move to happen ### self.key_pending = [] ### Used for keeping pressed keys ### self.update_caption()
def __init__(self): os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.mixer.pre_init(44100,-16, 2, 4096) pygame.init() if FULL_SCREEN == True: if os.name == "nt": self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN|HWSURFACE|DOUBLEBUF, COLOR_DEPTH) else: self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, COLOR_DEPTH) else: self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, COLOR_DEPTH) pygame.display.set_caption(GAME_NAME) self.clock = pygame.time.Clock() self.timer = time.time()-5 self.game_started = False self.menu = Menu(self) self.sound = Sound() self.sprites = pygame.sprite.OrderedUpdates() self.font = pygame.font.Font(os.path.join('data', 'misc', 'COOPBL.TTF'), 28) self.initialize_game() self.left_flip_count = 0 self.right_flip_count = 0
def open(self,filename): f = open(filename,"rw") reader = csv.reader(f,delimiter=",") self._data = {} for row in reader: if self._header == None: self._header = row continue urow = [] for cell in row: urow.append(unicode(cell,"utf-8")) s = Sound() s.phonetic = urow[0] s.ipa = urow[1] s.filter = urow[2] s.threshold = float(urow[3]) s.remarks = urow[4] self._data[s.phonetic] = s return self._data
class Game(object): modes = ['Waiting', 'In Play'] def __init__(self, fps=60, fullscreen=False): """ (int, int, int, bool) -> Game Instantiate Game object with expected properties of a tower defense game. """ pygame.init() # Parameter-based properties self.fps = fps self.fullscreen = fullscreen # Determine width and height self.screenW = pygame.display.list_modes()[0][0] self.screenH = pygame.display.list_modes()[0][1] if not self.fullscreen: self.screenW = floor(0.8 * self.screenW) self.screenH = floor(0.8 * self.screenH) # Display and framerate properties self.caption = GAME_NAME + ' - Left Mouse Button to select/place turret, drag by moving the mouse' self.displaySurf = None if self.fullscreen: self.flags = FULLSCREEN | DOUBLEBUF | HWACCEL else: self.flags = DOUBLEBUF | HWACCEL self.fpsClock = pygame.time.Clock() self.initializeDisplay() # Define and reset gameplay properties and objects self.money, self.wave, self.turrets, self.enemies, self.intersections, \ self.measuredFPS, self.tower, self.mode = [None] * 8 self.reset() # HUD object hudSize = 300 hudRect = pygame.Rect(self.screenW - hudSize, 0, hudSize, self.screenH) hudColour = GREY self.hud = HUD(hudRect, hudColour, Turret(), FourShotTurret(), GlueTurret(), FireTurret(), LongRange(), EightShotTurret()) # Collision-related properties self.pathRects = [] # Level appearance and elements self.intersectionSurface = pygame.Surface(self.displaySurf.get_size(), SRCALPHA | RLEACCEL, 32).convert_alpha() self.pathColour = ORANGE self.grassColour = LGREEN self.pathWidth = 50 # Mouse and events self.mouseX, self.mouseY = 0, 0 self.clicking = False self.dragging = False self.events = [] # Health increment self.healthIncrement = 1 # Menu object self.menu = Menu() # Background self.background = pygame.image.load(getDataFilepath(IMG_PATH_GRASS)).convert() self.pathImage = pygame.image.load(getDataFilepath(IMG_PATH_DIRT)).convert() # Sounds self.backgroundMusic = Sound(getDataFilepath('retro.wav'), True) self.hitSound = Sound(SOUND_PATH_SHOT, False) self.inPlay = True def reset(self, money=200, wave=1): """ ([int], [int]) -> None Reset money, wave number, and other similar game world properties. """ self.money = money self.wave = wave self.turrets = [] self.intersections = [] self.enemies = [] self.tower = Tower(IMG_PATH_TOWER, self.screenW / 2, self.screenH / 2) self.mode = self.modes[0] def incrementEnemyHealth(self, increment): for enemy in self.enemies: enemy.health *= increment def generateEnemies(self, x=1, separation=70): """ ([int], [int]) -> None Generate "x" number of enemies with the given separation for the tower defense game. """ # Return immediately if there are no intersections loaded. if not self.intersections: print('WARNING: Enemies not loaded! Intersections must be loaded first.') return # Clear the list of enemies to start with. self.enemies = [] # Gather information and create temporary variables. firstTurnX = self.intersections[0][0] firstTurnY = self.intersections[0][1] secondTurnX = self.intersections[1][0] secondTurnY = self.intersections[1][1] gap = x * separation xlist = [] ylist = [] direction = NODIR # Determine the starting direction and co-ordinate lists for the enemies. if firstTurnX == secondTurnX and firstTurnY > secondTurnY: xlist = [firstTurnX] ylist = xrange(firstTurnY, firstTurnY + gap, separation) direction = UP elif firstTurnX == secondTurnX: xlist = [firstTurnX] ylist = xrange(firstTurnY - gap, firstTurnY, separation) direction = DOWN elif firstTurnY == secondTurnY and firstTurnX > secondTurnX: xlist = xrange(firstTurnX, firstTurnX + gap, separation) ylist = [firstTurnY] direction = LEFT elif firstTurnY == secondTurnY: xlist = xrange(firstTurnX - gap, firstTurnX, separation) ylist = [firstTurnY] direction = RIGHT # Create enemies with the information determined above. w = Enemy(IMG_PATH_ENEMY1, 0, 0).w h = Enemy(IMG_PATH_ENEMY1, 0, 0).h assigned = False for x in xlist: for y in ylist: enemyType = random.randint(1, 5) if enemyType == 2 and not assigned: self.enemies.append(Enemy(IMG_PATH_ENEMY2, x - w // 2, y - h // 2, direction, 3, 200)) assigned = True elif enemyType == 3 and not assigned and self.wave >= 2: self.enemies.append(Enemy(IMG_PATH_ENEMY3, x - w // 2, y - h // 2, direction, 2, 300)) assigned = True elif enemyType == 4 and not assigned and self.wave >= 2: self.enemies.append(Plane(IMG_PATH_ENEMY4, x - w // 2, y - h // 2, direction, 6, 100)) assigned = True elif enemyType == 5 and not assigned and self.wave >= 10: self.enemies.append(HugeTank(IMG_PATH_ENEMY5, x - w // 2, y - h // 2, direction, 2, 500)) assigned = True else: self.enemies.append(Enemy(IMG_PATH_ENEMY1, x - w // 2, y - h // 2, direction, health=100)) assigned = True self.enemies[-1].setNextIntersection(self.intersections[0]) self.enemies[-1].initialDistanceFromWorld = distance((self.enemies[-1].x, self.enemies[-1].y), (firstTurnX, firstTurnY)) assigned = False if self.wave % 5 == 0: self.healthIncrement += 1 self.incrementEnemyHealth(self.healthIncrement) # Sort the list of enemies in terms of ascending distance away from the initial intersection. self.enemies.sort(key=lambda x: x.initialDistanceFromWorld) def makeStrSubstitutions(self, string): """ (str) -> str Return the input string but with human-readable keywords exchanged for co-ordinates and directions. """ substitutions = {'RIGHT': RIGHT, 'LEFT': LEFT, 'UP': UP, 'DOWN': DOWN, 'WIDTH': self.hud.left, 'HEIGHT': self.screenH} result = string[:] for word in string.split(): if word in substitutions: result = result.replace(word, str(substitutions[word])) return result def stretchIntersections(self): """ (None) -> None Stretch or compress intersection co-ordinates as necessary to fit them to screen. """ # Return immediately if there are no intersections if not self.intersections: return # Gather info about the needed scaling for horizontal and vertical co-ordinates of each intersection temp = self.intersections[:] temp.sort(key=lambda x: x[0]) horizontalStretch = (self.screenW - self.hud.width) / float(temp[-1][0] + self.pathWidth // 2) temp = self.intersections[:] temp.sort(key=lambda x: x[1]) verticalStretch = self.screenH / float(temp[-1][1] + self.pathWidth) # Make it happen and leave the intersection direction intact for i in xrange(len(self.intersections)): self.intersections[i] = ceil(self.intersections[i][0] * horizontalStretch), \ ceil(self.intersections[i][1] * verticalStretch), self.intersections[i][2] self.tower.x *= horizontalStretch self.tower.y *= verticalStretch def loadIntersections(self, filename): """ (None) -> tuple Load the saved intersections from file based on the current wave. Return the loaded intersection 3-tuples. """ self.intersections = [] data = open(getDataFilepath(filename), 'r') for line in data: intersection = self.makeStrSubstitutions(line).split() intersection = int(intersection[0]), int(intersection[1]), int(intersection[2]) self.intersections.append(intersection) self.stretchIntersections() return self.intersections def loadTowerLoc(self, filename): """ (None) -> None Load the co-ordinates of the tower to defend. """ data = open(getDataFilepath(filename), 'r').read().split() x = int(self.makeStrSubstitutions(data[-3])) y = int(self.makeStrSubstitutions(data[-2])) self.tower.x, self.tower.y = x - self.tower.w // 2, y - self.tower.h // 2 newRect = self.tower.getRect().clamp(pygame.Rect(0, 0, self.screenW - self.hud.width, self.screenH)) self.tower.x = newRect.x self.tower.y = newRect.y def incrementWave(self): """ (None) -> None Set up the level for the next wave. """ self.wave += 1 self.generateEnemies(4 * self.wave) for turret in self.turrets: turret.bullets = [] turret.angle = 0 def drawText(self, text, x=0, y=0): """ (str, [int], [int]) -> None Draw the given string such that the text matches up with the given top-left co-ordinates. Acts as a wrapper for the HUD drawText(). """ self.hud.drawText(self.displaySurf, text=text, left=x, top=y) def handleAI(self): """ (None) -> None Force the enemies to turn at each intersection. """ if not self.enemies or not self.intersections: return for enemy in self.enemies: nextTurn = enemy.getNextIntersection() if not enemy.getReducedRect().collidepoint(nextTurn[0:2]): continue if nextTurn[-1] == LEFT: enemy.startMovingLeft() elif nextTurn[-1] == RIGHT: enemy.startMovingRight() elif nextTurn[-1] == UP: enemy.startMovingUp() elif nextTurn[-1] == DOWN: enemy.startMovingDown() else: enemy.stop() intersectionIndex = self.intersections.index(nextTurn) if intersectionIndex + 1 < len(self.intersections): enemy.setNextIntersection(self.intersections[intersectionIndex + 1]) def drawIntersections(self, surface): """ (Surface) -> None Draw a sequence of paths joining all of the intersections onto the given surface. Update the list of path Rect objects for collision detection. """ if not self.intersections: return points, intersectionRects, joinRects, result = [], [], [], [] half = floor(self.pathWidth / 2.0) for intersection in self.intersections: points.append((intersection[0], intersection[1])) for point in points: intersectionRects.append(pygame.Rect(point[0] - half, point[1] - half, 2 * half, 2 * half)) for i in xrange(len(points) - 1): result.append(intersectionRects[i].union(intersectionRects[i + 1])) surface.blit(self.pathImage, (result[-1].x, result[-1].y), result[-1]) self.pathRects = result def onPath(self, other): """ (int, int) -> bool Return True if the x and y co-ordinates represent a spot on the paths, False otherwise. """ result = False if not self.pathRects: return result for rect in self.pathRects: if (isinstance(other, tuple) and rect.collidepoint(other)) or rect.colliderect(other): result = True return result def onGrass(self, other): """ (int, int) -> bool Return True if the x and y co-ordinates represent a spot on the grass, False otherwise. """ return not self.onPath(other) def hoveringSidebar(self): """ (None) -> bool Return True if the mouse is hovering over the HUD sidebar, False otherwise. """ return self.mouseX >= self.hud.left def initializeDisplay(self): """ (None) -> Surface Initialize the display Surface and update the caption and display settings. Only call once in __init__. """ self.displaySurf = pygame.display.set_mode((self.screenW, self.screenH), self.flags) pygame.display.set_caption(self.caption) return self.displaySurf def redrawAndProceedTick(self): """ (None) -> None Redraw the screen, and delay to enforce the FPS. Call on every update. """ pygame.display.flip() self.fpsClock.tick_busy_loop(self.fps) self.measuredFPS = self.fpsClock.get_fps() def terminate(self): """ (None) -> None Set the game to exit as soon as possible. """ print('Game closing...') self.inPlay = False def handleQuitEvents(self, events): """ (list-of-Events) -> None Exit the game if Escape is pressed or if the close button is used. """ for event in events: if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): self.terminate() def updateState(self): """ (None) -> None Update the state of the game based on the user selection on the sidebar. """ if self.hud.shouldPause(): self.backgroundMusic.pause() if self.menu.drawPauseMenu(self.displaySurf): self.__init__(self.fps, self.fullscreen) self.execute() self.menu.drawPauseMenu(self.displaySurf) self.backgroundMusic.play(-1) if self.hud.shouldStart(): self.mode = self.modes[1] self.canRun() def updateEnemies(self): """ (None) -> None Update and draw all enemies and the central tower. """ levelComplete = True for enemy in self.enemies: if self.mode == self.modes[0]: enemy.pause() elif self.mode == self.modes[1]: enemy.unpause() if enemy.alive(): levelComplete = False enemy.update() self.tower.update(self.displaySurf, enemy) enemy.draw(self.displaySurf, enemy.x, enemy.y) if levelComplete and self.mode == self.modes[1]: self.mode = self.modes[0] self.incrementWave() def enemyIndex(self, enemy): try: return self.enemies.index(enemy) except IndexError: print('WARNING: Tried to access nonexistent enemy.') return 0 @staticmethod def inRange(enemy, turret): """ (Enemy, Turret) -> None Return True if the enemy is in range of the given turret, False otherwise. """ return distance(enemy.getRect().center, turret.getRect().center) < turret.range and enemy.active def setTarget(self, enemy, turret): """ (Enemy, Turret) -> None Lock onto a new enemy with the given turret. """ if not isinstance(turret, FourShotTurret) and turret.canShoot: turret.angle = getAngle(deltaX(enemy.x, turret.x), deltaY(enemy.y, turret.y)) turret.lockOn = True def provideReward(self, turret): """ (None, Turret) -> None Provide the player with a reward for each kill. """ self.money += turret.reward def updateTurrets(self): """ (None) -> None Update and draw all turrets and bullets. """ for turret in self.turrets: # Check if the turret is highlighted turret.highlighted = False if turret.getRect().collidepoint(self.mouseX, self.mouseY): turret.highlighted = True # Check for lock-on with enemies foundTarget = False for enemy in self.enemies: if self.inRange(enemy, turret): self.setTarget(enemy, turret) foundTarget = True break if not foundTarget: turret.lockOn = False turret.bullets = [] # Update and draw the turret turret.update(self.displaySurf) # Check for bullet collision with enemies for bullet in turret.bullets: for enemy in self.enemies: bulletEnemyCollision = bullet.getRect().colliderect(enemy.getRect()) if bulletEnemyCollision and not isinstance(turret, FourShotTurret): self.hitSound.play() bullet.dispose() turret.test = True if not isinstance(turret, GlueTurret) or \ (isinstance(enemy, Plane) and not isinstance(turret, FireTurret)): enemy.health -= bullet.damagePotential else: enemy.topSpeed *= bullet.slowFactor enemy.dispose() if enemy.health <= 0: self.provideReward(turret) elif bulletEnemyCollision: self.hitSound.play() enemy.health -= bullet.damagePotential enemy.dispose() bullet.dispose() if enemy.health <= 0: self.provideReward(turret) def updateHud(self): """ (None) -> None Update and draw the HUD sidebar. """ self.hud.update(self.tower.health, self.money, self.wave) self.hud.draw(self.displaySurf) def updateInputs(self): """ (None) -> None Get keyboard and mouse status and check for quit events. """ self.mouseX, self.mouseY = pygame.mouse.get_pos() self.clicking = pygame.mouse.get_pressed()[0] self.events = pygame.event.get() self.handleQuitEvents(self.events) def addTurret(self, index): """ (int) -> None Add a turret with the given index to the list of turrets. """ newTurret = copy.copy(self.hud.turrets[index]) newTurret.x = DEFAULT_VALUE newTurret.y = DEFAULT_VALUE self.turrets.append(newTurret) def handleDragging(self): """ (None) -> None Facilitate dragging of turrets from the HUD sidebar to the game field. """ overlapping = False index = self.hud.highlighted() clicked = False rects = [turret.getRect() for turret in self.turrets[0:-1]] if len(self.turrets) > 1: for rect in rects: if self.turrets[-1].getRect().colliderect(rect): overlapping = True for event in self.events: if event.type == MOUSEBUTTONDOWN: clicked = True if self.dragging and clicked and self.onGrass(self.turrets[-1].getRect()) and not overlapping: self.dragging = False self.turrets[-1].canShoot = True self.money -= self.turrets[-1].price if index >= 0 and clicked and not self.dragging and self.money >= self.hud.turrets[index].price: self.dragging = True self.addTurret(index) if self.dragging and not clicked: self.turrets[-1].x = self.mouseX - self.turrets[-1].width // 2 self.turrets[-1].y = self.mouseY - self.turrets[-1].height // 2 self.turrets[-1].canShoot = False def update(self): """ (None) -> None Update the entire game state and draws all objects on the screen. """ self.displaySurf.blit(self.background, ORIGIN) self.updateInputs() self.handleAI() self.updateEnemies() self.updateTurrets() self.updateHud() self.handleDragging() self.redrawAndProceedTick() self.updateState() def execute(self): """ (None) -> None Execute the Tower Defense game. """ # Play background music and enter the title screen self.backgroundMusic.play(-1) self.menu.drawTitleMenu(self.displaySurf) filename = self.menu.drawSelectLevelScreen(self.displaySurf) # Load the first level properties self.loadTowerLoc(filename) self.loadIntersections(filename) self.generateEnemies(5) # Blit the tower and paths onto the background Surface self.drawIntersections(self.intersectionSurface) self.background.blit(self.intersectionSurface, ORIGIN) self.tower.draw(self.background) # Play! while self.inPlay: self.update() self.menu.drawLosePanel (self.displaySurf) self.menu.drawCredits(self.displaySurf) pygame.quit() def getRect(self): """ (None) -> Rect Return a pygame Rect object defining the display surface boundaries. """ return self.displaySurf.get_rect() def canRun (self): if self.tower.health <= 0: self.terminate ()
def __init__(self, frequency, name="none", velocity=64, attack=0, decay=0, sustain=127, release=0): Sound.__init__(self, frequency, velocity, attack, decay, sustain, release) self.name = name
class Engine(EventObject): def __init__(self, dimension, grid, food_score, bonus_score, snake_color, flag = 0): print ("Initializing Engine!") pygame.init() self.player = Player() self.player["color"] = snake_color self.connect(self.player, "dead", self, "player_died") self.fps = 0 self.map = Map(dimension, grid, self.player["color"], food_score, bonus_score, flag) ### Connect the map for receiving events from the Engine ### self.connect(self, "advance", self.map, "advance") self.connect(self, "direction_changed", self.map, "direction_changed") ### Engine receives events from the map ### self.connect(self.map, "food_eaten", self, "food_eaten") self.connect(self.map, "obstacle_hit", self, "obstacle_hit") ### Create Sound Class and connect the map with it ### self.sound = Sound() self.connect(self.map, "food_eaten", self.sound, "play_food_eaten_sound") self.connect(self.map, "obstacle_hit", self.sound, "play_obstacle_hit_sound") self.connect(self.map, "bonus_won", self.sound, "play_bonus_won_sound") self.connect(self.map, "bait_eaten", self.sound, "play_bait_eaten_sound") ### Connects the map with the player ### self.connect(self.map, "food_eaten", self.player, "food_eaten") self.connect(self.map, "bait_eaten", self.player, "bait_eaten") self.connect(self.map, "obstacle_hit", self.player, "obstacle_hit") self.connect(self.map, "bonus_won", self.player, "bonus_won") ### Connect the player with the view ### self.connect(self.player, "dead", self.map.view, "player_dead") self.start_new_game() self.clock = pygame.time.Clock() self.key_locked = False ### Used for locking key for the next move to happen ### self.key_pending = [] ### Used for keeping pressed keys ### self.update_caption() def update_caption(self, string = ""): """ Used only for updating the window caption. """ if string == "dead": pygame.display.set_caption("You are dead! score: %i, fps: %.2f"\ % (self.player["score"], self.fps)) elif string == "paused": pygame.display.set_caption("### Paused ### fps: %.2f" % self.fps) else: pygame.display.set_caption("nf: %i, no: %i, fs: %i, bs: %i, sp: %.2f, score: %i, fps: %.2f"\ % (self.map.board.num_food, self.map.number_obstacle_created,self.map.food_score, self.map.bonus_score, self.player["speed"], self.player["score"], self.fps)) def start_new_game(self): """ Starts a new game. """ self.advance = True self.player["live"] = True self.player["speed"] = 0.1 self.player["score"] = 0 self.map.reload() self.sound.play_music() def _exec_(self): """ Game event main loop. """ ticks_last_frame_speed = pygame.time.get_ticks() ticks_last_frame_fps = pygame.time.get_ticks() frames = 0 while True: frames += 1.0 self.handle_pending_keys() for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: exit(0) if self.player["live"] == 1: ### Keys for when player is alive ### if event.key == pygame.K_SPACE: if self.advance == True: self.advance = False ### Set advance false for stopping the map ### self.key_locked = True ### Lock key for not getting moves while paused ### self.sound.pause_music() else: self.advance = True ### Set advance true so the map can continue ### self.key_pending = [] ### Clean the pending keys so the snake won't move after continuing the game ### self.key_locked = False ### Set locked keys for getting new keys ### self.sound.play_music() elif not self.key_locked and self.advance: key = event.key self.handle_key(key) else: self.key_pending.append(event.key) else: ### Keys for player dead screen ### if event.key == pygame.K_y: self.start_new_game() elif event.key == pygame.K_n: exit(0) t = pygame.time.get_ticks() delta_time = (t - ticks_last_frame_speed) / 1000.0 if self.advance and delta_time >= self.player["speed"]: self.key_locked = False ### Unlock the key for new directions. ### self.emit("advance") ticks_last_frame_speed = t t = pygame.time.get_ticks() delta_time = (t - ticks_last_frame_fps) / 1000.0 if (delta_time >= 1.0): self.fps = frames frames = 0 ticks_last_frame_fps = t if self.advance == True: self.update_caption() elif self.player["live"] == 1: self.update_caption("paused") else: self.update_caption("dead") self.clock.tick(60) def handle_pending_keys(self): """ This method takes care of pending keys. Does nothing while key is locked. """ for key in self.key_pending: if self.key_locked: return self.key_pending.remove(key) self.handle_key(key) def player_died(self): """ This method is called when the player live is set to 0. """ self.update_caption("dead") self.advance = False def handle_key(self, key): """ Send to the map the new direction. And locks the key. """ if key == pygame.K_UP or key == pygame.K_w: self.emit("direction_changed", [Directions.UP]) self.key_locked = True elif key == pygame.K_DOWN or key == pygame.K_s: self.emit("direction_changed", [Directions.DOWN]) self.key_locked = True elif key == pygame.K_RIGHT or key == pygame.K_d: self.emit("direction_changed", [Directions.RIGHT]) self.key_locked = True elif key == pygame.K_LEFT or key == pygame.K_a: self.emit("direction_changed", [Directions.LEFT]) self.key_locked = True
def __init__(self, fps=60, fullscreen=False): """ (int, int, int, bool) -> Game Instantiate Game object with expected properties of a tower defense game. """ pygame.init() # Parameter-based properties self.fps = fps self.fullscreen = fullscreen # Determine width and height self.screenW = pygame.display.list_modes()[0][0] self.screenH = pygame.display.list_modes()[0][1] if not self.fullscreen: self.screenW = floor(0.8 * self.screenW) self.screenH = floor(0.8 * self.screenH) # Display and framerate properties self.caption = GAME_NAME + ' - Left Mouse Button to select/place turret, drag by moving the mouse' self.displaySurf = None if self.fullscreen: self.flags = FULLSCREEN | DOUBLEBUF | HWACCEL else: self.flags = DOUBLEBUF | HWACCEL self.fpsClock = pygame.time.Clock() self.initializeDisplay() # Define and reset gameplay properties and objects self.money, self.wave, self.turrets, self.enemies, self.intersections, \ self.measuredFPS, self.tower, self.mode = [None] * 8 self.reset() # HUD object hudSize = 300 hudRect = pygame.Rect(self.screenW - hudSize, 0, hudSize, self.screenH) hudColour = GREY self.hud = HUD(hudRect, hudColour, Turret(), FourShotTurret(), GlueTurret(), FireTurret(), LongRange(), EightShotTurret()) # Collision-related properties self.pathRects = [] # Level appearance and elements self.intersectionSurface = pygame.Surface(self.displaySurf.get_size(), SRCALPHA | RLEACCEL, 32).convert_alpha() self.pathColour = ORANGE self.grassColour = LGREEN self.pathWidth = 50 # Mouse and events self.mouseX, self.mouseY = 0, 0 self.clicking = False self.dragging = False self.events = [] # Health increment self.healthIncrement = 1 # Menu object self.menu = Menu() # Background self.background = pygame.image.load(getDataFilepath(IMG_PATH_GRASS)).convert() self.pathImage = pygame.image.load(getDataFilepath(IMG_PATH_DIRT)).convert() # Sounds self.backgroundMusic = Sound(getDataFilepath('retro.wav'), True) self.hitSound = Sound(SOUND_PATH_SHOT, False) self.inPlay = True
class Menu(): def __init__(self): self.const = util.Constant() self.player = VLC() self.lib = Library() self.user = User() self.sound = Sound() def start(self): while True: with color("blue"): print "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" print """ __ __ __ """ print """ / //_/___ _____ _________ _____ / /_____ """ print """ / ,< / __ `/ __ \/ ___/ __ `/ __ \/ //_/ _ \\""" print """ / /| / /_/ / / / / / / /_/ / /_/ / ,< / __/""" print """ /_/ |_\__,_/_/ /_/_/ \__,_/\____/_/|_|\___/ """ print """ """ print with color('yellow'): print "输入首字母搜索 (B)浏览歌曲 (V)原唱/伴唱 (N)下一首 (P)暂停/继续" print "\n\n\n\n" cmd = readline("Kanraoke > ") cmd = cmd.strip() if cmd: if cmd == "quit" or cmd == "q": break else: self._process_cmd(cmd) # def alert(self, msg): # if platform.system() == 'Darwin': # os.system('/usr/bin/osascript -e \'display notification "Karaoke open..."sound name "/System/Library/Sounds/Ping.aiff"\'') # def start_fork(self): # pid = os.fork() # if pid == 0: # Menu().alert("") # else: # Menu().start() def _process_cmd(self, cmd): cmd = re.sub('\s+', ' ', cmd) parts = cmd.split(" ") cmd = parts[0] if len(parts) > 1: params = parts[1:] else: params = None if cmd == "clear": self._clear_list() elif cmd == "next" or cmd == "n": self._next() elif cmd == "browse" or cmd == "b": self._browse() elif cmd == "pause" or cmd == "p": self._pause() elif cmd == "full" or cmd == "f": self._full(params) elif cmd == "vocal" or cmd == "v": self._vocal(params) elif cmd == "laugh" or cmd == "l": self._laugh() elif cmd == "woo" or cmd == "w": self._woo() elif cmd == "applause" or cmd == "a": self._applause() elif cmd == "replay" or cmd == "r": self._replay() elif cmd == "s" or cmd == "search": self._search(params) else: self._search([cmd]) def _full(self, param): if param: param = " ".join(param).strip().lower() if param == "on": self.player.fullscn() elif param == "off": self.player.fullscn(False) else: self.player.fullscn() def _vocal(self, param): if param: param = " ".join(param).strip().lower() if param == "on": self.player.change_atrack(1) elif param == "off": self.player.change_atrack(2) else: self.player.change_atrack(None) def _laugh(self): self.sound.laugh() def _applause(self): self.sound.applause() def _woo(self): self.sound.woo() def _next(self): self.player.next() def _pause(self): self.player.pause() def _replay(self): self.player.replay() def _clear_list(self): while True: resp = getch("Are you sure to clear the list? [Y/N] ") resp = resp.lower() print if resp == "y": self.player.clear() return elif resp == "n": return def _browse(self): songs = self.lib.browse() return self.display_list(songs, "song") def _search(self, param): if param: param = " ".join(param).strip() items = [("搜索歌曲", self._search_song), ("搜索歌手", self._search_artist)] self.display_list(items, "menu", param) def _search_artist(self, param): artists = self.lib.search_artist(param) return self.display_list(artists, "artist") # if artist: # name = artist["name"] # songs = self.lib.get_song_by_artist(name) # song = Menu.display_list(songs, "song") # if song: # loc = str(song["loc"]) # src_dir, f = os.path.split(loc) # self.player.add_to_playlist(src_dir, f) # src_dir, f = os.path.split(loc) # self.player.add_to_playlist(src_dir, f) def _search_song(self, param): songs = self.lib.search_song(param) return self.display_list(songs, "song") @staticmethod def display_menu(item, prefix): if prefix is not None: print str(prefix) + ". " + item[0] else: print item[0] def display_list(self, l, operation_type, param=None): if l: size = len(l) max_page = int(math.ceil(size / 10.0)) page = 0 to_main = False while not to_main: if operation_type == "menu": print "====================" else: print "\n"*50+"========= PAGE: %d/%d ===========" % (page+1, max_page) for i in range(10): if page * 10 + i >= size: break item = l[page * 10 + i] prefix = i + 1 if i < 9 else 0 if operation_type == "song": Library.display_song(item, prefix) elif operation_type == "artist": Library.display_artist(item, prefix) elif operation_type == "menu": Menu.display_menu(item, prefix) print "====================" print "(Nums)选择 (N)下一页 (P)上一页 (B)后退 (M)主菜单\n" valid_selection = False sys.stdout.write("please select > ") while not valid_selection: select = getch() if select == "b": return if select == "m": return True elif select == "n": new_page = min(page + 1, max_page - 1) if page != new_page: page = new_page valid_selection = True continue elif select == "p": new_page = max(page - 1, 0) if page != new_page: page = new_page valid_selection = True continue elif select.isdigit(): choice_str = select select = int(select) select = select - 1 if select > 0 else 9 idx = page * 10 + select if idx < size: res = l[idx] print choice_str to_main = self._select(res, operation_type, param) valid_selection = True else: continue else: pass return True else: with color("pink"): print "\n" print "\tMMMMMMMMMMMMMMMMMMMMMWNK0kxdooooooodxk0XNWMMMMMMMMMMMMMMMMMM" print "\tMMMMMMMMMMMMMMMWWNKkoc;'...............,:lx0NWMMMMMMMMMMMMMM" print "\tMMMMMMMMMMMMWNX0d:'.........................;lkXWMMMMMMMMMMM" print "\tMMMMMMMMMMWNKkl,........,:clodddddooc:,'.......;d0WMMMMMMMMM" print "\tMMMMMMMMWXKkc'......;ldOKXXXXXXXXXXXXXKOxl;......'l0WMMMMMMM" print "\tMMMMMMWXKOo'.....'lkKXXXXXXXXXXXXXXXXXXXXXKko;.....,dXMMMMMM" print "\tMMMMWNX0k:.....,oOXXXXXXXXXXXXXXXXK0KXXXXXXXX0d;.....:0WMMMM" print "\tMMMWNK0x;.....cOXXXXXXK00XXXXXXXKx:':xKXXXXXXXX0o,....,kWMMM" print "\tMMMNKKk;....'oKXXXXXXKo,,lOXXXNX0l....:xKXXXXXXXXk:....'xWMM" print "\tMMNKKO:....'dKXXXXXXKo...,xXXXXXXKx;....:kKXXXXXXXOc....,OWM" print "\tMWKK0o.....oKXXXXXX0l...'dKXXXXXXXX0l'....ckKXXXXXXO:....:KM" print "\tWXKKk;....:0XXXXXX0c....lKXXXXXXXXXXKk:....'oKXXXXXXk,....dN" print "\tWXKKd'....dXXXXXXO:....c0XXXXXXXXXXXXX0o,..'xXXXXXXXKl....:K" print "\tNKK0l....,kXXXXXXOc...;OXXXXXXXXXXXXXXXXOc;dKXXXXXXXXx'...'k" print "\tNKK0l....;OXXXXXXX0d,,xXXXXXXXXXXXXXXXXXXK0XXXXXXXXXXk;....d" print "\tNKK0l....;OXXXXXXXXXOOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXO;....o" print "\tNKK0o....'xXXXXXXXXXXXXXXXXXKKK00OOkkxddollclkXXXXXXXk,....d" print "\tWKKKx,....lKXXXXXXXOdoollc::;,,,''..........'xXXXXXXXd....'k" print "\tWXKKOc....;kXXXXXXXx'.......................;OXXXXXX0:....:K" print "\tMNKK0x,....c0XXXXXXKl.....';::ccllloddc.....lKXXXXXKd.....xW" print "\tMWXKK0l.....l0XXXXXXk,....l0XXXXXXXXXXx'....dXXXXXXx,....cXM" print "\tMMWXKKOc.....cOXXXXXKo....;OXXXXXXXXXXx'...,kXXXXKd,....;0WM" print "\tMMMWXKKOl.....;xKXXXXO:....dXXXXXXXXXXd....:0XXX0l'....;OWMM" print "\tMMMMWXKK0o'.....ckKXXXd'...:0XXXXXXXXXd....lKX0d;.....:0WMMM" print "\tMMMMMWNKK0x:......:d0X0c...'dXXXXXXXXXo...'dOo;.....'oXMMMMM" print "\tMMMMMMMWNKKOd;......,cdl'...c0XXXXXXXXo....,'......c0WMMMMMM" print "\tMMMMMMMMMWXKKOd:............'lxxkkxxdl;.........'lONMMMMMMMM" print "\tMMMMMMMMMMMWNXK0xl;..........................':dKWMMMMMMMMMM" print "\tMMMMMMMMMMMMMMWNXX0koc;'.................':lxKNMMMMMMMMMMMMM" print "\tMMMMMMMMMMMMMMMMMWWNNXKOkdolc:::::cclodkOXNWMMMMMMMMMMMMMMMM" print "\tMMMMMMMMMMMMMMMMMMMMMMMWWWWWNNNNNNWWMMMMMMMMMMMMMMMMMMMMMMMM" print "\n" getch("It seems your query does not match any record in our library, press ENTER to continue... ") return def _select(self, selection, t, param): if t == "song": song = selection if song and util.add_to_playlist(self.player, song): with color('yellow'): sys.stdout.write("\nSong added: ") Library.display_song(song) print sleep(.5) else: print "Song not found!" elif t == "artist": artist = selection if artist: aid = artist["id"] songs = self.lib.get_song_by_artist(aid) return self.display_list(songs, "song") elif t == "menu": if selection: return selection[1](param)
def __init__(self): self.const = util.Constant() self.player = VLC() self.lib = Library() self.user = User() self.sound = Sound()
def __init__(self, scale, vol, colors): self.colors = colors self.__init_randomized_cells() self.surface = pygame.Surface(screen_size) self.sound = Sound(scale, vol)
class Game: def __init__(self, scale, vol, colors): self.colors = colors self.__init_randomized_cells() self.surface = pygame.Surface(screen_size) self.sound = Sound(scale, vol) def __init_randomized_cells(self): self.cells = [] for y in range(game_height): row = [] self.cells.append(row) for x in range(game_width): row.append(Cell(x, y, self.colors, random.choice([True, False, False, False]))) self.cellsT = [list(i) for i in zip(*self.cells)] def playSound(self, ticks): if len != 0: self.sound.play(len(filter(lambda c: c.alive, self.cellsT[ticks]))) def change_column_color(self, ticks): for cell in self.cellsT[ticks]: cell.switch_color() def draw(self): self.surface.fill(black) for x in range(game_width): for y in range(game_height): cell = self.cells[y][x] if cell.alive: pygame.draw.rect(self.surface, cell.color, cell.rect) def iterate(self): for x in range(game_width): for y in range(game_height): cell = self.cells[y][x] cell.calculate_next(len(self.__alive_neighbours(cell))) def new_generation(self): for x in range(game_width): for y in range(game_height): cell = self.cells[y][x] cell.new_generation() def __neighbours(self, cell): iter_start_x = cell.x - 1 iter_start_y = cell.y - 1 iter_end_x = cell.x + 1 iter_end_y = cell.y + 1 neighbours = [] for xi in range(iter_start_x, iter_end_x+1): for yi in range(iter_start_y, iter_end_y+1): if cell.x == xi and cell.y == yi: continue neighbours.append(self.cells[yi % game_height][xi % game_width]) return neighbours def __alive_neighbours(self, cell): return filter(lambda c: c.is_alive(), self.__neighbours(cell))