def process_input(self, key, symbol, state: GameState, menu: Menu): if self.section == 'pause': if key == K_DOWN: self.__choice += 1 Sounds().menu_selection.play() if self.__choice > 2: self.__choice = 0 elif key == K_UP: self.__choice -= 1 Sounds().menu_selection.play() if self.__choice < 0: self.__choice = 2 elif key == K_RETURN: self.__select(menu) elif key == K_ESCAPE: self.__choice = 0 self.is_active = False pygame.mixer.music.unpause() elif self.section == 'save': if key == K_RETURN: state.save(self.__savename) self.__savename = '' self.section = 'pause' self.is_active = False Sounds().menu_selection.play() pygame.mixer.music.unpause() elif key == K_BACKSPACE: self.__savename = self.__savename[:-1] else: self.__savename += symbol
def __init__(self): """Initialize the game, and create game resources""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Alien Invasion") # self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_hight = self.screen.get_rect().height # Create an instance to store game statistics, # and create a scoreboard. self.stats = GameStats(self) self.sb = Scoreboard(self) self.sounds = Sounds(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() # Make the Play button. self.play_button = Button(self, "Play")
def attack(self, entity_lst): if self._inventory['equipment']['arm'] is not None: self._current_animation = 'attack' if self.__attack_count == 0: self._frame = 0 self.__attack_count = 6 elif self.__attack_count == 6: self.__attack_count = 12 elif self.__attack_count == 12: self.__attack_count = FC_HERO_ATTACK for entity in entity_lst: if isinstance(entity, Monster): if self.__side == RIGHT and self.position.x + 64 / TILE_SIZE[ 0] <= entity.position.x <= self.position.x + 95 / TILE_SIZE[ 0] and self.position.y - 13 <= entity.position.y <= self.position.y + 45 / TILE_SIZE[ 1]: entity._health -= self._damage if not entity.isDead(): Sounds().hit.play() elif self.__side == LEFT and self.position.x - 61 / TILE_SIZE[ 0] <= entity.position.x <= self.position.x - 32 / TILE_SIZE[ 0] and self.position.y - 13 <= entity.position.y <= self.position.y + 45 / TILE_SIZE[ 1]: entity._health -= self._damage if not entity.isDead(): Sounds().hit.play()
def _check_play_button(self, mouse_pos): """Запускает новую игру при нажатии кнопки Play.""" button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: # Сброс игровых настроек. self.settings.initialize_dynamic_settings() # Сброс игровой статистики. self.stats.reset_stats() self.stats.game_active = True # Обнуление статистики self.sb.prep_score() # Отображение текущего уровня self.sb.prep_level() # отображение оставшихся кораблей игрока self.sb.prep_ships() # Очистка списков пришельцев и снарядов. self.aliens.empty() self.bullets.empty() # Создание нового флота и размещение корабля в центре. self._create_fleet() self.ship.center_ship() # Указатель мыши скрывается. pygame.mouse.set_visible(False) # Запускаем музыку сражения fighting_music = Sounds('sounds/fighting.mp3') fighting_music.playing_music()
def __init__(self, modes): GPIO.setmode( GPIO.BCM) #set up to use gpio port numbers (instead of pin #s) self.buttons = Buttons() self.optos = Optos() self.lights = Lights() self.outlets = Outlets() self.sounds = Sounds() self.clock = Countdown(12) self.modes = modes self.last_time = time.localtime()
def tutorial_msg(step=0): if step == 0: return "You've finished our small tutorial. What would you like to do now? Do the grammar or the pronunciation exercise?" elif step == 1: return 'Welcome to the grammar exercise. I will give you an infinitive and the tense in which it should be used. \ The ' + Sounds.beep() + ' beep sound shows you where the correct verbform should go. \ I will do the first one: <break time="1s" /> To go <break time="1s"/> \ simple past <break time="1s"/> I ' + Sounds.beep() + ' to the park. \ <break time="1s"/> The correct answer would be <break time="1s"/> I walked in the park. <break time="1s"/> Now it is your turn! ' elif step == 2: return '<break time="1s"/> Now let\'s move on to the pronunciation exercise<break time="1s"/>' else: return ''
def apply(state): editor = SoundEditor(state) for cur in editor: next = cur.next if next.value is None: continue x, y = cur.value, next.value if x in Sounds('ac'): cur.value, next.value = ac_sandhi(x, y) elif x in Sounds('hal'): cur.value, next.value = hal_sandhi(x, y) yield editor.join()
def start_game(): #needs to be called before pygame.init pygame.mixer.pre_init(22050, -16, 2, 1024) window = Window() window.init() pygame.init() sounds = Sounds() sounds.init() window.sounds = sounds pygame.mixer.set_num_channels(32) # meta game loop while True: sounds.play_music("intro", loop=1) intro_main(window, handle_events) # so we can mix more channels at once. pygame defaults to 8. #sounds.play("jump1") #sounds.play("hit1") #sounds.play("goal1") sounds.set_music_tracks(['track-one', 'track-two']) world = World() world.stage = 2 populate(world, window) def count_leaves(): no_leaves = 0 for item in world.items: if item.role == "Bough": no_leaves = no_leaves + 1 return no_leaves CleanUp_Event = pygame.event.Event(CLEANUP, message="Cleaning Up Your shit") pygame.time.set_timer(CLEANUP, 1000) TickTock = pygame.event.Event( TICK_TOCK, message="TickTock goes the Ticking Clock") pygame.time.set_timer(TICK_TOCK, int(90000 / count_leaves())) AddCherry = pygame.event.Event(ADDCHERRY, message="Ooooo Cherry") pygame.time.set_timer(ADDCHERRY, int(90000 / 5)) AddOwange = pygame.event.Event(ADDOWANGE, message="Ooooo owange") pygame.time.set_timer(ADDOWANGE, int(1000 * 5)) for i in range(3): event.post(AddOwange) pygame.time.set_timer(BIRDY, 1000 * 7) render = Render(window, world) quit = runloop(window, world, render) if quit: return
def __init__(self, screen, user, maze): self.screen = screen self.maze = maze self.user = user self.sounds = Sounds( sound_files=['portal-open.wav', 'portal-travel.wav'], keys=['open', 'travel'], channel=PortalController.PORTAL_AUDIO_CHANNEL) self.blue_portal = pygame.sprite.GroupSingle( ) # portals as GroupSingle, which only allows one per group self.blue_projectile = None self.orange_portal = pygame.sprite.GroupSingle() self.orange_projectile = None self.portal_directions = {'l': 'r', 'r': 'l', 'u': 'd', 'd': 'u'}
def al_tasya(target, result): target = Sounds(target) result = Sounds(result) def func(value): letters = list(value) for i, L in enumerate(letters): if L in target: letters[i] = Sound(L).closest(result) # 1.1.51 ur aṇ raparaḥ if L in 'fF' and letters[i] in Sounds('aR'): letters[i] += 'r' break return ''.join(letters) return func
def hal_sandhi(x, y): """Apply the rules of hal sandhi to `x` as followed by `y`. These rules are from 6.1. A rule is part of hal sandhi iff the first letter is a consonant. :param x: the first letter. :param y: the second letter. """ # 6.1.66 lopo vyor vali if x in Sounds('v y') and y in Sounds('val'): x = '' return x, y
def run_game(): # Initialize pygame, settings, and screen object. pygame.mixer.pre_init(44100, -16, 2, 2048) pygame.mixer.init() pygame.init() game_settings = GameSettings() screen = pygame.display.set_mode((game_settings.screen_width, game_settings.screen_height)) pygame.display.set_caption("Pac Man Portal") # Open sprite sheet sprite_sheet = SpriteSheet(file_name='images/spritesheet.png') # Make the Play and Scores button. play_button = Button(screen=screen, msg="Play", order=0) score_button = Button(screen=screen, msg="High Scores", order=1) # Open high score file try: high_score_file = open("high_score_file.txt", "r+") except FileNotFoundError: high_score_file = open("high_score_file.txt", "w+") # Open maze layout file maze_file = open('mazelayout.txt', 'r') # Make sound manager sounds = Sounds() # Initialize game stats and scoreboard stats = GameStats(game_settings=game_settings) sb = Scoreboard(screen=screen, game_settings=game_settings, stats=stats, sprite_sheet=sprite_sheet, high_score_file=high_score_file, sounds=sounds) # Initialize pacman pacman = Pacman(screen=screen, game_settings=game_settings, stats=stats, sb=sb, image_list=sprite_sheet.pacman_image, death_anim_list=sprite_sheet.pacman_death_image, sounds=sounds) # Initialize maze maze = Maze(screen=screen, game_settings=game_settings, maze_file=maze_file, sprite_sheet=sprite_sheet, pacman=pacman, sounds=sounds) # Initialize the event handler event_handler = EventHandler(pacman=pacman, play_button=play_button, score_button=score_button, stats=stats, sb=sb, maze=maze, sounds=sounds) # Initialize the display manager display = Display(screen=screen, game_settings=game_settings, stats=stats, sb=sb, sprite_sheet=sprite_sheet, play_button=play_button, score_button=score_button, maze=maze, pacman=pacman, event_handler=event_handler, sounds=sounds) # Start the main loop for the game while True: event_handler.check_events() if stats.game_active: pacman.update(maze=maze, display=display) maze.update_ghosts() maze.update_bullets() maze.update_portals() display.update_screen()
def __init__(self): """ iniciando el juego y recursos""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Alien Invasion by David") self.bg_x = self.settings.bg_x_pos self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.sounds = Sounds() self.alien = Alien(self) self.aliens = pygame.sprite.Group() self._create_fleet() # crea el boton self.play_button = Button(self, 'Jugar') # crea una instancia de game stats self.stats = GameStats(self) # crea una insancia de Score self.sb = Scoreboard(self)
def __init__(self): pygame.init() pygame.display.set_caption("Pacman Portal") self.screen = pygame.display.set_mode((800, 600)) self.maze = Maze(screen=self.screen, maze_map_file='pacmanportalmaze.txt') self.clock = pygame.time.Clock() self.ghost_sounds = Sounds(sound_files=['ghost-blue.wav', 'ghost-eaten.wav', 'ghost-std.wav'], keys=['blue', 'eaten', 'std'], channel=Ghost.audio) self.stock = PacmanLives(screen=self.screen, ct_pos=((self.screen.get_width() // 3), (self.screen.get_height() * 0.965)), images_size=(self.maze.block_size, self.maze.block_size)) self.score = ScoreController(screen=self.screen, sb_pos=((self.screen.get_width() // 5), (self.screen.get_height() * 0.965)), items_image='cherry.png', itc_pos=(int(self.screen.get_width() * 0.6), self.screen.get_height() * 0.965)) self.next_level = NextLevel(screen=self.screen, score_controller=self.score) self.game_over = True self.pause = False self.player = Pacman(screen=self.screen, maze=self.maze) self.ghosts = Group() self.ghost_time = 2500 self.ghosts_stack = None self.top_ghost = None self.arr_ghost = [] self.spawn_ghosts() self.events = {PacmanPortal.START_EVENT: self.init_ghosts, PacmanPortal.REBUILD_EVENT: self.rebuild_maze, PacmanPortal.LEVEL_EVENT: self.clear_level}
def func(state, index, locus): term = state[index] term_value = term.get_at(locus) new_value = None add_part = False # 1.1.54 ādeḥ parasya if adi: try: new_value = sthani.value + term_value[1:] except AttributeError: new_value = sthani + term_value[1:] elif isinstance(sthani, basestring): # 1.1.52 alo 'ntyasya # 1.1.55 anekālśit sarvasya if len(sthani) <= 1: new_value = term_value[:-1] + sthani else: new_value = sthani elif not hasattr(sthani, 'value'): # 1.1.50 sthāne 'ntaratamaḥ last = Sound(term.antya).closest(sthani) new_value = term_value[:-1] + last # 1.1.47 mid aco 'ntyāt paraḥ elif 'mit' in sthani.samjna: ac = Sounds('ac') for i, L in enumerate(reversed(term_value)): if L in ac: break new_value = term_value[:-i] + sthani.value + term_value[-i:] add_part = True # 1.1.46 ādyantau ṭakitau elif 'kit' in sthani.samjna: new_value = term_value + sthani.value add_part = True elif 'wit' in sthani.samjna: new_value = sthani.value + term_value add_part = True # 1.1.52 alo 'ntyasya # 1.1.53 ṅic ca elif len(sthani.value) == 1 or 'Nit' in sthani.samjna: new_value = term_value[:-1] + sthani.value # 1.1.55 anekālśit sarvasya elif 'S' in sthani.it or len(sthani.value) > 1: new_value = sthani.value if new_value is not None: new_term = term.set_at(locus, new_value) if add_part: new_term = new_term.add_part(sthani.raw) return state.swap(index, new_term) raise NotImplementedError(sthani)
def run_game(): # Initialize pygame, settings, screen object, music channel pygame.init() sounds = Sounds() # Limit FPS clock = pygame.time.Clock() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Create an instance to store game statistics and create a scoreboard. stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # Create the start and highscore screen start_screen = StartScreen(ai_settings, screen) hs_screen = HighScoreScreen(ai_settings, screen, stats) # Make a ship, a group of ship_bullets, and a group of aliens ship = Ship(screen, ai_settings) ship_bullets = Group() aliens = Group() alien_bullets = Group() bunkers = Group() # Create the fleet of aliens and row of bunkers gf.create_fleet(ai_settings, screen, ship, aliens) gf.create_bunker_row(ai_settings, screen, ship, bunkers) # Start the main loop for the game while True: # Limit FPS clock.tick(60) # Watch for keyboard/mouse events gf.check_events(ai_settings, screen, stats, sb, start_screen, ship, aliens, ship_bullets, sounds, bunkers, hs_screen) if stats.game_active: ship.update(stats.ships_left) ship_bullets.update() alien_bullets.update() bunkers.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bunkers, ship_bullets, alien_bullets, sounds) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, ship_bullets, alien_bullets, sounds) # Redraw the screen during each pass through the loop. # Make the most recently drawn screen visible gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, ship_bullets, alien_bullets, start_screen, bunkers, hs_screen)
def __init__(self): """Инициализирует игру и создает игровые ресурсы.""" self.settings = Settings() # Функция pri_init должна вызываться до pygame.init pygame.mixer.pre_init(44100, -16, 1, 512) pygame.init() # Инициируем методы трансляции звуков в игре # pygame.mixer.init() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Alien Invasion") #pygame.display.set_icon(pygame.image.load("app.bmp")) # Загрузим фоновое изображение self.bg = pygame.image.load('images/StarFon1280x905.jpg') # Масштабируем изображение по величине игровой поверхности self.bg = pygame.transform.scale( self.bg, (self.settings.screen_width, self.settings.screen_height)) # Задаём что левый верхний угол изображения должен совпадать с углом экрана игры self.bg_rect = self.bg.get_rect(topleft=(0, 0)) self.volume = 1.0 #Загружаем музыку и звуки bg_music = Sounds('sounds/alarm.mp3') bg_music.playing_music() # Созданим несколько звёзд, которые случайным образом будут располагаться на небе. self.star_image = 'images/Star40x40.png' self._create_Stars(self.star_image) # Создаём группу для отрисовки взрывов self.explosions = pygame.sprite.Group() # Создаём экземпляр класса Animation. self.explosion = Animation((100, 100), 'images/explosions/explosion', 30) # Создаём группу спрайтов для отрисовки снарядов, это своего рода список с расширенной функциональностью self.bullets = pygame.sprite.Group() # Создаём группу пришельцев. Их отображение будет реализовано методами группы Pygame self.aliens = pygame.sprite.Group() # Создание экземпляра для хранения игровой статистики и панели результатов self.stats = GameStats(self) self.sb = Scoreboard(self) # Создаём объект ship, передав конструктору класса указатель на экземпляр класса AlienInvasion self.ship = Ship(self) self._create_fleet() # Создаём объект времени в игре self.clock = pygame.time.Clock() # Создание кнопки Play. self.play_button = Button(self, "Play")
def __init__(self, screen, score_controller, transition_time=5000): self.screen = screen self.score_controller = score_controller self.sound = Sounds(['pacman-beginning.wav'], keys=['transition'], channel=NextLevel.audio, volume=0.6) self.font = pygame.font.Font('fonts/LuckiestGuy-Regular.ttf', 32) self.ready_msg = self.font.render('Get Ready!', True, Scoreboard.white) self.ready_msg_rect = self.ready_msg.get_rect() ready_pos = screen.get_width() // 2, int(screen.get_height() * 0.65) self.ready_msg_rect.centerx, self.ready_msg_rect.centery = ready_pos self.level_msg = None self.level_msg_rect = None self.transition_time = transition_time self.transition_begin = None self.transition_show = False
def samyogapurva(term): """Filter on whether a term's final sound follows a conjunct.""" value = term.value hal = Sounds('hal') try: return value[-3] in hal and value[-2] in hal except IndexError: return False
def __init__(self): self.bg = pygame.image.load("images/bg.jpg") self.bg = pygame.transform.scale(self.bg, (SCREEN_WIDTH, SCREEN_HEIGHT)) self.bgrect = self.bg.get_rect() self.ball = Ball() self.human = Human() self.robot = Robot() self.goal = Goal(0) self.win = Win(0) self.lose = Lose(0) self.menu = Menu() self.mouse = (0, 0) self.sounds = Sounds() self.sounds.music() self.status = Game.MENU self.reset()
def check_msg(correct, solution, next_ex, celebrate=False): if correct: if celebrate: return 'Very good! ' + solution + '<break time="1s"/>' + Sounds.celebration() + '<break time="1s"/>' + Helper.congrats() + Helper.ex_ask_msg() else: return 'Very good! ' + solution + '. Here comes the next exercise: <break time="1s"/> ' + next_ex else: return 'I think this was wrong. Correct answer is ' + solution + '. Here comes the next exercise: <break time="1s"/>' + next_ex
def samyogadi(term): """Filter on whether a term begins with a conjunct.""" value = term.value hal = Sounds('hal') try: return value[0] in hal and value[1] in hal except IndexError: return False
def ekac(term): seen = False ac = Sounds('ac') for L in term.value: if L in ac: if seen: return False seen = True return True
def load_new_exercise_data(): ex_obj = random.choice(ex_iv) session.attributes['solution_verbform'] = ex_obj['answer'] session.attributes['solution_sentence'] = "%s %s %s" % ( ex_obj['sentence_front'], ex_obj['answer'], ex_obj['sentence_back']) session.attributes['task'] = "%s, %s, %s" % ( ex_obj['verb'], ex_obj['tense'], ex_obj['sentence_front'] + Sounds.beep() + ex_obj['sentence_back']) session.attributes['HelpLeadsTo'] = ex_obj['tense']
class NextLevel: audio = 4 def __init__(self, screen, score_controller, transition_time=5000): self.screen = screen self.score_controller = score_controller self.sound = Sounds(['pacman-beginning.wav'], keys=['transition'], channel=NextLevel.audio, volume=0.6) self.font = pygame.font.Font('fonts/LuckiestGuy-Regular.ttf', 32) self.ready_msg = self.font.render('Get Ready!', True, Scoreboard.white) self.ready_msg_rect = self.ready_msg.get_rect() ready_pos = screen.get_width() // 2, int(screen.get_height() * 0.65) self.ready_msg_rect.centerx, self.ready_msg_rect.centery = ready_pos self.level_msg = None self.level_msg_rect = None self.transition_time = transition_time self.transition_begin = None self.transition_show = False def prep_level_msg(self): text = 'level ' + str(self.score_controller.level) self.level_msg = self.font.render(text, True, Scoreboard.white) self.level_msg_rect = self.level_msg.get_rect() level_pos = self.screen.get_width() // 2, self.screen.get_height() // 2 self.level_msg_rect.centerx, self.level_msg_rect.centery = level_pos def set_show_transition(self): self.prep_level_msg() self.transition_begin = pygame.time.get_ticks() self.transition_show = True self.sound.play('transition') def draw(self): if abs(self.transition_begin - pygame.time.get_ticks()) > self.transition_time: self.transition_show = False else: self.screen.fill((0, 0, 0)) self.screen.blit(self.level_msg, self.level_msg_rect) if abs(self.transition_begin - pygame.time.get_ticks()) >= self.transition_time // 2: self.screen.blit(self.ready_msg, self.ready_msg_rect)
def __kill_entities(self, entity_lst, i=0): if i == len(entity_lst): return if entity_lst[i].isDead(): entity_lst.remove(entity_lst[i]) Sounds().death.play() self.__kill_entities(entity_lst, i) else: self.__kill_entities(entity_lst, i + 1)
def __init__(self, w, h): pygame.init() self.size = w, h self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption(TITLE) pygame.display.flip() self.hero_is_died = pygame.sprite.Sprite() self.hero_is_died.image = pygame.image.load("data/hero_died.png") self.hero_is_died.rect = self.hero_is_died.image.get_rect() self.hero_is_win = pygame.sprite.Sprite() self.hero_is_win.image = pygame.image.load("data/win.png") self.hero_is_win.rect = self.hero_is_died.image.get_rect() self.dead = pygame.sprite.Group() self.win_sp = pygame.sprite.Group() self.hero_is_win.add(self.win_sp) self.hero_is_died.add(self.dead) self.camera = Camera(w, h) self.win_m, self.dead_m = False, False self.music = [ pygame.mixer.Sound("data/background_music_1.ogg"), pygame.mixer.Sound("data/background_music_2.ogg"), pygame.mixer.Sound("data/background_music_3.ogg") ] self.menu_music = pygame.mixer.Sound("data/music/main_menu.ogg") self.victory_music = pygame.mixer.Sound("data/Victory.wav") self.dead_music = pygame.mixer.Sound("data/dead.wav") self.menu_music.play(-1) self.hero_sprite = pygame.sprite.Group() self.enemy_sprites = pygame.sprite.Group() self.boss_sprite = pygame.sprite.Group() self.platform_sprites = pygame.sprite.Group() self.all_sprites = pygame.sprite.Group() self.princess_sprite = pygame.sprite.Group() self.info_sprites = pygame.sprite.Group() self.background_sprite = pygame.sprite.Group() self.buttons = pygame.sprite.Group() self.level_names = ["intro", "1", "2", "final"] self.level_state = 0 self.new_game_btn = Button(self.buttons, "new_game_btn.png", "new_game_btn_2.png", 208, 93, "bookFlip2.ogg", "new_game") self.hero = Hero(self.hero_sprite, 60, 60, Sounds().return_dict_of_sounds()) self.hero.add(self.all_sprites) self.cursor_group = pygame.sprite.Group() self.cursor = Cursor(self.cursor_group) self.main_menu = True self.bg = Background(self.background_sprite) self.main_img = pygame.image.load("data/main_menu.png") pygame.mouse.set_visible(False) self.clock = pygame.time.Clock() self.fps = 40 self.just_music = None self.left_state, self.up_state, self.attack = None, None, None self.running = True
def setup(self): """ Called once at the start :return: none """ # open window arcade.open_window(self.WINDOW_WIDTH, self.WINDOW_HEIGHT, "Main") arcade.schedule(self.on_update, 1 / 60) arcade.set_background_color(arcade.color.BLACK) # setting up rooms self.tile_map = TiledMap() self.rooms = [] room = self.tile_map.tutorial_world() self.rooms.append(room) room = self.tile_map.stage_one() self.rooms.append(room) room = self.tile_map.stage_two() self.rooms.append(room) room = self.tile_map.stage_three() self.rooms.append(room) room = self.tile_map.boss_world() self.rooms.append(room) self.room_tutorial() # add start screen self.transition = arcade.load_texture("images/start_screen.png") # add sounds self.sound = Sounds() self.sound.update(1) # override arcade methods self.level_finish_time = 0 self.game_over = False window = arcade.get_window() window.on_key_press = self.on_key_press window.on_key_release = self.on_key_release window.on_draw = self.on_draw arcade.finish_render() arcade.run()
def __init__(self): ## initialize game pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Alien Invasion") self.stars = pygame.sprite.Group() self._create_sky() self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self.snd = Sounds() self.snd.start_bg_music() self._create_fleet() self.play_button = Button(self, "Play")
def __select(self, menu: Menu): if self.__choice == 0: self.is_active = False pygame.mixer.music.unpause() elif self.__choice == 1: self.section = 'save' elif self.__choice == 2: menu.is_active = True self.is_active = False self.__choice = 0 Sounds().select.play()
def __init__(self): pygame.mixer.pre_init(44100,-16,2,2048) pygame.init() self.sounds=Sounds() self.input_handler = InputHandler() self.game_screen = GameScreen(self.TITLE,self.WIDTH,self.HEIGHT) self.miner=Miner(8,0) self.explosion=Explosion(-1,-1) self.game_screen.add_sprite(self.miner) self.game_screen.add_sprite(self.explosion) self.health = 100 self.clock=pygame.time.Clock() self.state=self.WAITING self.game_screen.display_opening()
class StartQT4(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_mainWindow() self.ui.setupUi(self) # Force consistent theme and font size QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Plastique")) self.setStyleSheet("font-size: 11pt") # Disable resizing self.setFixedSize(self.size()) # Disable settings frame until a set is selected self.ui.frame.setEnabled(False) self.msg("Enabling frame.") # Clear lists self.ui.listSets.clear() self.ui.listPhonemes.clear() # Indices of objects currently selected in the interface self.levelIndex = 0 self.setIndex = None self.phonemeIndex = None # Instantiate all levels self.levels = [] for n in range(0, NUM_LEVELS): self.levels.append(Level()) self.msg("Adding level " + str(n+1)) # Update the displayed list of sets self.update_sets() self.msg("Updating set list.") # Display images self.show_images() ####################################################### # Interface Object Connections # ####################################################### itemClicked = QtCore.SIGNAL("itemClicked(QListWidgetItem *)") clicked = QtCore.SIGNAL("clicked()") ## List Widgets QtCore.QObject.connect(self.ui.listSets, itemClicked, self.select_set) QtCore.QObject.connect(self.ui.listPhonemes,itemClicked, self.select_phoneme) ## Buttons QtCore.QObject.connect(self.ui.btnAddSet, clicked, self.add_set) QtCore.QObject.connect(self.ui.btnRemoveSet, clicked, self.remove_set) QtCore.QObject.connect(self.ui.btnAddPhoneme, clicked, self.add_phoneme) QtCore.QObject.connect(self.ui.btnRemovePhoneme, clicked, self.remove_phoneme) QtCore.QObject.connect(self.ui.btnSetGoal, clicked, self.set_goal) QtCore.QObject.connect(self.ui.btnLoadImage, clicked, self.load_image) QtCore.QObject.connect(self.ui.btnModifySounds, clicked, self.modify_sounds) QtCore.QObject.connect(self.ui.btnSave, clicked, self.save) QtCore.QObject.connect(self.ui.btnLoad, clicked, self.load) QtCore.QObject.connect(self.ui.btnInstall, clicked, self.install) QtCore.QObject.connect(self.ui.btnCustom, clicked, self.custom_sound) QtCore.QObject.connect(self.ui.btnA, clicked, self.a) QtCore.QObject.connect(self.ui.btnO, clicked, self.o) QtCore.QObject.connect(self.ui.btnEU, clicked, self.eu) QtCore.QObject.connect(self.ui.btnE_grave, clicked, self.e_grave) QtCore.QObject.connect(self.ui.btnE_acute, clicked, self.e_acute) QtCore.QObject.connect(self.ui.btnE, clicked, self.e) QtCore.QObject.connect(self.ui.btnI, clicked, self.i) QtCore.QObject.connect(self.ui.btnU, clicked, self.u) QtCore.QObject.connect(self.ui.btnOU, clicked, self.ou) QtCore.QObject.connect(self.ui.btnAN, clicked, self.an) QtCore.QObject.connect(self.ui.btnON, clicked, self.on) QtCore.QObject.connect(self.ui.btnUN, clicked, self.un) QtCore.QObject.connect(self.ui.btnIN, clicked, self.in2) QtCore.QObject.connect(self.ui.btnUI, clicked, self.ui2) QtCore.QObject.connect(self.ui.btnILL, clicked, self.ill) QtCore.QObject.connect(self.ui.btnOI, clicked, self.oi) QtCore.QObject.connect(self.ui.btnP, clicked, self.p) QtCore.QObject.connect(self.ui.btnB, clicked, self.b) QtCore.QObject.connect(self.ui.btnF, clicked, self.f) QtCore.QObject.connect(self.ui.btnV, clicked, self.v) QtCore.QObject.connect(self.ui.btnM, clicked, self.m) QtCore.QObject.connect(self.ui.btnR, clicked, self.r) QtCore.QObject.connect(self.ui.btnT, clicked, self.t) QtCore.QObject.connect(self.ui.btnD, clicked, self.d) QtCore.QObject.connect(self.ui.btnS, clicked, self.s) QtCore.QObject.connect(self.ui.btnZ, clicked, self.z) QtCore.QObject.connect(self.ui.btnN, clicked, self.n) QtCore.QObject.connect(self.ui.btnL, clicked, self.l) QtCore.QObject.connect(self.ui.btnK, clicked, self.k) QtCore.QObject.connect(self.ui.btnG, clicked, self.g) QtCore.QObject.connect(self.ui.btnCH, clicked, self.ch) QtCore.QObject.connect(self.ui.btnJ, clicked, self.j) QtCore.QObject.connect(self.ui.btnGN, clicked, self.gn) ## Others QtCore.QObject.connect(self.ui.txtNewPhoneme, QtCore.SIGNAL("textChanged(const QString&)"), self.check_new_phoneme) QtCore.QObject.connect(self.ui.txtNewPhoneme, QtCore.SIGNAL("returnPressed()"), self.press_enter) QtCore.QObject.connect(self.ui.verticalSlider, QtCore.SIGNAL("valueChanged(int)"), self.change_level) QtCore.QObject.connect(self.ui.sldrFailedAttempts, QtCore.SIGNAL("valueChanged(int)"), self.update_sliders) QtCore.QObject.connect(self.ui.sldrHintsRequested, QtCore.SIGNAL("valueChanged(int)"), self.update_sliders) QtCore.QObject.connect(self.ui.sldrTime, QtCore.SIGNAL("valueChanged(int)"), self.update_sliders) # Updates the displayed list of sets with the internal list. def update_sets(self): # get the list of sets in the selected level level = self.get_level() levelSets = level.sets # clear the displayed sets self.ui.listSets.clear() self.msg("Clearing set list.") # add each set to the list index = 1 for item in levelSets: self.ui.listSets.addItem("Set " + str(index)) self.msg("Adding set index " + str(index)) index += 1 # disable 'remove set' button if necessary if len(levelSets) < 2: self.ui.btnRemoveSet.setEnabled(False) self.msg("Disabling remove set button. (sets = " + str(len(levelSets)) + ")") else: self.ui.btnRemoveSet.setEnabled(True) self.msg("Enabling remove set button. (sets = " + str(len(levelSets)) + ")") # This function is called when the user selects a set from the list def select_set(self, item): # show frame if it isn't there already self.ui.frame.setEnabled(True) # get the index of the selected item index = self.set_index(item) # remember index self.setIndex = index # load phonemes from the current set self.update_phonemes() # clear current phoneme and current goal self.phonemeIndex = None # disable phoneme-specific ui elements self.reset_phoneme_ui() # debug string currentSet = self.get_set() string = "Selecting set at index " + str(index) + ":" string += currentSet.toString() self.msg(string) # This function removes phoneme-specific content from the UI def reset_phoneme_ui(self): self.ui.btnRemovePhoneme.setEnabled(False) self.ui.btnSetGoal.setEnabled(False) self.ui.soundsGroup.setEnabled(False) self.ui.imageGroup.setEnabled(False) self.ui.lblSoundPath.clear() self.ui.lblImagePath = "" self.ui.imgPhoneme.clear() # Enables phoneme-specific content in the UI def enable_phoneme_ui(self): self.ui.btnRemovePhoneme.setEnabled(True) self.ui.btnSetGoal.setEnabled(True) self.ui.soundsGroup.setEnabled(True) self.ui.imageGroup.setEnabled(True) # Updates the phoneme lists def update_phonemes(self): # clear phoneme list self.ui.listPhonemes.clear() # add phonemes into appropriate lists phonemes = self.get_set().phonemes if phonemes != None: for p in range(0, len(phonemes)): # get current phoneme phoneme = phonemes[p] if phoneme.goal: self.ui.listPhonemes.addItem(phoneme.name + " (GOAL)") else: self.ui.listPhonemes.addItem(phoneme.name) # This function is called whenever the user selects an items from the phoneme list def select_phoneme(self, phoneme): # enable 'make goal' button self.enable_phoneme_ui() # get the index of the selected item index = self.phoneme_index(phoneme) # remember index self.phonemeIndex = index # Enable phoneme sounds and load image button self.ui.soundsGroup.setEnabled(True) self.ui.btnLoadImage.setEnabled(True) self.ui.lblSoundPath.clear() # Update interface with phoneme information p = self.get_phoneme() self.msg("Index: " + str(index)) self.msg("Selected phoneme at index " + str(index) + ":\n" + p.toString()) if p.image_path != "": self.ui.lblImagePath = p.image_path self.ui.imgPhoneme.setPixmap(QtGui.QPixmap(p.image_path)) else: self.ui.lblImagePath = "" self.ui.imgPhoneme.clear() self.select_sound(p.text) # Select appropriate sound self.select_sound(p.text) # Enables or disables the 'add phoneme' button as necessary def check_new_phoneme(self, text): # ensure text isn't blank if text != "": # ensure text is unique uniqueName = True currentSet = self.get_set() phonemes = currentSet.phonemes if phonemes != None: for p in range(0, len(phonemes)): phoneme = phonemes[p] if phoneme.name == str(text): uniqueName = False if uniqueName: self.ui.btnAddPhoneme.setEnabled(True) else: self.ui.btnAddPhoneme.setEnabled(False) else: self.ui.btnAddPhoneme.setEnabled(False) # Enter key while editing new phoneme text functionality def press_enter(self): if self.ui.btnAddPhoneme.isEnabled(): self.add_phoneme() # Loads an image into the interface and saves it into the phoneme object def load_image(self): phoneme = self.get_phoneme() phoneme.image_path = str(QtGui.QFileDialog.getOpenFileName()) phoneme.image_file = basename(phoneme.image_path) self.ui.imgPhoneme.setPixmap(QtGui.QPixmap(phoneme.image_path)) self.ui.lblImagePath = phoneme.image_file # Returns the currently selected level def get_level(self): return self.levels[self.levelIndex] # Returns the currently selected set def get_set(self): level = self.levels[self.levelIndex] if self.setIndex != None: return level.sets[self.setIndex] else: return None # Returns the currently selected phoneme def get_phoneme(self): set = self.get_set() if self.phonemeIndex != None: return set.phonemes[self.phonemeIndex] else: return None # Returns the index of a given set as an integer. def set_index(self, item): return int(item.text()[4:]) - 1 # get text from set string # Returns the index of a given phoneme as an integer. def phoneme_index(self, item): currentSet = self.get_set() phonemes = currentSet.phonemes for i in range(0, len(phonemes)): phoneme = phonemes[i] self.msg("Phoneme name: " + str(phoneme.name)) self.msg("Item text: " + str(item.text())) self.msg("Item text [:-7]: " + str(item.text())[:-7]) if str(phoneme.name) == str(item.text()): self.msg("Item text == phoneme name") return i elif str(phoneme.name) == str(item.text())[:-7]: self.msg("Item text + goal == phoneme name") return i return None # Adds a set to the currently selected level def add_set(self): level = self.get_level() self.msg("Adding set.") level.add_set() self.update_sets() # Removes a set from the currently selected level def remove_set(self): if self.setIndex != None: level = self.get_level() self.msg("Removing set at index " + str(self.setIndex)) level.remove_set(self.setIndex) self.update_sets() # Adds a phoneme to the currently selected set def add_phoneme(self): if self.get_num_phonemes() <= MAX_PHONEMES: # build phoneme phoneme = Phoneme() phoneme.name = str(self.ui.txtNewPhoneme.text()) # clear input text self.ui.txtNewPhoneme.clear() # add phoneme to set currentSet = self.get_set() self.msg("Adding phoneme " + phoneme.name) currentSet.add_phoneme(phoneme) self.msg("Current set: " + currentSet.toString()) # update phoneme list self.update_phonemes() else: QtGui.QMessageBox.warning(self, "Phoneme Limit Reached", "You have reached the limit of " + str(MAX_PHONEMES) + " phonemes.\nPlease remove some existing phonemes to add new ones.") # Removes a phoneme from the currently selected set def remove_phoneme(self): if self.phonemeIndex != None: currentSet = self.get_set() self.msg("Removing phoneme at index " + str(self.phonemeIndex)) currentSet.remove_phoneme(self.phonemeIndex) self.reset_phoneme_ui() self.update_phonemes() # Returns the number of phonemes currently in the game. def get_num_phonemes(self): n = 0 for level in self.levels: for set in level.sets: for phoneme in set.phonemes: n += 1 return n # Sets the currently selected phoneme as the goal for the set def set_goal(self): if self.phonemeIndex != None: currentSet = self.get_set() currentSet.set_goal_index(self.phonemeIndex) self.update_phonemes() # Loads the phoneme sound modification inderface def modify_sounds(self): # load up sounds UI self.Sounds = Sounds(self) self.Sounds.show() # Print debug messages, if needed def msg(self, message): if DEBUG: print(str(datetime.time(datetime.now())) + " > DEBUG: " + message) # Switches the interface to edit another level. def change_level(self, newLevel): self.msg("Switching to level " + str(newLevel)) self.levelIndex = newLevel - 1 self.update_sets() self.reset_phoneme_ui() self.ui.listPhonemes.clear() # Updates the sound paths of all phonemes using the sounds config file. def update_sound_paths(self): try: # get the collection from the sounds config file with open("sounds.pk", 'rb') as input: collection = pickle.load(input) self.msg("Data loaded from sounds.pk.") currentSet = self.get_set() phonemes = currentSet.phonemes # for each phoneme, update the path using the text for i in range(0, len(phonemes)): phoneme = phonemes[i] # iterate through every Phoneme_Sound to find a match for ps in collection: if ps.text == phoneme.text: phoneme.sound_path = ps.path except: self.msg("Warning: sounds config file not found.") # Saves the entire configuration as a file using the pickle module. # The file contains a single Game() object as defined in phoneme.py. # The object consists of a list of levels as well as values for each # difficulty slider (failed attempts, hints requested, and time). def save(self): # construct the game object to save game = Game() game.levels = self.levels game.failedAttemptsWeight = self.ui.sldrFailedAttempts.value() game.hintsRequestedWeight = self.ui.sldrHintsRequested.value() game.timeWeight = self.ui.sldrTime.value() # get path to save file to path = QtGui.QFileDialog.getSaveFileName(self, "Save File", "", "Phoneme Awareness Configuration File (*.cfg)") path = str(path) + ".cfg" try: with open(str(path), 'wb') as output: pickle.dump(game, output, pickle.HIGHEST_PROTOCOL) self.msg("Save successful.") except: self.msg("Save failed.") # additionally, save the slider values into a text file #try: # with open("sliders.txt", 'wb') as output: # output.write(str(game.failedAttemptsWeight) + "\n") # output.write(str(game.hintsRequestedWeight) + "\n") # output.write(str(game.timeWeight) + "\n") #except: # self.msg("Slider file output failed.") # Load button functionality def load(self): # get path to load file from path = str(QtGui.QFileDialog.getOpenFileName(self, "Load File", "", "Phoneme Awareness Configuration File (*.cfg)")) # get game object from file game = None try: with open(path, 'rb') as input: game = pickle.load(input) self.levels = game.levels self.ui.sldrFailedAttempts.setValue(game.failedAttemptsWeight) self.ui.sldrHintsRequested.setValue(game.hintsRequestedWeight) self.ui.sldrTime.setValue(game.timeWeight) self.update_sliders() self.msg("Settings file loaded successfully.") self.update_sets() except: self.msg("Settings could not be loaded.") # Installs the game with the current configuration to the Sifteos def install(self): # construct the game object QtGui.QMessageBox.information(self, "Starting Installation", "This will begin installing the game to the Sifteo cubes.\n\nYou will be notified when the installation is complete.") try: game = Game() game.levels = self.levels game.failedAttemptsWeight = self.ui.sldrFailedAttempts.value() game.hintsRequestedWeight = self.ui.sldrHintsRequested.value() game.timeWeight = self.ui.sldrTime.value() generate_files(game, '..\PhonemeFrenzy') compile_elf() install_elf() QtGui.QMessageBox.information(self, "Installation Complete", "The installation is complete.") except Exception as e: QtGui.QMessageBox.warning(self, "Installation Error", "An error occurred. The following exception was given:\n\n" + str(e)) # Allows the user to define a custom sound file def custom_sound(self): phoneme = self.get_phoneme() path = str(QtGui.QFileDialog.getOpenFileName()) if path != "": phoneme.sound_path = path phoneme.text = "custom" self.lblSoundPath.setText(basename(path)) # Updates the displayed values for the sliders. def update_sliders(self): self.ui.lblAttempts.setText(str(self.ui.sldrFailedAttempts.value()) + "%") self.ui.lblHints.setText(str(self.ui.sldrHintsRequested.value()) + "%") self.ui.lblTimeValue.setText(str(self.ui.sldrTime.value()) + "%") def show_images(self): self.ui.btnRemoveSet.setIcon(QtGui.QIcon("minus.png")) self.ui.btnAddSet.setIcon(QtGui.QIcon("plus.png")) self.ui.btnRemovePhoneme.setIcon(QtGui.QIcon("minus.png")) self.ui.btnAddPhoneme.setIcon(QtGui.QIcon("plus.png")) # Individual phoneme sound button functions def a(self): self.select_sound("a") def o(self): self.select_sound("o") def eu(self): self.select_sound("eu") def e_grave(self): self.select_sound("e_grave") def e_acute(self): self.select_sound("e_acute") def e(self): self.select_sound("e") def i(self): self.select_sound("i") def u(self): self.select_sound("u") def ou(self): self.select_sound("ou") def an(self): self.select_sound("an") def on(self): self.select_sound("on") def un(self): self.select_sound("un") def in2(self): self.select_sound("in") def ui2(self): self.select_sound("ui") def ill(self): self.select_sound("ill") def oi(self): self.select_sound("oi") def p(self): self.select_sound("p") def b(self): self.select_sound("b") def f(self): self.select_sound("f") def v(self): self.select_sound("v") def m(self): self.select_sound("m") def r(self): self.select_sound("r") def t(self): self.select_sound("t") def d(self): self.select_sound("d") def s(self): self.select_sound("s") def z(self): self.select_sound("z") def n(self): self.select_sound("n") def l(self): self.select_sound("l") def k(self): self.select_sound("k") def g(self): self.select_sound("g") def ch(self): self.select_sound("ch") def j(self): self.select_sound("j") def gn(self): self.select_sound("gn") # Selects a specific sound button def select_sound(self, s): self.deselect_all() if s == "a": self.ui.btnA.setChecked(True) elif s == "o": self.ui.btnO.setChecked(True) elif s == "eu": self.ui.btnEU.setChecked(True) elif s == "e_grave": self.ui.btnE_grave.setChecked(True) elif s == "e_acute": self.ui.btnE_acute.setChecked(True) elif s == "i": self.ui.btnI.setChecked(True) elif s == "u": self.ui.btnU.setChecked(True) elif s == "ou": self.ui.btnOU.setChecked(True) elif s == "an": self.ui.btnAN.setChecked(True) elif s == "on": self.ui.btnON.setChecked(True) elif s == "un": self.ui.btnUN.setChecked(True) elif s == "in": self.ui.btnIN.setChecked(True) elif s == "ui": self.ui.btnUI.setChecked(True) elif s == "ill" or s == "y": self.ui.btnILL.setChecked(True) elif s == "oi" or s == "w": self.ui.btnOI.setChecked(True) elif s == "p": self.ui.btnP.setChecked(True) elif s == "b": self.ui.btnB.setChecked(True) elif s == "f": self.ui.btnF.setChecked(True) elif s == "v": self.ui.btnV.setChecked(True) elif s == "m": self.ui.btnM.setChecked(True) elif s == "r": self.ui.btnR.setChecked(True) elif s == "t": self.ui.btnT.setChecked(True) elif s == "d": self.ui.btnD.setChecked(True) elif s == "s": self.ui.btnS.setChecked(True) elif s == "z": self.ui.btnZ.setChecked(True) elif s == "n": self.ui.btnN.setChecked(True) elif s == "l": self.ui.btnL.setChecked(True) elif s == "k": self.ui.btnK.setChecked(True) elif s == "g": self.ui.btnG.setChecked(True) elif s == "ch": self.ui.btnCH.setChecked(True) elif s == "j": self.ui.btnJ.setChecked(True) elif s == "gn": self.ui.btnGN.setChecked(True) # update current phoneme sound if s != "": phoneme = self.get_phoneme() phoneme.text = s self.update_sound_paths() self.ui.lblSoundPath.setText(basename(phoneme.sound_path)) sound = QtGui.QSound(phoneme.sound_path) sound.play() # Deselects all sound buttons in the phoneme sounds section def deselect_all(self): self.ui.btnA.setChecked(False) self.ui.btnO.setChecked(False) self.ui.btnEU.setChecked(False) self.ui.btnE_grave.setChecked(False) self.ui.btnE_acute.setChecked(False) self.ui.btnE.setChecked(False) self.ui.btnI.setChecked(False) self.ui.btnU.setChecked(False) self.ui.btnOU.setChecked(False) self.ui.btnAN.setChecked(False) self.ui.btnON.setChecked(False) self.ui.btnUN.setChecked(False) self.ui.btnIN.setChecked(False) self.ui.btnUI.setChecked(False) self.ui.btnILL.setChecked(False) self.ui.btnOI.setChecked(False) self.ui.btnP.setChecked(False) self.ui.btnB.setChecked(False) self.ui.btnF.setChecked(False) self.ui.btnV.setChecked(False) self.ui.btnM.setChecked(False) self.ui.btnR.setChecked(False) self.ui.btnT.setChecked(False) self.ui.btnD.setChecked(False) self.ui.btnS.setChecked(False) self.ui.btnZ.setChecked(False) self.ui.btnN.setChecked(False) self.ui.btnL.setChecked(False) self.ui.btnK.setChecked(False) self.ui.btnG.setChecked(False) self.ui.btnCH.setChecked(False) self.ui.btnJ.setChecked(False) self.ui.btnGN.setChecked(False)
def __init__(self): print "Arranca Domotics" #Configuramos el los pines GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(deviceConfig.pinResetButton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(deviceConfig.pinIRSensor, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.leds = Leds() #Cuando se encienda el dispositivo se encenderan todos los leds self.leds.setLedsOn() self.sounds = Sounds() #Configuracion del evento para el reset GPIO.add_event_detect(deviceConfig.pinResetButton, GPIO.FALLING, callback=self.buttonResetCallback, bouncetime=500) time.sleep(1) #Una vez pasa 1 segundo se mantiene encendida solo la luz de error hasta que consiga conectarse a internet y montar el servidor self.leds.setLedsError() print "Solicitamos codigo se seguridad" self.updateSecurityCode() print "¡¡¡Tenemos codigo!!!" self.updateVersionDevice(deviceConfig.deviceId) self.updateSoftware() self.port = int(self.getPort()) #obtenemos el puerto print self.port self.privateIp = self.getPrivateIp() #Obtenemos la ip privada print self.privateIp class RequestHandler(pyjsonrpc.HttpRequestHandler): # Register public JSON-RPC methods methods = { "switchGetValue": self.switchGetValue, "switchSetValue": self.switchSetValue, "sensorGetValues": self.sensorGetValues, "cameraGetPhoto": self.cameraGetPhoto, "cameraGetPhotoForMail": self.cameraGetPhotoForMail, "installRemoteDevice": self.installRemoteDevice, "setDeviceAlarmMode": self.setDeviceAlarmMode, "quitDeviceAlarmMode": self.quitDeviceAlarmMode } # Threading HTTP-Server http_server = pyjsonrpc.ThreadingHttpServer( server_address = (self.privateIp, self.port), RequestHandlerClass = RequestHandler ) print "Creado servidor" # Start the scheduler sched = Scheduler() sched.start() # Schedule sendStatus every 1 minutes sched.add_interval_job(self.sendStatus, minutes=1) # Schedule updateSecurityCode every 1 hours sched.add_interval_job(self.updateSecurityCode, hours=1) # Schedule updateSoftware every 24 hours sched.add_interval_job(self.updateSoftware, hours=24) #Obtenemos del servidor el tipo de dispositivo que es y inicializamos self.typeDevice = int(self.getTypeDevice()) print self.typeDevice #Remote Device if self.typeDevice == 0: self.NRF24 = Remote() sched.add_interval_job(self.newReadingSensors, hours=1) #Rele device elif self.typeDevice == 1: self.rele = Rele() #Camera device elif self.typeDevice == 2: self.camera = Camera() #Sensors device elif self.typeDevice == 4: self.sensors = Sensors() sched.add_interval_job(self.newReadingSensors, hours=1) print "Actualizamos estado dispositivo" ## Actualizamos el estado del dispositivo self.sendStatus() #Temporizador para guadar datos de sensores if self.typeDevice == 0 or self.typeDevice == 4: self.newReadingSensors() #Configuracion del evento para el detector de presencia GPIO.add_event_detect(deviceConfig.pinIRSensor, GPIO.RISING, callback=self.IRSensorDetectCallback, bouncetime=10000) print "Listo para arracar el servidor" self.sounds.start() #print myconfig.urlDb print "Starting HTTP server ..." print "URL: http://%s:%d" % (self.privateIp, self.port) try: http_server.serve_forever() except KeyboardInterrupt: http_server.shutdown() self.leds.setLedsError() except: self.leds.setLedsError() time.sleep(10) os.system('sudo reboot') print "Stopping HTTP server ..."
class Device: #Sensors sensors = 0 #Remote NRF24 = 0 #Remoto devicesRemote = [] #Dispositivos remotos #Rele rele = 0 #Rele camera = 0 #Status connectionStatus = 0 #0 offline, 1 online, 2 portNotOpen alarmMode = 0 #0 No, 1 Yes #Leds leds = 0 #Sounds sounds = 0 #Port and IPs port = 0 publicIp = 0 privateIp = 0 #Code security currentCode = str(randint(10000,99999999)) previousCode = currentCode numberOfPetitions = 0 #Type Device typeDevice = 0 ################################################################################################################################################# ################################################################################################################################################# ##################################################### SECTION DOMOTICS SERVER ######################################################### ################################################################################################################################################# ################################################################################################################################################# def __init__(self): print "Arranca Domotics" #Configuramos el los pines GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(deviceConfig.pinResetButton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(deviceConfig.pinIRSensor, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.leds = Leds() #Cuando se encienda el dispositivo se encenderan todos los leds self.leds.setLedsOn() self.sounds = Sounds() #Configuracion del evento para el reset GPIO.add_event_detect(deviceConfig.pinResetButton, GPIO.FALLING, callback=self.buttonResetCallback, bouncetime=500) time.sleep(1) #Una vez pasa 1 segundo se mantiene encendida solo la luz de error hasta que consiga conectarse a internet y montar el servidor self.leds.setLedsError() print "Solicitamos codigo se seguridad" self.updateSecurityCode() print "¡¡¡Tenemos codigo!!!" self.updateVersionDevice(deviceConfig.deviceId) self.updateSoftware() self.port = int(self.getPort()) #obtenemos el puerto print self.port self.privateIp = self.getPrivateIp() #Obtenemos la ip privada print self.privateIp class RequestHandler(pyjsonrpc.HttpRequestHandler): # Register public JSON-RPC methods methods = { "switchGetValue": self.switchGetValue, "switchSetValue": self.switchSetValue, "sensorGetValues": self.sensorGetValues, "cameraGetPhoto": self.cameraGetPhoto, "cameraGetPhotoForMail": self.cameraGetPhotoForMail, "installRemoteDevice": self.installRemoteDevice, "setDeviceAlarmMode": self.setDeviceAlarmMode, "quitDeviceAlarmMode": self.quitDeviceAlarmMode } # Threading HTTP-Server http_server = pyjsonrpc.ThreadingHttpServer( server_address = (self.privateIp, self.port), RequestHandlerClass = RequestHandler ) print "Creado servidor" # Start the scheduler sched = Scheduler() sched.start() # Schedule sendStatus every 1 minutes sched.add_interval_job(self.sendStatus, minutes=1) # Schedule updateSecurityCode every 1 hours sched.add_interval_job(self.updateSecurityCode, hours=1) # Schedule updateSoftware every 24 hours sched.add_interval_job(self.updateSoftware, hours=24) #Obtenemos del servidor el tipo de dispositivo que es y inicializamos self.typeDevice = int(self.getTypeDevice()) print self.typeDevice #Remote Device if self.typeDevice == 0: self.NRF24 = Remote() sched.add_interval_job(self.newReadingSensors, hours=1) #Rele device elif self.typeDevice == 1: self.rele = Rele() #Camera device elif self.typeDevice == 2: self.camera = Camera() #Sensors device elif self.typeDevice == 4: self.sensors = Sensors() sched.add_interval_job(self.newReadingSensors, hours=1) print "Actualizamos estado dispositivo" ## Actualizamos el estado del dispositivo self.sendStatus() #Temporizador para guadar datos de sensores if self.typeDevice == 0 or self.typeDevice == 4: self.newReadingSensors() #Configuracion del evento para el detector de presencia GPIO.add_event_detect(deviceConfig.pinIRSensor, GPIO.RISING, callback=self.IRSensorDetectCallback, bouncetime=10000) print "Listo para arracar el servidor" self.sounds.start() #print myconfig.urlDb print "Starting HTTP server ..." print "URL: http://%s:%d" % (self.privateIp, self.port) try: http_server.serve_forever() except KeyboardInterrupt: http_server.shutdown() self.leds.setLedsError() except: self.leds.setLedsError() time.sleep(10) os.system('sudo reboot') print "Stopping HTTP server ..." ################################################################################################################################################# ################################################################################################################################################# ##################################################### SECTION INSTALL DEVICE ######################################################### ################################################################################################################################################# ################################################################################################################################################# def buttonResetCallback(self, channel): print "Reset" time.sleep(1) if GPIO.input(channel) == GPIO.LOW: buttonAlwaysPressed = 1 for i in range(10): if GPIO.input(channel) == GPIO.LOW: self.leds.setLedsOn() time.sleep(0.2) self.sounds.on() time.sleep(0.1) self.sounds.off() time.sleep(0.2) self.leds.setLedsOff() time.sleep(0.5) else: buttonAlwaysPressed = 0 if GPIO.input(channel) == GPIO.LOW and buttonAlwaysPressed == 1: self.leds.setLedsAdhoc() os.system('sudo cp /home/pi/Domotics/Default/bootInstall.py /home/pi/Domotics/bootConfig.py') os.system('sudo cp /home/pi/Domotics/Default/network/adhoc/dhcpd.conf /etc/dhcp/dhcpd.conf') os.system('sudo cp /home/pi/Domotics/Default/network/adhoc/wpa_supplicant.conf /etc/wpa_supplicant/wpa_supplicant.conf') #Eliminamos fichero de configuracion os.system('sudo rm /etc/network/interfaces') nameWIFI = "Domotics%d" % (randint(1000,9999)) #Creamos el fichero de configuración en base a la plantilla y rellenamos el nombre de la red adhoc with open("/etc/network/interfaces", "wt") as fout: with open("/home/pi/Domotics/Default/network/adhoc/interfaces", "rt") as fin: for line in fin: fout.write(line.replace('<NAME>', nameWIFI)) self.sounds.reset() time.sleep(2) os.system('sudo reboot') else: self.leds.updateLeds(self.connectionStatus, self.alarmMode) def installRemoteDevice(self, idDevice, pipeSend, pipeRecv, code): if (self.currentCode == code or self.previousCode == code) and self.numberOfPetitions < deviceConfig.maxNumberOfPetitions: #Eliminamos el software anterior os.system('sudo rm /home/pi/Domotics/Arduino/src/domotics.ino') #Configuramos el nuevo software con el valor del pipeSend y el pipeRecv with open("/home/pi/Domotics/Arduino/src/domotics.ino", "wt") as fout: with open("/home/pi/Domotics/Default/domoticsAux.ino", "rt") as fin: for line in fin: fout.write(line.replace('<PIPE_SEND>', pipeSend).replace('<PIPE_RECV>', pipeRecv)) #Cambiamos la ruta en la que esta el Software Arduino os.chdir('/home/pi/Domotics/Arduino') #Limpiamos el proyecto #os.system('sudo ino clean') #Compilamos os.system('sudo ino build -m leonardo') #Subimos el binario al ardino os.system('sudo ino upload -m leonardo') self.updateVersionDevice(idDevice) self.sendStatus() return 1 else: self.numberOfPetitions += 1 return -1 ################################################################################################################################################# ################################################################################################################################################# ##################################################### SECTION SECURITY CODE ######################################################### ################################################################################################################################################# ################################################################################################################################################# def updateSecurityCode(self): self.previousCode = self.currentCode self.currentCode = str(randint(10000,99999999)) rpc_client = pyjsonrpc.HttpClient(url = deviceConfig.url) result = rpc_client("updateSecurityCode", deviceConfig.deviceId, self.currentCode, self.previousCode) while result == 0: time.sleep(5) result = rpc_client("updateSecurityCode", deviceConfig.deviceId, self.currentCode, self.previousCode) print "Intentamos enviar el codigo de seguridad" return result ################################################################################################################################################# ################################################################################################################################################# ################################################ SECTION GET DEVICE IP & PORT ####################################################### ################################################################################################################################################# ################################################################################################################################################# # private IP def getPrivateIp(self): success = False privateIp = 0 while success == False: try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.connect_ex(('<broadcast>', 0)) privateIp = s.getsockname()[0] success = True except: success = False self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) return privateIp # public IP def getPublicIp(self): success = False publicIp = 0 while success == False: try: publicIp = json.load(urllib2.urlopen('http://httpbin.org/ip'))['origin'] success = True except: self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) try: publicIp = json.load(urllib2.urlopen('http://jsonip.com'))['ip'] success = True except: self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) try: publicIp = json.load(urllib2.urlopen('https://api.ipify.org/?format=json'))['ip'] success = True except: success = False self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) return publicIp # Port def getPort(self): success = False port = 0 while success == False: try: rpc_client = pyjsonrpc.HttpClient(url = deviceConfig.url) port = rpc_client("getPort", deviceConfig.deviceId, self.currentCode)['port'] success = True except: success = False self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) return port def checkPortConnection(self, port, publicIp): # Setup socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) connectionStatus = 2 try: sock.connect((publicIp, port)) except Exception,e: rpc_client = pyjsonrpc.HttpClient(url = deviceConfig.url) result = rpc_client("checkPort", publicIp, port) if result: #print "Port is open" connectionStatus = 1 else: #print "Port is not open" connectionStatus = 2 else:
def modify_sounds(self): # load up sounds UI self.Sounds = Sounds(self) self.Sounds.show()
class Game(object): TITLE = "Gold Rush!" WIDTH=680 HEIGHT=600 WAITING = 1 PLAYING = 2 FRAMES_PER_SECOND = 30 board=[] def __init__(self): pygame.mixer.pre_init(44100,-16,2,2048) pygame.init() self.sounds=Sounds() self.input_handler = InputHandler() self.game_screen = GameScreen(self.TITLE,self.WIDTH,self.HEIGHT) self.miner=Miner(8,0) self.explosion=Explosion(-1,-1) self.game_screen.add_sprite(self.miner) self.game_screen.add_sprite(self.explosion) self.health = 100 self.clock=pygame.time.Clock() self.state=self.WAITING self.game_screen.display_opening() def setup(self): self.gold=0 self.charges=10 self.cash=0 self.health=100 self.board=[] # top row of empty spaces self.board.append([' ']*20) self.board.append(['*']*20) for y in range(2,14): row=[] for x in range(20): c='*' if y>1 and random()<0.4: c=' ' if random()<0.5: c='0' else: c='1' row.append(c) self.board.append(row) self.miner.set_location(8,0) self.game_screen.setup() self.game_screen.set_board(self.board) self.game_screen.draw_board() def mainloop(self): deltat=self.clock.tick(self.FRAMES_PER_SECOND) running=True while running: self.input_handler.check() if self.input_handler.exit_action: running=False elif self.state == self.WAITING: if self.input_handler.key_press: self.setup() self.state=self.PLAYING else: self.game_screen.clear_sprites() if self.miner.can_move(): kpress=self.input_handler.arrow_press if kpress: dx=0 dy=0 if kpress == K_RIGHT: dx=1 elif kpress == K_LEFT: dx=-1 elif kpress == K_UP: dy=-1 elif kpress == K_DOWN: dy=1 if self.input_handler.space_press and (dx!=0 or dy!=0): self.do_explosion(dx,dy) tx=self.miner.x + dx ty=self.miner.y + dy if (dx!=0 or dy!=0) and (tx>=0 and tx<=19 and ty>=0 and ty<=13): o=self.board[ty][tx] if o in ' 01': self.miner.set_location(tx,ty) if o in '01': self.take_nugget(tx,ty) elif (dy==-1 and tx==17 and ty==-1 and self.gold!=0): self.cash_out() if self.charges==0: self.state=self.WAITING self.input_handler.reset() self.game_screen.display_gameover() if self.miner.y>0: self.health-=1 if self.health<0: self.health=0 self.game_screen.display_health(self.health) else: self.health+=1 if self.health>100: self.health=100 self.game_screen.display_health(self.health) self.game_screen.draw(deltat) pygame.quit() def do_explosion(self,dx,dy): bx=self.miner.x + dx by=self.miner.y + dy if bx>=0 and bx<20 and (by>0 or (by==0 and dy==1)) and by<14 and self.charges>0: self.explosion.explode(bx,by) self.charges-=1 self.board[by][bx]=' ' self.miner.add_delay(20) self.game_screen.clear_square(bx,by) self.game_screen.display_charges() self.sounds.play_boom() self.game_screen.display_charges(self.charges) for j in range(20): x=randint(0,19) y=randint(2,11) o=self.board[y][x] a=self.board[y-1][x] if o==' ' and a=='*': self.board[y][x]='*' self.game_screen.reset_square(x,y) def cash_out(self): self.cash+=self.gold*self.charges self.gold=0 self.sounds.play_kaching() self.game_screen.display_gold(self.gold) self.game_screen.display_cash(self.cash) self.sounds.play_yeehaw() def take_nugget(self,tx,ty): self.board[ty][tx]=' ' self.gold += 1 self.sounds.play_bell() self.game_screen.clear_square(tx,ty) self.game_screen.display_gold(self.gold)
def start_game(): #needs to be called before pygame.init pygame.mixer.pre_init(22050, -16, 2, 1024) window = Window() window.init() pygame.init() sounds = Sounds() sounds.init() window.sounds = sounds pygame.mixer.set_num_channels(32) # meta game loop while True: sounds.play_music("intro", loop=1) intro_main(window, handle_events) # so we can mix more channels at once. pygame defaults to 8. #sounds.play("jump1") #sounds.play("hit1") #sounds.play("goal1") sounds.set_music_tracks(['track-one', 'track-two']) world = World() world.stage = 2 populate(world, window) def count_leaves(): no_leaves = 0 for item in world.items: if item.role == "Bough": no_leaves = no_leaves + 1 return no_leaves CleanUp_Event = pygame.event.Event(CLEANUP, message="Cleaning Up Your shit") pygame.time.set_timer(CLEANUP, 1000) TickTock = pygame.event.Event(TICK_TOCK, message="TickTock goes the Ticking Clock") pygame.time.set_timer(TICK_TOCK, int(90000/count_leaves())) AddCherry = pygame.event.Event(ADDCHERRY, message="Ooooo Cherry") pygame.time.set_timer(ADDCHERRY, int(90000/5)) AddOwange = pygame.event.Event(ADDOWANGE, message="Ooooo owange") pygame.time.set_timer(ADDOWANGE, int(1000 * 5)) for i in range(3): event.post(AddOwange) pygame.time.set_timer(BIRDY, 1000 * 7) render = Render(window, world) quit = runloop(window, world, render) if quit: return