def game_loop(): """Ciclo de juego. Mientras no se cierre la ventana, el juego no termina.""" pantalla = set_mode((ANCHO, ALTO)) set_caption("Pong <3") fondo = cargar_imagen('images/fondo_pong.png') bola = Bola() pala = Pala(30, imagen="images/amlo.jpg") pala_cpu = Pala(ANCHO - 30, 0.3, "images/trump.jpg") clock = Clock() puntos = [0, 0] sonido = Sound('audios/Tetris.ogg') sonido.play() while puntos[0] < 30 and puntos[1] < 30: time = clock.tick(60) keys = get_pressed() for eventos in get(): if eventos.type == QUIT: sys.exit(0) bola.actualizar(time, pala, pala_cpu, puntos) pala.mover(time, keys) pala_cpu.ia(time, bola) puntos_jug, puntos_jug_rect = texto( "Jugador Puntos: " + str(puntos[0]), 140, 40) puntos_cpu, puntos_cpu_rect = texto( "Maquina Puntos: " + str(puntos[1]), ANCHO - ANCHO / 4, 40) pantalla.blit(fondo, (0, 0)) pantalla.blit(bola.image, bola.rect) pantalla.blit(pala.image, pala.rect) pantalla.blit(pala_cpu.image, pala_cpu.rect) pantalla.blit(puntos_jug, puntos_jug_rect) pantalla.blit(puntos_cpu, puntos_cpu_rect) flip() return 0
class SoundDecorator(FrameDecorator): def __init__(self, parent_component=NullComponent(), sound_file_path=''): self.sound_file_path = sound_file_path self.parent = parent_component self.sound = Sound(sound_file_path) self.start_time = 0 def get_parent(self): return self.parent def set_parent(self, new_parent): self.parent = new_parent def get_landmarks(self): self.parent.get_landmarks() def get_image(self): self.play() return self.parent.get_image() def play(self): if not self.is_playing(): self.start_time = time() self.sound.play() def is_playing(self): now = time() return self.sound.get_length() > now - self.start_time def stop(self): self.sound.stop() self.start_time = 0 def copy(self): return SoundDecorator(parent_component=self.parent.copy(), sound_file_path=self.sound_file_path)
class Player(Spaceship, EventHandler): def __init__(self): super().__init__(image_path='assets/spaceship_1_normal.png') self.rocket_sound = Sound('assets/rocket.wav') self.shoot_sound = Sound('assets/player_shoot.wav') def handle(self, event: pygame.event.Event): if event.type == locals.KEYDOWN: if event.key == locals.K_RIGHT: self.move_x = self.MOVE_STEP elif event.key == locals.K_LEFT: self.move_x = -self.MOVE_STEP elif event.key == locals.K_UP: self.move_y = -self.MOVE_Y_STEP self.load_image('assets/spaceship_1_rocket.png') self.rocket_sound.play(-1) elif event.key == locals.K_DOWN: self.move_y = self.MOVE_STEP if event.type == locals.KEYUP: if event.key in (locals.K_LEFT, locals.K_RIGHT): self.move_x = 0 elif event.key == locals.K_SPACE: self.shoot() self.shoot_sound.play() elif event.key in (locals.K_UP, locals.K_DOWN): self.move_y = 0 self.load_image('assets/spaceship_1_normal.png') self.rocket_sound.stop()
class AbstractButton(ABC): def __init__(self, action, app): self._action = action self._app = app self._dark_mode_on = app.settings[Settings.COLOR] == ColorMode.DARK self._base_color = (70, 70, 70) if self._dark_mode_on else (190, 190, 190) self._hovered_color = (60, 60, 60) if self._dark_mode_on else (170, 170, 170) self._pressed_color = (50, 50, 50) if self._dark_mode_on else (155, 155, 155) self._click_sound = Sound(os.path.join( ABS_PROJECT_ROOT_PATH, "game_app/resources/sounds/common/button_click_sound.wav")) @abstractmethod def contains_point(self, point): pass @abstractmethod def render(self, screen, mouse_position, is_mouse_pressed): pass def _get_color(self, mouse_position, is_mouse_pressed): if not self.contains_point(mouse_position): return self._base_color return self._pressed_color if is_mouse_pressed else self._hovered_color def on_pressed(self): if self._app.settings[Settings.SOUNDS]: self._click_sound.play() self._action()
class ScreenAuthorize(LcarsScreen): def setup(self, all_sprites): all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_2.png"), layer=0) all_sprites.add(LcarsText(colours.ORANGE, (270, -1), "AUTHORIZATION REQUIRED", 2), layer=1) all_sprites.add(LcarsText( colours.BLUE, (330, -1), "ONLY AUTHORIZED PERSONNEL MAY ACCESS THIS TERMINAL", 1.5), layer=1) all_sprites.add(LcarsText(colours.BLUE, (360, -1), "TOUCH TERMINAL TO PROCEED", 1.5), layer=1) all_sprites.add(LcarsText(colours.BLUE, (390, -1), "FAILED ATTEMPTS WILL BE REPORTED", 1.5), layer=1) all_sprites.add(LcarsGifImage("assets/gadgets/stlogorotating.gif", (103, 369), 50), layer=1) # sounds Sound("assets/audio/panel/215.wav").play() Sound("assets/audio/enter_authorization_code.wav").play() self.sound_granted = Sound("assets/audio/accessing.wav") self.sound_beep1 = Sound("assets/audio/panel/206.wav") self.sound_denied = Sound("assets/audio/access_denied.wav") self.sound_deny1 = Sound("assets/audio/deny_1.wav") self.sound_deny2 = Sound("assets/audio/deny_2.wav") self.attempts = 0 self.granted = False def handleEvents(self, event, fpsClock): LcarsScreen.handleEvents(self, event, fpsClock) if event.type == pygame.MOUSEBUTTONDOWN: if (self.attempts > 1): self.granted = True self.sound_beep1.play() else: if self.attempts == 0: self.sound_deny1.play() else: self.sound_deny2.play() self.granted = False self.attempts += 1 if event.type == pygame.MOUSEBUTTONUP: if (self.granted): self.sound_granted.play() from screens.main import ScreenMain self.loadScreen(ScreenMain()) else: self.sound_denied.play() return False
class Player(Sprite): def __init__(self, position = [0,0], score = 0, lifes = 100): Sprite.__init__(self) self.position = position self.image = pygame.image.load("assets/images/player.png").convert() self.image.set_colorkey((0, 0, 0)) self.rect = self.image.get_rect(topleft = self.position) self.score = score self.lifes = lifes self.missile = None self.hit_sound = Sound("assets/sound/187535-crash.ogg") def update(self): self.rect.x, self.rect.y = self.position if self.missile != None: self.missile.update() def shot(self, screen): self.missile = Missile(self.position) self.missile.emit_shot_sound() return self.missile def hit(self): self.hit_sound.play() return PlayerHitAnimation(self)
class DisableableRectangularTextButton(RectangularTextButton): def __init__(self, enabled_text, disabled_text, action, app, position, size, disabled): super().__init__(enabled_text, action, app, position, size) self._disabled = disabled self._disabled_color = (45, 45, 45) if self._dark_mode_on else (230, 230, 230) self._enabled_text = enabled_text self._disabled_text = disabled_text self._disabled_click_sound = Sound(os.path.join( ABS_PROJECT_ROOT_PATH, "game_app/resources/sounds/common/disabled_button_sound.wav")) def _get_color(self, mouse_position, is_mouse_pressed): if self._disabled: return self._disabled_color return super()._get_color(mouse_position, is_mouse_pressed) def set_disabled(self, new_disabled): self._disabled = new_disabled self.set_text(self._disabled_text if new_disabled else self._enabled_text) def on_pressed(self): if self._disabled: if self._app.settings[Settings.SOUNDS]: self._disabled_click_sound.play() else: super().on_pressed()
class Ball: def __init__(self, pos = Vector2(0, 0)): mixer.init() self.pos = pos self.dir = Vector2(1, 1) self.speed = 0.2 self.size = 5 self.effect = Sound("assets/sounds/pong.wav") def init(self, screen: Surface): self.screen = screen self.pos = Vector2(screen.get_width() / 2, screen.get_height() / 2) def update(self): max_height = self.screen.get_height() - self.size max_width = self.screen.get_width() - self.size min_height = min_width = self.size if self.pos.y >= max_height or self.pos.y <= min_height: self.dir.y = -self.dir.y self.effect.play() if self.pos.x >= max_width or self.pos.x <= min_width: self.pos = Vector2(self.screen.get_width() / 2, self.screen.get_height() / 2) rand_dir_x = 1 if randint(0, 1) == 1 else -1 rand_dir_y = 1 if randint(0, 1) == 1 else -1 self.dir = Vector2(rand_dir_x, rand_dir_y) self.pos += self.dir * self.speed draw.circle(self.screen, (255, 255, 255), self.pos, self.size) def get_collision_square(self): return Rect(self.pos.x - self.size, self.pos.y - self.size, self.size * 2, self.size * 2);
def devil(self): self.lightning.set_A(ON) self.lightning.set_C(ON) self.lightning.send() poodle = Sound("%s/poodle.wav" % (self._data_folder)) poodle.play() time.sleep(0.3) self.lightning.set_A(OFF) self.lightning.send() time.sleep(0.7) for i in range(10): wait = random.randint(0, 3) while self._last == wait: wait = random.randint(0, 3) print "devil intensity:", wait self._last = wait thunder = Sound("%s/thunder_0%d.wav" % (self._data_folder, wait)) thunder.play() if wait < 2: off_for = 0.05 + random.random() * 0.3 print "flicker for", off_for self.lightning.set_B(OFF) self.lightning.send() time.sleep(off_for) self.lightning.set_B(ON) self.lightning.send() time.sleep(2) self.lightning.set_C(OFF) self.lightning.send() time.sleep(1) self.lightning.set_B(ON) self.lightning.send()
class LcarsButton(LcarsWidget): def __init__(self, colour, pos, text, handler=None): self.handler = handler image = pygame.image.load("assets/button.png").convert() size = (image.get_rect().width, image.get_rect().height) font = Font("assets/swiss911.ttf", 19) textImage = font.render(text, False, colours.BLACK) image.blit(textImage, (image.get_rect().width - textImage.get_rect().width - 10, image.get_rect().height - textImage.get_rect().height - 5)) self.image = image self.colour = colour LcarsWidget.__init__(self, colour, pos, size) self.applyColour(colour) self.highlighted = False self.beep = Sound("assets/audio/panel/202.wav") def handleEvent(self, event, clock): handled = False if (event.type == MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos)): self.applyColour(colours.WHITE) self.highlighted = True self.beep.play() handled = True if (event.type == MOUSEBUTTONUP and self.highlighted): self.applyColour(self.colour) if self.handler: self.handler(self, event, clock) handled = True LcarsWidget.handleEvent(self, event, clock) return handled
def thunder(self, inc): wait = random.randint(0, 2+inc) while (self._last == wait): wait = random.randint(0, 2+inc) self._last = wait print "intensity:", wait thunder = Sound("%s/thunder_0%d.wav" % (self._data_folder, wait)) if wait < 6: self.lightning.set_C(ON) self.lightning.send() time.sleep(random.uniform(0.5, 1.5)) self.lightning.set_C(OFF) self.lightning.send() time.sleep(wait) if wait < 6: self.lightning.set_B(OFF) self.lightning.send() thunder.play() if wait < 6: time.sleep(0.3) self.lightning.set_B(ON) self.lightning.send() time.sleep(thunder.get_length()-0.3) thunder.fadeout(200) time.sleep(wait)
class LcarsButton(LcarsWidget): """Button - either rounded or rectangular if rectSize is spcified""" def __init__(self, colour, pos, text, handler=None, rectSize=None): if rectSize == None: image = pygame.image.load("assets/button.png").convert() size = (image.get_rect().width, image.get_rect().height) else: size = rectSize image = pygame.Surface(rectSize).convert() image.fill(colour) self.colour = colour self.image = image font = Font("assets/swiss911.ttf", 19) textImage = font.render(text, False, colours.BLACK) image.blit(textImage, (image.get_rect().width - textImage.get_rect().width - 10, image.get_rect().height - textImage.get_rect().height - 5)) LcarsWidget.__init__(self, colour, pos, size, handler) self.applyColour(colour) self.highlighted = False self.beep = Sound("assets/audio/panel/202.wav") def handleEvent(self, event, clock): if (event.type == MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos)): self.applyColour(colours.WHITE) self.highlighted = True self.beep.play() if (event.type == MOUSEBUTTONUP and self.highlighted): self.applyColour(self.colour) return LcarsWidget.handleEvent(self, event, clock)
class Score(object): def __init__(self, font_path): self.collect = Sound(COLLECT_BACKSOUND) self.font = Font(font_path, 24) self.score = 0 self.old_score = self.score def add_score(self): self.score += 1 new_score = self.old_score + 10 if self.score == new_score: self.collect.play() self.old_score = self.score def rescore(self): self.score -= 1 def check(self): if self.score < 0: return True else: return False def draw(self, screen): text_surface, rect = self.font.render("Score: " + str(self.score), (133, 230, 159)) screen.blit(text_surface, (10, 10))
def update(self): globvars.viewport.center.x = globvars.player.position.x globvars.viewport.center.y = globvars.player.position.y # Nearby dock contact detection: self.nearby_dock = None for dock in globvars.docks: if dock.position.distance(globvars.player.position) < 20: self.nearby_dock = dock break # Nearby shipyard contact detection: self.nearby_shipyard = None if globvars.shipyard.position.distance(globvars.player.position) < 20: self.nearby_shipyard = globvars.shipyard # Asteroid collision detection: for asteroid in globvars.asteroids: if asteroid.position.distance(globvars.player.position) < 50: collision_sound = Sound("assets/sounds/collision.ogg") collision_sound.play() globvars.player.setSpeed(2) if self.tab_pressed: globvars.cargo_panel.update() self.fly_hud.update()
def sounds(): templateData = { 'samplesSorted': sorted(scan('static'), key=str), 'samplesSortedKeys': sorted(scan('static').values(), key=str), 'lenSamples': len(sorted(scan('static'), key=str)), 'samples': scan('static'), 'wifi': quality()[0], 'last': '', 'lastlang': '' } if request.method == 'POST': if (request.form.get('play')): pygame.mixer.quit() file = request.form.get('play') fileWave = wave.open(file) fileFreq = int(fileWave.getframerate()) fileWave.close() pygame.mixer.init(fileFreq, -16, 1, 4096) sample = Sound(bytes(file, encoding='utf-8')) lastSample = sample sample.play() elif (request.form.get('say')): pygame.mixer.quit() templateData['last'] = request.form.get('say') tts = gTTS(text=templateData['last'], lang=request.form['lang'], slow=False) tts.save("say.mp3") file = './say.mp3' pygame.mixer.init(27000, -16, 1, 4096) pygame.mixer.music.load(file) pygame.mixer.music.play() elif (request.form.get('resay')): pygame.mixer.quit() templateData['last'] = request.form.get('resay') print(request.form.get('resay')) tts = gTTS(text=templateData['last'], lang=request.form['lang'], slow=False) tts.save("say.mp3") file = './say.mp3' pygame.mixer.init(27000, -16, 1, 4096) pygame.mixer.music.load(file) pygame.mixer.music.play() return render_template('list_sounds.html', **templateData)
def tiro(self, nave): pygame.mixer.init(44100, -16, 2, 2048) audio = Sound('shoot.wav') audio.play() tiro = circ() tiro.pos = [nave.cubes[3].x, nave.cubes[3].y + 1.5, 0] return tiro
def play_sfx(self, name, preload_if_not=True): if name not in self.audio_sources: raise "Attempted to play unregistered audio source" preloaded, path, sound_obj = self.audio_sources[name] if not preloaded and preload_if_not: # preload logic sound_obj = Sound(path) self.audio_sources[name] = [True, path, sound_obj] sound_obj.set_volume(self.master_volume * self.sfx_volume) # set volume before playing sound_obj.play()
class ScreenAuthorize(LcarsScreen): def setup(self, all_sprites): all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_2.png"), layer=0) all_sprites.add(LcarsText(colours.ORANGE, (270, -1), "AUTHORIZATION REQUIRED", 2), layer=1) all_sprites.add(LcarsText(colours.BLUE, (330, -1), "ONLY AUTHORIZED PERSONNEL MAY ACCESS THIS TERMINAL", 1.5), layer=1) all_sprites.add(LcarsText(colours.BLUE, (360, -1), "TOUCH TERMINAL TO PROCEED", 1.5), layer=1) all_sprites.add(LcarsText(colours.BLUE, (390, -1), "FAILED ATTEMPTS WILL BE REPORTED", 1.5), layer=1) all_sprites.add(LcarsGifImage("assets/gadgets/stlogorotating.gif", (103, 369), 50), layer=1) # sounds Sound("assets/audio/panel/215.wav").play() Sound("assets/audio/enter_authorization_code.wav").play() self.sound_granted = Sound("assets/audio/accessing.wav") self.sound_beep1 = Sound("assets/audio/panel/206.wav") self.sound_denied = Sound("assets/audio/access_denied.wav") self.sound_deny1 = Sound("assets/audio/deny_1.wav") self.sound_deny2 = Sound("assets/audio/deny_2.wav") self.attempts = 0 self.granted = False def handleEvents(self, event, fpsClock): LcarsScreen.handleEvents(self, event, fpsClock) if event.type == pygame.MOUSEBUTTONDOWN: if (self.attempts > 1): self.granted = True self.sound_beep1.play() else: if self.attempts == 0: self.sound_deny1.play() else: self.sound_deny2.play() self.granted = False self.attempts += 1 if event.type == pygame.MOUSEBUTTONUP: if (self.granted): self.sound_granted.play() from screens.main import ScreenMain self.loadScreen(ScreenMain()) else: self.sound_denied.play() return False
def play_wav(name, *args): """This is a convenience method to play a wav. *args These are passed to play. Return the sound object. """ s = Sound(filepath(name)) s.play(*args) return s
class LcarsButton(LcarsWidget): def __init__(self, colour, shape, pos, text, handler=None): self.handler = handler # Load different image for shape if (shape == "nav"): image = pygame.image.load("assets/nav.png").convert() elif (shape == "btn"): image = pygame.image.load("assets/button.png").convert() size = (image.get_rect().width, image.get_rect().height) font = Font("assets/swiss911.ttf", 22) textImage = font.render(text, False, colours.BLACK) # Change text position if (shape == "nav"): image.blit( textImage, (image.get_rect().width - textImage.get_rect().width - 12, image.get_rect().height - textImage.get_rect().height)) elif (shape == "btn"): image.blit( textImage, (image.get_rect().width - textImage.get_rect().width - 10, image.get_rect().height - textImage.get_rect().height - 5)) self.image = image self.colour = colour LcarsWidget.__init__(self, colour, pos, size) self.applyColour(colour) self.highlighted = False self.beep = Sound("assets/audio/panel/202.wav") def handleEvent(self, event, clock): handled = False if (event.type == MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos)): self.applyColour(colours.WHITE) self.highlighted = True self.beep.play() handled = True if (event.type == MOUSEBUTTONUP and self.highlighted): self.applyColour(self.colour) if self.handler: self.handler(self, event, clock) handled = True LcarsWidget.handleEvent(self, event, clock) return handled
def update(self, clock): if self.message != None: delta_time_ms = clock.get_time() self.time += delta_time_ms if self.time > self.duration: self.message = None elif not self.queue.empty(): message = self.queue.get() self.message = message self.setText(message) beep = Sound("assets/sounds/beep.ogg") beep.play() self.time = 0 else: self.setText("")
class Bass: __author__ = 'James Dewes' def __init__(self): try: import pygame.mixer from pygame.mixer import Sound except RuntimeError: print("Unable to import pygame mixer sound") raise Exception("Unable to import pygame mixer sound") self.soundfile = "launch_bass_boost_long.wav" self.mixer = pygame.mixer.init() #instance of pygame self.bass = Sound(self.soundfile) def start(self): state = self.bass.play() while state.get_busy() == True: continue def stop(self): try: Pass except Exception: raise Exception("unable to stop")
class PauseState(GameState): CONTINUE_OPTION = 0 RESTART_OPTION = 1 EXIT_OPTION = 2 def __init__(self, game, restart_state): super(PauseState, self).__init__(game) self.listen_keys = (pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN, pygame.K_RETURN) self.restart_state = restart_state self.options = VerticalMenuOptions( ['Continue', 'Restart', 'Exit'], self.on_click, self.on_change, ) self.select_sound = None def show(self): # Initialize options font = resources.get_font('prstartcustom.otf') self.options.init(font, 15, True, MORE_WHITE) # Initialize sounds self.select_sound = Sound(resources.get_sound('menu_select.wav')) def update(self, delta): self.options.update(self.input) def render(self, canvas): canvas.fill(NOT_SO_BLACK) self.options.render(canvas, GAME_WIDTH / 2, GAME_HEIGHT / 2 - self.options.get_height() / 2) def on_click(self, option): self.select_sound.play() if option == PauseState.CONTINUE_OPTION: self.state_manager.pop_overlay() elif option == PauseState.RESTART_OPTION: self.state_manager.set_state(self.restart_state) elif option == PauseState.EXIT_OPTION: self.state_manager.set_state(MenuState(self.game)) def on_change(self, old_option, new_option): self.select_sound.play() def dispose(self): pass
def colisao(nave, listTiros, listEnemys): for e in listEnemys: for t in listTiros: if (t.pos[0] >= e.leaft - 0.3 and t.pos[0] <= e.rigth + 0.3 and t.pos[1] + t.tam >= e.face - 0.3): pygame.mixer.init(44100, -16, 2, 2048) audio2 = Sound('invaderkilled.wav') audio2.play() return [e, t] for c in nave.cubes: if (c.x - 0.5 > e.leaft - 0.3 and c.x + 0.5 < e.rigth + 0.3 and c.y + 0.5 >= e.face): return "Game Over" return -1
class Bola(Sprite): """ Clase Bola: hereda atributos directamente de la clase Sprite, que se encuentra en el modulo pygame.sprite. Permite modelar la pelota con la que se interactua en el juego. """ def __init__(self): """ Constructor que inicializa los siguientes valores: - La imagen a desplegar. - Posición, la cual es representada a través de un rectangulo invisible. - Velocidad por defecto de la pelota en el eje Y y Y """ Sprite.__init__(self) self.image = cargar_imagen("images/ball.png", True) self.rect = self.image.get_rect() self.rect.centerx = ANCHO / 2 self.rect.centery = ALTO / 2 self.sound = Sound('audios/rebote.wav') self.speed = [0.4, 0.4] def actualizar(self, time, pala, pala_cpu, puntos): """ Actualiza la posición de la pelota en tantos pixeles determinado por TIME. Además permite identificar si interactua con PALA y PALA_CPU. En caso de que existan puntos, actualiza los valores de PUNTOS. """ self.rect.centerx += self.speed[0] * time self.rect.centery += self.speed[1] * time if self.rect.left <= 0: puntos[1] += 1 if self.rect.right >= ANCHO: puntos[0] += 1 if self.rect.left <= 0 or self.rect.right >= ANCHO: self.speed[0] = -self.speed[0] self.rect.centerx += self.speed[0] * time if self.rect.top <= 0 or self.rect.bottom >= ALTO: self.speed[1] = -self.speed[1] self.rect.centery += self.speed[1] * time if self.rect.left == 0 or self.rect.right == ANCHO: self.sound.play() if self.rect.top == 0 or self.rect.bottom == ALTO: self.sound.play() if collide_rect(self, pala): self.speed[0] = -self.speed[0] self.rect.centerx += self.speed[0] * time self.sound.play() if collide_rect(self, pala_cpu): self.speed[0] = -self.speed[0] self.rect.centerx += self.speed[0] * time self.sound.play() return puntos
class Note: """Represents a musical note.""" # Defining a note # Default value (if not provided) for duration is a QUARTER_NOTE def __init__(self, note: str, instrument: str, duration: int = QUARTER_NOTE): self.duration = duration self.note = note self.instrument = instrument # Add a instrument member variable, such as self.instrument, # so we can invoke get_note_sound_path(note) and that function will know # whether the instrument is piano, flute, or guitar # self.instrument = instrument <--- where instrument will be provided as a string argument when # invoking Note() # ex Note() call: Note('A3', EIGHTH_NOTE, guitar) # This calls the constructor method for the Sound class, where the __sound is # a member variable of the Note class. # get_piano_note_sound_path() is in sound_effects.py # We will need to change this and allow it to choose flute, piano, or guitar self.__sound = Sound(get_note_sound_path(note, instrument)) def play(self) -> None: """Play the note. :return: None """ self.__sound.play() def to_str(self) -> str: return self.note def __eq__(self, other): return isinstance(other, Note) and self.note == other.note def __repr__(self): return "<Note '{}'>".format(self.note) def __str__(self): return "<Note '{}'>".format(self.note)
class LcarsHalfButton(LcarsWidget): """Button - half sized for increment and decrement usage """ # Parameter direction can be up/down/left/right, defines side that curve of button is on. # Are enums a thing in Python? # Default colour? def __init__(self, colour, pos, text, handler=None, direction="up"): if (direction=="up"): image = pygame.image.load("assets/buttons/half_button_u.png").convert() if (direction == "down"): image = pygame.image.load("assets/buttons/half_button_d.png").convert() if (direction == "left"): image = pygame.image.load("assets/buttons/half_button_l.png").convert() if (direction == "right"): image = pygame.image.load("assets/buttons/half_button_r.png").convert() size = (image.get_rect().width, image.get_rect().height) self.colour = colour self.image = image font = Font("assets/swiss911.ttf", 19) textImage = font.render(text, False, colours.BLACK) image.blit(textImage, (image.get_rect().width - textImage.get_rect().width - 10, image.get_rect().height - textImage.get_rect().height - 5)) LcarsWidget.__init__(self, colour, pos, size, handler) self.applyColour(colour) self.highlighted = False self.beep = Sound("assets/audio/panel/202.wav") def handleEvent(self, event, clock): if (event.type == MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos)): self.applyColour(colours.WHITE) self.highlighted = True self.beep.play() if (event.type == MOUSEBUTTONUP and self.highlighted): self.applyColour(self.colour) return LcarsWidget.handleEvent(self, event, clock) def changeColour(self, colour): self.applyColour(colour)
class Enemy(Spaceship, EventHandler): def __init__(self, config: EnenyConfig): super().__init__(image_path=f'assets/enemy_{config.image_id}.png') self.shoot_sound = Sound('assets/player_shoot.wav') self.shoot_sound.set_volume(0.5) self.config = config self.rect.y = 0 self.rect.x = SCREEN_WITH // 2 - self.rect.width // 2 self._random_move() self._random_shoot() def _random_move(self): event = Event( pygame.USEREVENT, dict(value=CreateDelayedEvent(delay=random.randint( *self.config.movement_freq), element=self, event=ChangeDirectionEvent()))) pygame.event.post(event) def _random_shoot(self): event = Event( pygame.USEREVENT, dict(value=CreateDelayedEvent(delay=random.randint( *self.config.shoot_freq), element=self, event=ShootEvent()))) pygame.event.post(event) def create_bullet(self, direction=Directon.UP): return Bullet(self.rect.x + self.rect.width // 2, self.rect.y + self.rect.height, Directon.DOWN) def handle(self, event: pygame.event.Event): if event.type == pygame.USEREVENT: if isinstance(event.value, ChangeDirectionEvent): self.move_x = random.randint(-1, 1) * self.MOVE_STEP self._random_move() elif isinstance(event.value, ShootEvent): self.shoot() self.shoot_sound.play() self._random_shoot()
class SplashScreen(GameState): def __init__(self): super(SplashScreen, self).__init__() self.font = pygame.font.Font(MAIN_TITLE_FONT[0], 54) self.title = self.font.render(GAME_TITLE, True, (229, 22, 22)) self.title_rect = self.title.get_rect(x=(SCREEN_SIZE[0] / 2) - 220, y=80) self.persist["screen_color"] = "black" self.next_state = "GAMEPLAY" self.menu = Menu([ Button("Start", ((SCREEN_SIZE[0] / 2) - 125, 300, 250, 40)), Button("Credits", ((SCREEN_SIZE[0] / 2) - 125, 350, 250, 40)) ]) self.sound = Sound("assets/sound/MainTheme.wav") self.sound.play() def startup(self, persistent): self.sound.play() self.menu.select_option(0) def get_event(self, event): if event.type == pygame.QUIT: self.quit = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: self.menu.select_option(-1) elif event.key == pygame.K_DOWN: self.menu.select_option(1) elif event.key == pygame.K_RETURN: self.next_state = "GAMEPLAY" if self.menu.selected_option == 0 else "CREDITS" self.persist["selected_option"] = self.menu.selected_option self.done = True self.sound.stop() def draw(self, surface): surface.fill(Color("black")) background = pygame.image.load("assets/images/nave.png").convert() background.set_colorkey((255, 255, 255)) surface.blit(background, [(SCREEN_SIZE[0] / 2) - 250, (SCREEN_SIZE[1] / 2) - 140]) surface.blit(self.title, self.title_rect) self.menu.draw(surface) def update(self, surface): self.menu.update()
class LcarsElbow(LcarsWidget): """The LCARS corner elbow - not currently used""" #STYLE_BOTTOM_LEFT = 0 #STYLE_TOP_LEFT = 1 #STYLE_BOTTOM_RIGHT = 2 #STYLE_TOP_RIGHT = 3 def __init__(self, colour, pos, text, handler=None): self.handler = handler image = pygame.image.load("assets/elbow.png").convert() size = (image.get_rect().width, image.get_rect().height) font = Font("assets/swiss911.ttf", 19) textImage = font.render(text, False, colours.BLACK) image.blit(textImage, (image.get_rect().width - 219, image.get_rect().height - textImage.get_rect().height - 35)) self.image = image self.colour = colour LcarsWidget.__init__(self, colour, pos, size) self.applyColour(colour) self.highlighted = False self.beep = Sound("assets/audio/panel/202.wav") def handleEvent(self, event, clock): handled = False if (event.type == MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos)): self.applyColour(colours.WHITE) self.highlighted = True self.beep.play() handled = True if (event.type == MOUSEBUTTONUP and self.highlighted): self.applyColour(self.colour) if self.handler: self.handler(self, event, clock) handled = True LcarsWidget.handleEvent(self, event, clock) return handled
class ScreenIdle(LcarsScreen): def setup(self, all_sprites): all_sprites.add(LcarsBackgroundImage("assets/lcars_splash.png"), layer=0) all_sprites.add(LcarsText(colours.ORANGE, (270, -1), "LCARS SYSTEM MONITOR", 1.8), layer=1) all_sprites.add(LcarsText( colours.BLUE, (330, -1), "ONLY AUTHORIZED PERSONNEL MAY ACCESS THIS TERMINAL", 1.5), layer=1) all_sprites.add(LcarsText(colours.BLUE, (360, -1), "TOUCH SCREEN TO PROCEED", 1.5), layer=1) all_sprites.add(LcarsGifImage("assets/animated/st_logo.gif", (103, 369), 50), layer=1) # sounds Sound("assets/audio/panel/215.wav").play() self.sound_beep1 = Sound("assets/audio/panel/206.wav") self.sound_denied = Sound("assets/audio/access_denied.wav") self.sound_deny1 = Sound("assets/audio/deny_1.wav") self.sound_deny2 = Sound("assets/audio/deny_2.wav") self.granted = False def handleEvents(self, event, fpsClock): LcarsScreen.handleEvents(self, event, fpsClock) if event.type == pygame.MOUSEBUTTONDOWN: self.granted = True self.sound_beep1.play() if event.type == pygame.MOUSEBUTTONUP: if (self.granted): #self.sound_granted.play() from screens.main import ScreenMain self.loadScreen(ScreenMain()) return False
class SoundEffect: """Class wrapping ``pygame.mixer.Sound`` with the ability to enable/disable sound globally Use this instead of ``pygame.mixer.Sound``. The interface is fully transparent. """ def __init__(self, source, ui_config): self._ui_config = ui_config if ui_config.sound_on: self.sound = Sound(source) def play(self, loops=0, maxtime=0, fade_ms=0): if self._ui_config: self.sound.play(loops, maxtime, fade_ms) def stop(self): if self._ui_config: self.sound.stop() def fadeout(self, time): if self._ui_config: self.sound.fadeout(time) def set_volume(self, value): if self._ui_config: self.sound.set_volume(value) def get_volume(self): if self._ui_config: return self.sound.get_volume() def get_num_channels(self): if self._ui_config: return self.sound.get_num_channels() def get_length(self): if self._ui_config: return self.get_length() def get_raw(self): if self._ui_config: return self.sound.get_raw()
class Sound: """Class wrapping ``pygame.mixer.Sound`` with the ability to enable/disable sound globally Use this instead of ``pygame.mixer.Sound``. The interface is fully transparent. """ def __init__(self, source): if config.SOUND: self.sound = OldSound(source) def play(self, loops=0, maxtime=0, fade_ms=0): if config.SOUND: self.sound.play(loops, maxtime, fade_ms) def stop(self): if config.SOUND: self.sound.stop() def fadeout(self, time): if config.SOUND: self.sound.fadeout(time) def set_volume(self, value): if config.SOUND: self.sound.set_volume(value) def get_volume(self): if config.SOUND: return self.sound.get_volume() def get_num_channels(self): if config.SOUND: return self.sound.get_num_channels() def get_length(self): if config.SOUND: return self.get_length() def get_raw(self): if config.SOUND: return self.sound.get_raw()
class SoundManager: #Constructor for SoundManager. Loads the music assets. def __init__(self): pre_init(22050, -16, 2, 1024) init() quit() init(22050, -16, 2, 1024) music.load(cfg.MUSIC_FILE) self.eatSfx = Sound(cfg.EAT_SFX_FILE) self.collideSfx = Sound(cfg.COLLIDE_SFX_FILE) self.winSfx = Sound(cfg.WIN_SFX_FILE) #Plays the background music. def playBackground(self): music.play() #Stops the background music. def stopBackground(self): music.stop() #Generates the eating SFX. def playEat(self): self.eatSfx.play() #Generates the collision SFX. def playCollide(self): self.collideSfx.play() #Generates the winning cheer SFX. def playWinning(self): self.winSfx.play()
def Play(sound_file): if Debug_mode: print("playing song") mixer_init = False while not mixer_init: try: if Debug_mode: print("attempting to init mixer") pygame.mixer.init() if Debug_mode: print("mixer init complete") mixer_init = True except: if Debug_mode: print("Waiting for mixer") time.sleep(10) continue pygame.mixer.init() sound = Sound(sound_file) sound.play() if Debug_mode: print("waiting for song") while pygame.mixer.get_busy(): if button.is_pressed: if Debug_mode: print("Button! Stopping Sound!") if button.is_pressed: if Debug_mode: print("button was pressed after stop - wating") button.wait_for_release() break continue if Debug_mode: print("stopping current sound") sound.stop() pygame.mixer.quit()
class RectangularDisableableChoiceButton(RectangularChoiceButton): def __init__(self, text, action, app, position, size, chosen, enabled): super().__init__(text, action, app, position, size, chosen) self._enabled = enabled self.disabled_color = (52, 52, 52) if self._dark_mode_on else (215, 215, 215) self._disabled_click_sound = Sound(os.path.join( ABS_PROJECT_ROOT_PATH, "game_app/resources/sounds/common/disabled_button_sound.wav")) def _get_color(self, mouse_position, is_mouse_pressed): if self._enabled: return super()._get_color(mouse_position, is_mouse_pressed) return self.disabled_color def set_enabled(self, new_enabled): self._enabled = new_enabled def on_pressed(self): if self._enabled: super().on_pressed() elif self._app.settings[Settings.SOUNDS]: self._disabled_click_sound.play()
class Explosion(pygame.sprite.Sprite, EventHandler): def __init__(self, x, y, width, height): super().__init__() self.count = 1 self.width = width self.height = height self.x = x self.y = y self.sound = Sound('assets/explosion.wav') self.sound.play() self._load_image() self._next_animation() def _load_image(self): self.image = pygame.image.load( f'assets/explosion_{self.count}.png').convert_alpha() self.image = pygame.transform.scale(self.image, (self.width, self.height)) self.rect = self.image.get_rect() self.rect.x = self.x self.rect.y = self.y def _next_animation(self): event = Event( pygame.USEREVENT, dict(value=CreateDelayedEvent( delay=200, element=self, event=AnimateEvent()))) pygame.event.post(event) def handle(self, event: pygame.event.Event): if event.type == pygame.USEREVENT and isinstance( event.value, AnimateEvent): if self.count >= 3: self.kill() else: self.count += 1 self._load_image() self._next_animation()
class Note: """Represents a musical note.""" def __init__(self, note: str, duration: int = QUARTER_NOTE): self.duration = duration self.note = note self.__sound = Sound(get_piano_note_sound_path(note)) def play(self) -> None: """Play the note. :return: None """ self.__sound.play() def __eq__(self, other): return isinstance(other, Note) and self.note == other.note def __repr__(self): return "<Note '{}'>".format(self.note) def __str__(self): return "<Note '{}'>".format(self.note)
class ScreenAbout(LcarsScreen): def setup(self, all_sprites): all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_1.png"), layer=0) # panel text all_sprites.add(LcarsText(colours.BLACK, (11, 75), "MOSF"), layer=1) all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "LONG RANGE PROBE", 2.5), layer=1) all_sprites.add(LcarsText(colours.BLACK, (54, 667), "192 168 0 3"), layer=1) # info text #all_sprites.add(LcarsText(colours.WHITE, (192, 174), "WELCOME", 1.5), # layer=3) #all_sprites.add(LcarsText(colours.BLUE, (244, 174), "TO THE Museum of Science Fiction", 1.5), # layer=3) #all_sprites.add(LcarsText(colours.BLUE, (286, 174), "LONG RANGE PROBE EXHIBIT", 1.5), # layer=3) #all_sprites.add(LcarsText(colours.BLUE, (330, 174), "LOOK AROUND", 1.5), # layer=3) #self.info_text = all_sprites.get_sprites_from_layer(3) # date display self.stardate = LcarsText(colours.BLACK, (444, 506), "", 1) self.lastClockUpdate = 0 all_sprites.add(self.stardate, layer=1) # permanent buttons all_sprites.add(LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler), layer=1) all_sprites.add(LcarsBlockSmall(colours.ORANGE, (211, 16), "ABOUT", self.aboutHandler), layer=1) all_sprites.add(LcarsBlockLarge(colours.BLUE, (145, 16), "DEMO", self.demoHandler), layer=1) all_sprites.add(LcarsBlockHuge(colours.PEACH, (249, 16), "EXPLORE", self.exploreHandler), layer=1) all_sprites.add(LcarsElbow(colours.BEIGE, (400, 16), "MAIN", self.mainHandler), layer=1) # Sounds self.beep1 = Sound("assets/audio/panel/201.wav") #Sound("assets/audio/panel/220.wav").play() # specific buttons self.purpose = LcarsButton(colours.GREY_BLUE, (107, 127), "PURPOSE", self.purposeHandler) self.purpose.visible = True all_sprites.add(self.purpose, layer=4) self.details = LcarsButton(colours.ORANGE, (107, 262), "DETAILS", self.detailsHandler) self.details.visible = True all_sprites.add(self.details, layer=4) self.personnel = LcarsButton(colours.GREY_BLUE, (107, 398), "PERSONNEL", self.personnelHandler) self.personnel.visible = True all_sprites.add(self.personnel, layer=4) self.sources = LcarsButton(colours.ORANGE, (107, 533), "SOURCES", self.sourcesHandler) self.sources.visible = True all_sprites.add(self.sources, layer=4) # Purpose all_sprites.add(LcarsText(colours.WHITE, (172, 140), "To inspire the next generation of STEAM", 2.7), layer=3) all_sprites.add(LcarsText(colours.WHITE, (217, 140), "(science, technology, engineering, art,", 2.7), layer=3) all_sprites.add(LcarsText(colours.WHITE, (262, 140), "mathematics) students to innovate with", 2.7), layer=3) all_sprites.add(LcarsText(colours.WHITE, (307, 140), "unique projects and boldly go where no", 2.7), layer=3) all_sprites.add(LcarsText(colours.WHITE, (352, 140), "one has gone before.", 2.7), layer=3) #all_sprites.add(LcarsText(colours.BLUE, (244, 174), "TO THE Museum of Science Fiction", 1), # layer=3) #all_sprites.add(LcarsText(colours.BLUE, (286, 174), "LONG RANGE PROBE EXHIBIT", 1), # layer=3) #all_sprites.add(LcarsText(colours.BLUE, (330, 174), "LOOK AROUND", 1), # layer=3) self.purpose_text = all_sprites.get_sprites_from_layer(3) self.hideText(self.purpose_text) # Details all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "LENGTH: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (192, 220), "1.5 m (4 ft 6 in)", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (212, 140), "WIDTH: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (212, 220), "0.45 m (1 ft 6 in)", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (232, 140), "HEIGHT: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (232, 220), "0.25 m (10 in)", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "MASS: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (252, 220), "20 kg (30 slugs)", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (292, 140), "MATERIALS: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (292, 220), "Carbon fiber reinforced fiberglass shell, internal components 3D-printed PLA plastic", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (332, 140), "CONTROL: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (332, 220), "7-inch touchscreen via Rasberry Pi, lights & movement via Arduino Mega", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (372, 140), "COST: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (372, 220), "$1,000, 800 man-hours", 1.25), layer=6) self.details_text = all_sprites.get_sprites_from_layer(6) self.hideText(self.details_text) # Personnel all_sprites.add(LcarsText(colours.RED_BROWN, (192, 140), "Designed and built by a team of four mechanical & aerospace", 1.25), layer=7) all_sprites.add(LcarsText(colours.RED_BROWN, (212, 140), "engineering students at North Carolina State University", 1.25), layer=7) self.personnel_text= all_sprites.get_sprites_from_layer(7) self.hideText(self.personnel_text) self.personnel_image1 = LcarsImage("assets/ncsu.png", (192, 560)) self.personnel_image1.visible = False all_sprites.add(self.personnel_image1, layer=7) # Sources all_sprites.add(LcarsText(colours.GREY_BLUE, (192, 140), "SPECIAL THANKS TO:", 1.25), layer=8) all_sprites.add(LcarsText(colours.WHITE, (212, 180), "Toby Kurien (creator of LCARS Python Graphical Interface)", 1.25), layer=8) all_sprites.add(LcarsText(colours.WHITE, (232, 180), "NC State Mechanical Engineering Department", 1.25), layer=8) all_sprites.add(LcarsText(colours.WHITE,(252, 180), "NC State Entrepreneurship Initiative Garage", 1.25), layer=8) self.sources_text = all_sprites.get_sprites_from_layer(8) self.hideText(self.sources_text) #TEST self.test = LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler) self.test.visible = False all_sprites.add(self.test, layer = 4) def update(self, screenSurface, fpsClock): if pygame.time.get_ticks() - self.lastClockUpdate > 1000: self.stardate.setText("EARTH DATE {}".format(datetime.now().strftime("%m.%d.%y %H:%M:%S"))) self.lastClockUpdate = pygame.time.get_ticks() LcarsScreen.update(self, screenSurface, fpsClock) def handleEvents(self, event, fpsClock): LcarsScreen.handleEvents(self, event, fpsClock) if event.type == pygame.MOUSEBUTTONDOWN: self.beep1.play() if event.type == pygame.MOUSEBUTTONUP: return False def hideText(self, name): if name[0].visible: for sprite in name: sprite.visible = False def showText(self, name): for sprite in name: sprite.visible = True def logoutHandler(self, item, event, clock): # demo() from screens.authorize import ScreenAuthorize self.loadScreen(ScreenAuthorize()) def demoHandler(self, item, event, clock): demo(a) def exploreHandler(self, item, event, clock): # demo() from screens.exploreScreen import ScreenExplore self.loadScreen(ScreenExplore()) def mainHandler(self, item, event, clock): # demo() from screens.main import ScreenMain self.loadScreen(ScreenMain()) ## Specific Screen Handlers def aboutHandler(self, item, event, clock): self.hideText(self.purpose_text) self.hideText(self.details_text) self.hideText(self.personnel_text) self.personnel_image1.visible = False self.hideText(self.sources_text) def purposeHandler(self, item, event, clock): self.showText(self.purpose_text) self.hideText(self.details_text) self.hideText(self.personnel_text) self.personnel_image1.visible = False self.hideText(self.sources_text) def detailsHandler(self, item, event, clock): self.hideText(self.purpose_text) self.showText(self.details_text) self.hideText(self.personnel_text) self.personnel_image1.visible = False self.hideText(self.sources_text) def personnelHandler(self, item, event, clock): self.hideText(self.purpose_text) self.hideText(self.details_text) self.showText(self.personnel_text) self.personnel_image1.visible = True self.hideText(self.sources_text) def sourcesHandler(self, item, event, clock): self.hideText(self.purpose_text) self.hideText(self.details_text) self.hideText(self.personnel_text) self.personnel_image1.visible = False self.showText(self.sources_text)
class ScreenMain(LcarsScreen): def setup(self, all_sprites): areset(a) all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_1.png"), layer=0) # panel text all_sprites.add(LcarsText(colours.BLACK, (11, 75), "MOSF"), layer=1) all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "LONG RANGE PROBE", 2.5), layer=1) all_sprites.add(LcarsText(colours.BLACK, (54, 667), "192 168 0 3"), layer=1) # date display self.stardate = LcarsText(colours.BLACK, (444, 506), "", 1) self.lastClockUpdate = 0 all_sprites.add(self.stardate, layer=1) # permanent buttons all_sprites.add(LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler), layer=1) all_sprites.add(LcarsBlockSmall(colours.ORANGE, (211, 16), "ABOUT", self.aboutHandler), layer=1) all_sprites.add(LcarsBlockLarge(colours.BLUE, (145, 16), "DEMO", self.demoHandler), layer=1) all_sprites.add(LcarsBlockHuge(colours.PEACH, (249, 16), "EXPLORE", self.exploreHandler), layer=1) all_sprites.add(LcarsElbow(colours.BEIGE, (400, 16), "MAIN"), layer=1) # Sounds self.beep_1 = Sound("assets/audio/panel/201.wav") self.fwoosh = Sound("assets/audio/panel/250.m4a") self.fwoosh.set_volume(1.0) self.fwoosh.play() time.sleep(6) # Sound("assets/audio/panel/220.wav").play() #-----Screens-----# # Main Screen ------------------------------------------------------------------------------------ #116-800: 684 : 342 #90-440 : 350 : 175 all_sprites.add(LcarsText(colours.WHITE, (192, 174), "WELCOME", 1.5), layer=3) all_sprites.add(LcarsText(colours.BLUE, (244, 174), "TO THE Museum of Science Fiction", 1.5), layer=3) all_sprites.add(LcarsText(colours.BLUE, (286, 174), "LONG RANGE PROBE EXHIBIT", 1.5), layer=3) all_sprites.add(LcarsText(colours.BLUE, (330, 174), "LOOK AROUND", 1.5), layer=3) self.main_text = all_sprites.get_sprites_from_layer(3) # Logout Screen ---------------------------------------------------------------------------------- self.logout_image = LcarsImage("assets/intro_screen.png", (0,0), self.mainHandler) self.logout_image.visible = False all_sprites.add(self.logout_image, layer=49) #Previously layer2 self.logout_gif = LcarsGifImage("assets/gadgets/MOSF.gif", (90, 330), 35) self.logout_gif.visible = False all_sprites.add(self.logout_gif, layer=49) #Previously 2 all_sprites.add(LcarsText(colours.ORANGE, (270, -1), "LONG RANGE PROBE", 3), layer=50) all_sprites.add(LcarsText(colours.ORANGE, (390, -1), "TOUCH TERMINAL TO PROCEED", 1.5), layer=50) self.logout_text = all_sprites.get_sprites_from_layer(50) self.hideText(self.logout_text) # Demo Screen ------------------------------------------------------------------------------------ # About Screen ----------------------------------------------------------------------------------- self.purpose = LcarsButton(colours.GREY_BLUE, (107, 127), "PURPOSE", self.purposeHandler) self.purpose.visible = False all_sprites.add(self.purpose, layer=4) self.details = LcarsButton(colours.ORANGE, (107, 262), "DETAILS", self.detailsHandler) self.details.visible = False all_sprites.add(self.details, layer=4) self.personnel = LcarsButton(colours.GREY_BLUE, (107, 398), "PERSONNEL", self.personnelHandler) self.personnel.visible = False all_sprites.add(self.personnel, layer=4) self.sources = LcarsButton(colours.ORANGE, (107, 533), "SOURCES", self.sourcesHandler) self.sources.visible = False all_sprites.add(self.sources, layer=4) # Purpose all_sprites.add(LcarsText(colours.WHITE, (192, 140), "To inspire", 1.25), layer=5) #all_sprites.add(LcarsText(colours.BLUE, (244, 174), "TO THE Museum of Science Fiction", 1), # layer=3) #all_sprites.add(LcarsText(colours.BLUE, (286, 174), "LONG RANGE PROBE EXHIBIT", 1), # layer=3) #all_sprites.add(LcarsText(colours.BLUE, (330, 174), "LOOK AROUND", 1), # layer=3) self.purpose_text = all_sprites.get_sprites_from_layer(5) self.hideText(self.purpose_text) # Details all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "LENGTH: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (192, 220), "1.5 m (4 ft 6 in)", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (212, 140), "WIDTH: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (212, 220), "0.45 m (blah)", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (232, 140), "HEIGHT: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (232, 220), "0.25 m (blah)", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "MASS: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (252, 220), "20 kg (30 slugs)", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (292, 140), "MATERIALS: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (292, 220), "Carbon fiber reinforced fiberglass shell, internal components 3-D printed PLA plastic", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (332, 140), "CONTROL: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (332, 220), "7 in touchscreen via Rasberry Pi, lights & movement via Arduino Mega", 1.25), layer=6) all_sprites.add(LcarsText(colours.ORANGE, (372, 140), "COST: ", 1.25), layer=6) all_sprites.add(LcarsText(colours.WHITE, (372, 220), "$$$", 1.25), layer=6) self.details_text = all_sprites.get_sprites_from_layer(6) self.hideText(self.details_text) # Personnel all_sprites.add(LcarsText(colours.RED_BROWN, (192, 140), "Designed and built by a team of four mechanical & aerospace", 1.25), layer=7) all_sprites.add(LcarsText(colours.RED_BROWN, (212, 140), "engineering students at North Carolina State University", 1.25), layer=7) self.personnel_text= all_sprites.get_sprites_from_layer(7) self.hideText(self.personnel_text) self.personnel_image1 = LcarsImage("assets/ncsu.png", (192, 560)) self.personnel_image1.visible = False all_sprites.add(self.personnel_image1, layer=7) # Sources all_sprites.add(LcarsText(colours.GREY_BLUE, (192, 140), "SPECIAL THANKS TO:", 1.25), layer=8) all_sprites.add(LcarsText(colours.WHITE, (212, 180), "Toby Kurien", 1.25), layer=8) all_sprites.add(LcarsText(colours.WHITE,(232, 180), "NC State EI Garage", 1.25), layer=8) self.sources_text = all_sprites.get_sprites_from_layer(8) self.hideText(self.sources_text) # Explore Screen --------------------------------------------------------------------------------- all_sprites.add(LcarsText(colours.RED_BROWN, (142, 140), "Select a section for more information", 1.25), layer=70) self.explore_screen_text = all_sprites.get_sprites_from_layer(70) self.hideText(self.explore_screen_text) self.probe_forward_image = LcarsImage("assets/probe_front.png", (172, 500), self.forwardHandler) self.probe_forward_image.visible = False all_sprites.add(self.probe_forward_image, layer =70) self.probe_aft_image = LcarsImage("assets/probe_rear.png", (172, 150), self.aftHandler) self.probe_aft_image.visible = False all_sprites.add(self.probe_aft_image, layer=70) ##### Forward Section ##### all_sprites.add(LcarsText(colours.RED_BROWN, (142, 140), "Select a component for more information", 1.25), layer=71) self.forward_text = all_sprites.get_sprites_from_layer(71) # self.forward_text.visible = False self.forward_plate = LcarsImage("assets/forward/front_section.png", (172, 533)) self.forward_plate.visible = False all_sprites.add(self.probe_forward_image, layer =71) ## Back Forward Button ## self.forward_button = LcarsTabBlock(colours.RED_BROWN, (372, 650), "BACK", self.forwardHandler) self.forward_button.visible = False all_sprites.add(self.forward_button, layer=60) ## Back Aft Button ## self.aft_button = LcarsTabBlock(colours.RED_BROWN, (372, 650), "BACK", self.exploreHandler) self.aft_button.visible = False all_sprites.add(self.aft_button, layer=60) # BTO ARRAY # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "B.T.O. ARRAY", 1.75), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "The B.T.O. Array is the primary method of communication for the probe.", 1.25), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "The array is entirely composed of the S.B.S. High-Gain Parabolic Antenna,", 1.25), layer = 61) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "which is capable of simultaneous dual transmission in the S and X bands", 1.25), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "and receipt of control commands in the Ka and Ku bands. The array is", 1.25), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "paired with the Yokel Sensor Suite to determine physical properties of ", 1.25), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "local bodies using microwave radiation.", 1.25), layer=61) self.communication_text = all_sprites.get_sprites_from_layer(61) self.hideText(self.communication_text) # YOKEL SENSOR SUITE # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "YOKEL SENSOR SUITE", 1.75), layer=62) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "The Yokel Sensor Suite houses the scientific payload and guidance", 1.25), layer=62) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "system on the probe. The instruments contained within are:", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (222, 150), "Autonomous Telemetry Guidance Unit", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (242, 150), "Energetic Particle Detector", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (262, 150), "Gravitational Mapping Unit", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (282, 150), "High Energy Multi-Spectral Analyzer", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (302, 150), "Magnetometry Suite", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (322, 150), "Radar Detection & Tracking System", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (342, 150), "Radio Science Array", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (362, 150), "Space Radiation Measurement System", 1.25), layer=62) all_sprites.add(LcarsText(colours.ORANGE, (392, 140), "Collected data is stored in the Optical Data Chips for later processing.", 1.25), layer=62) self.sensor_text = all_sprites.get_sprites_from_layer(62) self.hideText(self.sensor_text) # Probe Computers # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "PROBE COMPUTERS", 1.75), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "This probe features two onboard computers, the Guidance Computer and", 1.25), layer=63) all_sprites.add(LcarsText(colours.WHITE, (162, 473), "Guidance Computer", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "the Data Processing Unit , which handle all data and control processes.", 1.25), layer=63) all_sprites.add(LcarsText(colours.WHITE, (192, 165), "Data Processing Unit", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "The Guidance Computer receives control commands through the BTO ", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "Array, and local object data from the Yokel Sensor Suite, to ensure safe", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "travel. The Data Processing Unit receives all raw data from the Optical", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "and processes the data for transmission. For redundancy, both", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (342, 140), "computers are independently capable of assuming the others' duties.", 1.25), layer=63) self.computer_text = all_sprites.get_sprites_from_layer(63) self.hideText(self.computer_text) # Optical Data Chips # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "OPTICAL DATA CHIPS", 1.75), layer=64) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "This probe is equipped with 24 optical data chips for the storage of sensor", 1.25), layer=64) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "and control data. Each chip, which can store up to 830 TB of data, is", 1.25), layer=64) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "constructed of a nano-structured quartz composite. Data is read/written", 1.25), layer=64) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "to the chips using a Smith-Taylor laser system.", 1.25), layer=64) self.chip_text = all_sprites.get_sprites_from_layer(64) self.hideText(self.chip_text) # Lofton Microfusion Core # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "LOFTON MICROFUSION CORE", 1.75), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "All of the required power for the probe is provided by the Lofton", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "Microfusion Core. Encased within a shielded tungsten-titanium shell,", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "11.3 KW of power are produced from a micro-aneutronic fusion reaction ", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "which is converted to electricity via electrostatic direct conversion.", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "Of the 11.3 KW produced, 8 KW are used by the ion propulsion system,", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "1.4 KW by the sensor suite, 1 KW by the computers, and 0.9 KW by the", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (342, 140), "communication array during normal operation. Helium is used for the", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (372, 140), "fusion reaction which is provided by the monopropellant tank.", 1.25), layer=65) self.fusion_text = all_sprites.get_sprites_from_layer(65) self.hideText(self.fusion_text) ###### AFT SECTION ###### all_sprites.add(LcarsText(colours.WHITE, (112, 140), "PROPULSION SYSTEM", 1.75), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "After launch, the probe is driven by the Kehrer Hybrid Ion Drive, is", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "capable of both ion and chemical propulsion, and is comprised of the ", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "engine, thrusters, and fuel tanks. Ion propulsion creates thrust by drawing", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "power from the fusion core to accelerate and expel Xenon ions from the", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "two, 420 kg storage tanks, and is the main method of propulsion. For quick", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "changes in velocity, the chemical propulsion system is activated. This", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (342, 140), "system uses the monopropellant hydrazine, which is stored in the 300 kg ", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (372, 140), "storage tank. The combination of two different propulsion methods allows", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (402, 140), "the probe a versatile mix of range and maneuverability.", 1.25), layer=66) self.propulsion_text = all_sprites.get_sprites_from_layer(66) self.hideText(self.propulsion_text) # ** Event Handlers ** def update(self, screenSurface, fpsClock): if pygame.time.get_ticks() - self.lastClockUpdate > 1000: self.stardate.setText("EARTH DATE {}".format(datetime.now().strftime("%m.%d.%y %H:%M:%S"))) self.lastClockUpdate = pygame.time.get_ticks() LcarsScreen.update(self, screenSurface, fpsClock) def handleEvents(self, event, fpsClock): LcarsScreen.handleEvents(self, event, fpsClock) if event.type == pygame.MOUSEBUTTONDOWN: self.beep_1.play() if event.type == pygame.MOUSEBUTTONUP: return False # ** Screen Handlers ** -------------------------------------------------------------------- def mainHandler(self, item, event, clock): # demo(a) self.hideAll() self.showText(self.main_text) def logoutHandler(self, item, event, clock): # demo(a) from screens.authorize import ScreenAuthorize self.loadScreen(ScreenAuthorize()) # PUT TURN OFF COMMAND HERE def aboutHandler(self, item, event, clock): # demo(a) from screens.aboutScreen import ScreenAbout self.loadScreen(ScreenAbout()) def demoHandler(self, item, event, clock): demo(a) def exploreHandler(self, item, event, clock): # demo(a) from screens.exploreScreen import ScreenExplore self.loadScreen(ScreenExplore()) # self.hideAll() # # self.showText(self.explore_screen_text) # self.probe_forward_image.visible = True # self.probe_aft_image.visible = True # ** Sub Screen Handlers ** ----------------------------------------------------------------- # About Screen ------------------------------------- def purposeHandler(self, item, event, clock): self.showText(self.purpose_text) self.hideText(self.details_text) self.hideText(self.personnel_text) self.personnel_image1.visible = False self.hideText(self.sources_text) def detailsHandler(self, item, event, clock): self.hideText(self.purpose_text) self.showText(self.details_text) self.hideText(self.personnel_text) self.personnel_image1.visible = False self.hideText(self.sources_text) def personnelHandler(self, item, event, clock): self.hideText(self.purpose_text) self.hideText(self.details_text) self.showText(self.personnel_text) self.personnel_image1.visible = True self.hideText(self.sources_text) def sourcesHandler(self, item, event, clock): self.hideText(self.purpose_text) self.hideText(self.details_text) self.hideText(self.personnel_text) self.personnel_image1.visible = False self.showText(self.sources_text) # Explore Screen ----------------------------------- # ** Main ** def forwardHandler(self, item, event, clock): self.hideText(self.explore_screen_text) self.probe_forward_image.visible = False self.probe_aft_image.visible = False self.forward_button.visible = False self.hideText(self.communication_text) self.hideText(self.sensor_text) self.hideText(self.computer_text) self.hideText(self.chip_text) self.hideText(self.fusion_text) self.showText(self.forward_text) self.aft_button.visible = True #Put others here self.forward_plate.visible = True def aftHandler(self, item, event, clock): self.hideText(self.explore_screen_text) self.probe_forward_image.visible = False self.probe_aft_image.visible = False self.showText(propulsion_text) self.aft_button.visible = True # ** Forward ** def communicationsHandler(self, item, event, clock): self.showText(self.communication_text) self.aft_button.visible = False self.forward_button.visible = True def sensorsHandler(self, item, event, clock): self.showText(sensor_text) self.aft_button.visible = False self.forward_button.visible = True def computerHandler(self, item, event, clock): self.showText(computer_text) self.aft_button.visible = False self.forward_button.visible = True def chipsHandler(self, item, event, clock): self.showText(chip_text) self.aft_button.visible = False self.forward_button.visible = True def powerHandler(self, item, event, clock): self.showText(fusion_text) self.aft_button.visible = False self.forward_button.visible = True # ** Content Handlers ** -------------------------------------------------------- def hideText(self, name): if name[0].visible: for sprite in name: sprite.visible = False def showText(self, name): for sprite in name: sprite.visible = True def hideAll(self): #MAIN self.hideText(self.main_text) #LOGOUT self.logout_image.visible = False self.logout_gif.visible = False self.hideText(self.logout_text) #ABOUT self.purpose.visible = False self.details.visible = False self.personnel.visible = False self.sources.visible = False self.hideText(self.purpose_text) self.hideText(self.details_text) self.hideText(self.personnel_text) self.personnel_image1.visible = False self.hideText(self.sources_text) #EXPLORE self.probe_forward_image.visible = False self.probe_aft_image.visible = False self.forward_plate.visible = False self.aft_button.visible = False self.forward_button.visible = False self.hideText(self.explore_screen_text) self.hideText(self.forward_text) self.hideText(self.propulsion_text) self.hideText(self.communication_text) self.hideText(self.sensor_text) self.hideText(self.computer_text) self.hideText(self.chip_text) self.hideText(self.fusion_text)
class Player(PhysicsObject): def __init__(self, pos, color_interval, input): PhysicsObject.__init__(self, pos, (0, 0), (28, 48), BODY_DYNAMIC) self.change_color_mode = False self.color_interval = 0 self.color_timer_text = None if color_interval > 0: self.change_color_mode = True self.color_interval = color_interval font = Font('./assets/font/vcr.ttf', 18) self.color_timer_text = Text(font, str(color_interval), (740, 5)) self.color_timer_text.update = True self.color_timer = 0.0 self.input = input self.sprite = Sprite("./assets/img/new_guy.png", (64, 64), (1.0 / 12.0)) self.set_foot(True) self.active_color = 'red' self.acceleration = 400 self.dead = False self.sound_jump = Sound('./assets/audio/jump.wav') self.sound_land = Sound('./assets/audio/land.wav') self.sound_push = Sound('./assets/audio/push.wav') self.sound_timer = 0.0 self.sound_min_interval = 0.5 self.id = ID_PLAYER self.bounce_timer = 0.0 # view rectangle for HUD stuff self.view_rect = Rect(0, 0, 0, 0) def handle_input(self, dt): self.target_vel.x = 0 if self.input.is_pressed(K_RIGHT): if not self.wants_to_move: self.wants_to_move = True self.target_vel.x = 300 self.sprite.set_direction(1) self.sprite.use_frames([1, 2]) elif self.input.is_pressed(K_LEFT): if not self.wants_to_move: self.wants_to_move = True self.target_vel.x = -300 self.sprite.set_direction(-1) self.sprite.use_frames([1, 2]) if self.input.is_down(K_UP) and self.on_ground: self.vel.y = PLAYER_JUMP_FORCE PLAY_SOUND(self.sound_jump) # if we are in the automatic color changing mode # ignore the input from the user if self.change_color_mode: return if self.input.is_down(K_1): self.active_color = 'red' self.sprite.set_offset(0) elif self.input.is_down(K_2): self.active_color = 'green' self.sprite.set_offset(4) elif self.input.is_down(K_3): self.active_color = 'blue' self.sprite.set_offset(8) def play_land_sound(self): if self.sound_timer > self.sound_min_interval: PLAY_SOUND(self.sound_land.play()) self.sound_timer = 0.0 def on_collide_obj(self, obj): if isinstance(obj, ColorChangingBlock) or \ isinstance(obj, MovingBlock) or \ isinstance(obj, MovableBlock) or \ isinstance(obj, ImpulseBlock): if obj.active_color != self.active_color: if self.vel.y > 1.0: pass return True return False elif isinstance(obj, LavaBlock): self.dead = True elif isinstance(obj, ExitBlock): return True if self.active_color != 'green' else False return True def on_collide_platform(self, platform): if platform.layer != self.active_color: if self.vel.y > 1.0: pass return True return False def change_color(self): current_color_index = COLORS.index(self.active_color) next_color_index = (current_color_index + 1) % len(COLORS) self.active_color = COLORS[next_color_index] self.sprite.set_offset(4 * next_color_index) def update(self, dt): PhysicsObject.update(self, dt) self.handle_input(dt) self.sprite.update(dt) self.sound_timer += dt if self.bounce_timer > 0.0: self.bounce_timer -= dt if self.change_color_mode: self.color_timer_text.text = str(self.color_interval - self.color_timer)[:4] self.color_timer += dt if self.color_timer >= self.color_interval: self.color_timer = 0.0 self.change_color() if self.vel.y > 1.0 and not self.on_ground: self.sprite.use_frames([3]) else: self.sprite.use_frames([0]) def draw(self, screen): rect = copy.copy(self.rect) # TODO: find the reason of this bug rect.bottom -= 16 self.sprite.draw(screen, rect) if not self.color_timer_text is None: self.color_timer_text.draw(screen, self.view_rect)
class ScreenAuthorize(LcarsScreen): def setup(self, all_sprites): all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_2.png"), layer=0) all_sprites.add(LcarsGifImage("assets/gadgets/stlogorotating.gif", (103, 369), 50), layer=0) all_sprites.add(LcarsText(colours.ORANGE, (270, -1), "AUTHORIZATION REQUIRED", 2), layer=0) all_sprites.add(LcarsText(colours.BLUE, (330, -1), "ONLY AUTHORIZED PERSONNEL MAY ACCESS THIS TERMINAL", 1.5), layer=1) all_sprites.add(LcarsText(colours.BLUE, (360, -1), "TOUCH TERMINAL TO PROCEED", 1.5), layer=1) #all_sprites.add(LcarsText(colours.BLUE, (390, -1), "FAILED ATTEMPTS WILL BE REPORTED", 1.5),layer=1) all_sprites.add(LcarsButton(colours.GREY_BLUE, (320, 130), "1", self.num_1), layer=2) all_sprites.add(LcarsButton(colours.GREY_BLUE, (370, 130), "2", self.num_2), layer=2) all_sprites.add(LcarsButton(colours.GREY_BLUE, (320, 270), "3", self.num_3), layer=2) all_sprites.add(LcarsButton(colours.GREY_BLUE, (370, 270), "4", self.num_4), layer=2) all_sprites.add(LcarsButton(colours.GREY_BLUE, (320, 410), "5", self.num_5), layer=2) all_sprites.add(LcarsButton(colours.GREY_BLUE, (370, 410), "6", self.num_6), layer=2) all_sprites.add(LcarsButton(colours.GREY_BLUE, (320, 550), "7", self.num_7), layer=2) all_sprites.add(LcarsButton(colours.GREY_BLUE, (370, 550), "8", self.num_8), layer=2) self.layer1 = all_sprites.get_sprites_from_layer(1) self.layer2 = all_sprites.get_sprites_from_layer(2) # sounds Sound("assets/audio/panel/215.wav").play() self.sound_granted = Sound("assets/audio/accessing.wav") self.sound_beep1 = Sound("assets/audio/panel/201.wav") self.sound_denied = Sound("assets/audio/access_denied.wav") self.sound_deny1 = Sound("assets/audio/deny_1.wav") self.sound_deny2 = Sound("assets/audio/deny_2.wav") ############ # SET PIN CODE WITH THIS VARIABLE ############ self.pin = 1234 ############ self.reset() def reset(self): # Variables for PIN code verification self.correct = 0 self.pin_i = 0 self.granted = False for sprite in self.layer1: sprite.visible = True for sprite in self.layer2: sprite.visible = False def handleEvents(self, event, fpsClock): if event.type == pygame.MOUSEBUTTONDOWN: # Play sound self.sound_beep1.play() if event.type == pygame.MOUSEBUTTONUP: if (not self.layer2[0].visible): for sprite in self.layer1: sprite.visible = False for sprite in self.layer2: sprite.visible = True Sound("assets/audio/enter_authorization_code.wav").play() elif (self.pin_i == len(str(self.pin))): # Ran out of button presses if (self.correct == 4): self.sound_granted.play() from screens.main import ScreenMain self.loadScreen(ScreenMain()) else: self.sound_deny2.play() self.sound_denied.play() self.reset() return False def num_1(self, item, event, clock): if str(self.pin)[self.pin_i] == '1': self.correct += 1 self.pin_i += 1 def num_2(self, item, event, clock): if str(self.pin)[self.pin_i] == '2': self.correct += 1 self.pin_i += 1 def num_3(self, item, event, clock): if str(self.pin)[self.pin_i] == '3': self.correct += 1 self.pin_i += 1 def num_4(self, item, event, clock): if str(self.pin)[self.pin_i] == '4': self.correct += 1 self.pin_i += 1 def num_5(self, item, event, clock): if str(self.pin)[self.pin_i] == '5': self.correct += 1 self.pin_i += 1 def num_6(self, item, event, clock): if str(self.pin)[self.pin_i] == '6': self.correct += 1 self.pin_i += 1 def num_7(self, item, event, clock): if str(self.pin)[self.pin_i] == '7': self.correct += 1 self.pin_i += 1 def num_8(self, item, event, clock): if str(self.pin)[self.pin_i] == '8': self.correct += 1 self.pin_i += 1
def exibe_som(som): som = Sound(som) som.play()
class ScreenMain(LcarsScreen): def setup(self, all_sprites): all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_1.png"), layer=0) # panel text all_sprites.add(LcarsText(colours.BLACK, (11, 75), "MOSF"), layer=1) all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "LONG RANGE PROBE", 2.5), layer=1) all_sprites.add(LcarsText(colours.BLACK, (54, 667), "192 168 0 3"), layer=1) # date display self.stardate = LcarsText(colours.BLACK, (444, 506), "", 1) self.lastClockUpdate = 0 all_sprites.add(self.stardate, layer=1) # permanent buttons all_sprites.add(LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler), layer=1) all_sprites.add(LcarsBlockSmall(colours.ORANGE, (211, 16), "ABOUT", self.aboutHandler), layer=1) all_sprites.add(LcarsBlockLarge(colours.BLUE, (145, 16), "DEMO", self.demoHandler), layer=1) all_sprites.add(LcarsBlockHuge(colours.PEACH, (249, 16), "EXPLORE", self.exploreHandler), layer=1) all_sprites.add(LcarsElbow(colours.BEIGE, (400, 16), "MAIN"), layer=1) # Sounds self.beep1 = Sound("assets/audio/panel/201.wav") #Sound("assets/audio/panel/220.wav").play() #-----Screens-----# # Main Screen all_sprites.add(LcarsText(colours.WHITE, (265, 458), "WELCOME", 1.5), layer=3) all_sprites.add(LcarsText(colours.BLUE, (244, 174), "TO THE Museum of Science Fiction", 1.5), layer=3) all_sprites.add(LcarsText(colours.BLUE, (286, 174), "LONG RANGE PROBE EXHIBIT", 1.5), layer=3) all_sprites.add(LcarsText(colours.BLUE, (330, 174), "LOOK AROUND", 1.5), layer=3) self.info_text = all_sprites.get_sprites_from_layer(3) # Demo Screen #116-800: 684 : 342 #90-440 : 350 : 175 # About Screen # Explore Screen # # gadgets #all_sprites.add(LcarsGifImage("assets/gadgets/fwscan.gif", (277, 556), 100), layer=1) #self.sensor_gadget = LcarsGifImage("assets/gadgets/lcars_anim2.gif", (235, 150), 100) #self.sensor_gadget.visible = False #all_sprites.add(self.sensor_gadget, layer=2) #self.dashboard = LcarsImage("assets/gadgets/dashboard.png", (187, 232)) #self.dashboard.visible = False #all_sprites.add(self.dashboard, layer=2) #self.weather = LcarsImage("assets/weather.jpg", (188, 122)) #self.weather.visible = False #all_sprites.add(self.weather, layer=2) #self.earth = LcarsGifImage("assets/gadgets/earth.gif", (187, 122), 100) #self.earth.visible = False #all_sprites.add(self.earth, layer=2) # Uniform def update(self, screenSurface, fpsClock): if pygame.time.get_ticks() - self.lastClockUpdate > 1000: self.stardate.setText("EARTH DATE {}".format(datetime.now().strftime("%m.%d.%y %H:%M:%S"))) self.lastClockUpdate = pygame.time.get_ticks() LcarsScreen.update(self, screenSurface, fpsClock) def handleEvents(self, event, fpsClock): LcarsScreen.handleEvents(self, event, fpsClock) if event.type == pygame.MOUSEBUTTONDOWN: self.beep1.play() if event.type == pygame.MOUSEBUTTONUP: return False # Screen Handlers def logoutHandler(self, item, event, clock): from screens.authorize import ScreenAuthorize self.loadScreen(ScreenAuthorize()) def aboutHandler(self, item, event, clock): from screens.aboutScreen import ScreenAbout self.loadScreen(ScreenAbout()) def demoHandler(self, item, event, clock): from screens.demoScreen import ScreenDemo self.loadScreen(ScreenDemo()) def exploreHandler(self, item, event, clock): from screens.exploreScreen import ScreenExplore self.loadScreen(ScreenExplore())
class MenuState(GameState): PLAY_OPTION = 0 HISCORES_OPTION = 1 EXIT_OPTION = 2 ONE_PLAYER_OPTION = 0 TWO_PLAYERS_OPTION = 1 BACK_OPTION = 2 KONAMI_CODE = (pygame.K_UP, pygame.K_UP, pygame.K_DOWN, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT, pygame.K_LEFT, pygame.K_RIGHT, pygame.K_b, pygame.K_a) def __init__(self, game): super(MenuState, self).__init__(game) # Listen to up, down, and enter and all of the Konami code ones self.set_listen_keys((pygame.K_DOWN, pygame.K_UP, pygame.K_RETURN) + MenuState.KONAMI_CODE) # Konami code step self.konami_code_step = 0 # Model of the menu self.title = GAME_TITLE self.selected = 0 self.hiscore = str(self.game.hiscores.get_hiscore().name) + " - " + str(self.game.hiscores.get_hiscore().score) self.rights = u'\u00a9 Dezassete' self.current_menu_options = None self.main_menu_options = VerticalMenuOptions( ['Play', 'Hi-scores', 'Exit'], self.main_menu_on_click, self.on_change ) self.play_menu_options = VerticalMenuOptions( ['1 Player', '2 Players', 'Back'], self.play_menu_on_click, self.on_change ) # Surfaces self.hiscore_surface = None self.hiscore_label_surface = None self.title_surface = None self.rights_surface = None # Sounds self.select_sound = None def set_listen_keys(self, listen_keys_tuple): listen_keys_list = [] for key in listen_keys_tuple: if key not in listen_keys_list: listen_keys_list.append(key) self.listen_keys = tuple(listen_keys_list) def show(self): # Start the music pygame.mixer.music.load(resources.get_music('whatislove.ogg')) pygame.mixer.music.play(-1) # Get font name font = resources.get_font('prstartcustom.otf') # Make Hi-score and rights font_renderer = pygame.font.Font(font, 12) self.hiscore_label_surface = font_renderer.render('Hi-score', True, NOT_SO_BLACK) self.hiscore_surface = font_renderer.render(self.hiscore, True, NOT_SO_BLACK) self.rights_surface = font_renderer.render(self.rights, True, NOT_SO_BLACK) # Make title font_renderer = pygame.font.Font(font, 36) self.title_surface = font_renderer.render(GAME_TITLE, False, NOT_SO_BLACK) # Make all options and change to the main menu self.play_menu_options.init(font, 15, True, NOT_SO_BLACK) self.main_menu_options.init(font, 15, True, NOT_SO_BLACK) self.change_menu_options(self.main_menu_options) # Load all sounds self.select_sound = Sound(resources.get_sound('menu_select.wav')) def update(self, delta): # Konami code listener for key in self.listen_keys: if self.input.key_clicked(key): if MenuState.KONAMI_CODE[self.konami_code_step] == key: self.konami_code_step += 1 if self.konami_code_step >= len(MenuState.KONAMI_CODE): from state.god_state import GodState self.state_manager.set_state(GodState(self.game)) self.konami_code_step = 0 return else: self.konami_code_step = 0 self.current_menu_options.update(self.input) def render(self, canvas): canvas.fill(NOT_SO_WHITE) # Render hiscore canvas.blit(self.hiscore_label_surface, (GAME_WIDTH / 2 - self.hiscore_label_surface.get_width() / 2, 15)) canvas.blit(self.hiscore_surface, ( GAME_WIDTH / 2 - self.hiscore_surface.get_width() / 2, (self.hiscore_label_surface.get_height() + 15) * 1.2 )) # Render the title surface canvas.blit(self.title_surface, ( GAME_WIDTH / 2 - self.title_surface.get_width() / 2, GAME_HEIGHT / 4 * 1.4 - self.title_surface.get_height() / 2 )) # Render the current options in the middle of the screen self.current_menu_options.render(canvas, GAME_WIDTH / 2, GAME_HEIGHT / 4 * 2.2) # Draw rights canvas.blit(self.rights_surface, ( GAME_WIDTH / 2 - self.rights_surface.get_width() / 2, GAME_HEIGHT - self.rights_surface.get_height() - 15 )) def change_menu_options(self, menu_options): self.current_menu_options = menu_options self.current_menu_options.reset() def main_menu_on_click(self, option): self.select_sound.play() if option == MenuState.EXIT_OPTION: self.game.stop() elif option == MenuState.PLAY_OPTION: self.change_menu_options(self.play_menu_options) elif option == MenuState.HISCORES_OPTION: from state.hiscores_state import HiscoresState self.state_manager.push_overlay(HiscoresState(self.game)) def play_menu_on_click(self, option): self.select_sound.play() if option == MenuState.ONE_PLAYER_OPTION: from state.singleplayer_state import SinglePlayerState self.state_manager.set_state(SinglePlayerState(self.game)) elif option == MenuState.TWO_PLAYERS_OPTION: from state.multiplayer_state import MultiPlayerState self.state_manager.set_state(MultiPlayerState(self.game)) elif option == MenuState.BACK_OPTION: self.change_menu_options(self.main_menu_options) def on_change(self, old_option, new_option): self.select_sound.play() def dispose(self): pygame.mixer.music.stop()
def playSound(filename): soundFile = _rootDir + '/' + filename sound = Sound(soundFile) sound.play()
class ScreenExplore(LcarsScreen): def setup(self, all_sprites): all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_1.png"), layer=0) # panel text all_sprites.add(LcarsText(colours.BLACK, (11, 75), "MOSF"), layer=1) all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "LONG RANGE PROBE", 2.5), layer=1) all_sprites.add(LcarsText(colours.BLACK, (54, 667), "192 168 0 3"), layer=1) # date display self.stardate = LcarsText(colours.BLACK, (444, 506), "", 1) self.lastClockUpdate = 0 all_sprites.add(self.stardate, layer=1) # permanent buttons all_sprites.add(LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler), layer=1) all_sprites.add(LcarsBlockSmall(colours.ORANGE, (211, 16), "ABOUT", self.aboutHandler), layer=1) all_sprites.add(LcarsBlockLarge(colours.BLUE, (145, 16), "DEMO", self.demoHandler), layer=1) all_sprites.add(LcarsBlockHuge(colours.PEACH, (249, 16), "EXPLORE", self.exploreHandler), layer=1) all_sprites.add(LcarsElbow(colours.BEIGE, (400, 16), "MAIN", self.mainHandler), layer=1) # Sounds self.beep1 = Sound("assets/audio/panel/201.wav") #Sound("assets/audio/panel/220.wav").play() ###################################################################### ##### Explore Screen ##### # Explore Screen --------------------------------------------------------------------------------- all_sprites.add(LcarsText(colours.RED_BROWN, (142, 140), "Select a section for more information", 1.25), layer=70) self.explore_screen_text = all_sprites.get_sprites_from_layer(70) # self.hideText(self.explore_screen_text) self.probe_forward_image = LcarsImage("assets/probe_front.png", (172, 500), self.forwardHandler) all_sprites.add(self.probe_forward_image, layer =70) self.probe_aft_image = LcarsImage("assets/probe_rear.png", (172, 150), self.aftHandler) all_sprites.add(self.probe_aft_image, layer=70) ##### Forward Section ##### self.forward_text = LcarsText(colours.RED_BROWN, (142, 140), "Select a component for more information", 1.25) self.forward_text.visible = False all_sprites.add(self.forward_text, layer=71) # self.forward_text.visible = False self.forward_plate = LcarsImage("assets/forward/front_section.png", (172, 150)) self.forward_plate.visible = False all_sprites.add(self.forward_plate, layer =71) ## Back Forward Button ## self.forward_button = LcarsTabBlock(colours.RED_BROWN, (372, 650), "BACK", self.forwardHandler) self.forward_button.visible = False all_sprites.add(self.forward_button, layer=60) ## Back Aft Button ## self.aft_button = LcarsTabBlock(colours.RED_BROWN, (372, 650), "BACK", self.exploreHandler) self.aft_button.visible = False all_sprites.add(self.aft_button, layer=60) # BTO ARRAY # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "B.T.O. ARRAY", 1.75), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "The B.T.O. Array is the primary method of communication for the probe.", 1.25), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "The array is entirely composed of the S.B.S. High-Gain Parabolic Antenna,", 1.25), layer = 61) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "which is capable of simultaneous dual transmission in the S and X bands", 1.25), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "and receipt of control commands in the Ka and Ku bands. The array is", 1.25), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "paired with the Yokel Sensor Suite to determine physical properties of ", 1.25), layer=61) all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "local bodies using microwave radiation.", 1.25), layer=61) self.communication_text = all_sprites.get_sprites_from_layer(61) self.hideText(self.communication_text) # YOKEL SENSOR SUITE # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "YOKEL SENSOR SUITE", 1.75), layer=62) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "The Yokel Sensor Suite houses the scientific payload and guidance", 1.25), layer=62) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "system on the probe. The instruments contained within are:", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (222, 150), "Autonomous Telemetry Guidance Unit", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (242, 150), "Energetic Particle Detector", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (262, 150), "Gravitational Mapping Unit", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (282, 150), "High Energy Multi-Spectral Analyzer", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (302, 150), "Magnetometry Suite", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (322, 150), "Radar Detection & Tracking System", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (342, 150), "Radio Science Array", 1.25), layer=62) all_sprites.add(LcarsText(colours.WHITE, (362, 150), "Space Radiation Measurement System", 1.25), layer=62) all_sprites.add(LcarsText(colours.ORANGE, (392, 140), "Collected data is stored in the Optical Data Chips for later processing.", 1.25), layer=62) self.sensor_text = all_sprites.get_sprites_from_layer(62) self.hideText(self.sensor_text) # Probe Computers # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "PROBE COMPUTERS", 1.75), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "This probe features two onboard computers, the Guidance Computer and", 1.25), layer=63) all_sprites.add(LcarsText(colours.WHITE, (162, 473), "Guidance Computer", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "the Data Processing Unit , which handle all data and control processes.", 1.25), layer=63) all_sprites.add(LcarsText(colours.WHITE, (192, 165), "Data Processing Unit", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "The Guidance Computer receives control commands through the BTO ", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "Array, and local object data from the Yokel Sensor Suite, to ensure safe", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "travel. The Data Processing Unit receives all raw data from the Optical", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "and processes the data for transmission. For redundancy, both", 1.25), layer=63) all_sprites.add(LcarsText(colours.ORANGE, (342, 140), "computers are independently capable of assuming the others' duties.", 1.25), layer=63) self.computer_text = all_sprites.get_sprites_from_layer(63) self.hideText(self.computer_text) # Optical Data Chips # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "OPTICAL DATA CHIPS", 1.75), layer=64) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "This probe is equipped with 24 optical data chips for the storage of sensor", 1.25), layer=64) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "and control data. Each chip, which can store up to 830 TB of data, is", 1.25), layer=64) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "constructed of a nano-structured quartz composite. Data is read/written", 1.25), layer=64) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "to the chips using a Smith-Taylor laser system.", 1.25), layer=64) self.chip_text = all_sprites.get_sprites_from_layer(64) self.hideText(self.chip_text) # Lofton Microfusion Core # all_sprites.add(LcarsText(colours.WHITE, (112, 140), "LOFTON MICROFUSION CORE", 1.75), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "All of the required power for the probe is provided by the Lofton", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "Microfusion Core. Encased within a shielded tungsten-titanium shell,", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "11.3 KW of power are produced from a micro-aneutronic fusion reaction ", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "which is converted to electricity via electrostatic direct conversion.", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "Of the 11.3 KW produced, 8 KW are used by the ion propulsion system,", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "1.4 KW by the sensor suite, 1 KW by the computers, and 0.9 KW by the", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (342, 140), "communication array during normal operation. Helium is used for the", 1.25), layer=65) all_sprites.add(LcarsText(colours.ORANGE, (372, 140), "fusion reaction which is provided by the monopropellant tank.", 1.25), layer=65) self.fusion_text = all_sprites.get_sprites_from_layer(65) self.hideText(self.fusion_text) ###### AFT SECTION ###### all_sprites.add(LcarsText(colours.WHITE, (112, 140), "PROPULSION SYSTEM", 1.75), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (162, 140), "After launch, the probe is driven by the Kehrer Hybrid Ion Drive, is", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (192, 140), "capable of both ion and chemical propulsion, and is comprised of the ", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (222, 140), "engine, thrusters, and fuel tanks. Ion propulsion creates thrust by drawing", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (252, 140), "power from the fusion core to accelerate and expel Xenon ions from the", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (282, 140), "two, 420 kg storage tanks, and is the main method of propulsion. For quick", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (312, 140), "changes in velocity, the chemical propulsion system is activated. This", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (342, 140), "system uses the monopropellant hydrazine, which is stored in the 300 kg ", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (372, 140), "storage tank. The combination of two different propulsion methods allows", 1.25), layer=66) all_sprites.add(LcarsText(colours.ORANGE, (402, 140), "the probe a versatile mix of range and maneuverability.", 1.25), layer=66) self.propulsion_text = all_sprites.get_sprites_from_layer(66) self.hideText(self.propulsion_text) #TEST self.test = LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler) self.test.visible = False all_sprites.add(self.test, layer = 4) def hideText(self, name): if name[0].visible: for sprite in name: sprite.visible = False def showText(self, name): for sprite in name: sprite.visible = True def update(self, screenSurface, fpsClock): if pygame.time.get_ticks() - self.lastClockUpdate > 1000: self.stardate.setText("EARTH DATE {}".format(datetime.now().strftime("%m.%d.%y %H:%M:%S"))) self.lastClockUpdate = pygame.time.get_ticks() LcarsScreen.update(self, screenSurface, fpsClock) def handleEvents(self, event, fpsClock): LcarsScreen.handleEvents(self, event, fpsClock) if event.type == pygame.MOUSEBUTTONDOWN: self.beep1.play() if event.type == pygame.MOUSEBUTTONUP: return False def logoutHandler(self, item, event, clock): # demo() from screens.authorize import ScreenAuthorize self.loadScreen(ScreenAuthorize()) def aboutHandler(self, item, event, clock): # demo() from screens.aboutScreen import ScreenAbout self.loadScreen(ScreenAbout()) def demoHandler(self, item, event, clock): demo(a) # from screens.demoScreen import ScreenDemo # self.loadScreen(ScreenDemo()) def exploreHandler(self, item, event, clock): # demo() # Turn off all content here self.test.visible = False self.loadScreen(ScreenExplore()) def mainHandler(self, item, event, clock): # demo() from screens.main import ScreenMain self.loadScreen(ScreenMain()) ## ****** Explore Screen Handlers ****** # Forward Section forwardHandler # - Open front hatches & activate red interior lighting # Communications Array communicationsHandler # - Illuminate # Sensors Array sensorsHandler # - Change spin speed & light up and down? sonar beep? # Data Acquisition & Processing Node computerHandler # - Illuminate (fiber optic lighting) # Optical Data Storage Modules chipsHandler # - Pulse # Power System powerHandler # - Pulse # Aft Section aftHandler # - Open rear hatches # Ion Thrusters thrustersHandler # - Pulse (have 2 LED colors, Red & Blue) # Ion Drive driveHandler # - Pulse (have 2 LED colors, Red & Blue) # Fuel Tanks tanksHandler # - illumate section by section # Impulse Chemical Reaction Tank impulseHandler # - Illuminate # ** Main ** def forwardHandler(self, item, event, clock): self.hideText(self.explore_screen_text) self.probe_forward_image.visible = False self.probe_aft_image.visible = False self.hideText(self.propulsion_text) self.forward_button.visible = False self.hideText(self.communication_text) self.hideText(self.sensor_text) self.hideText(self.computer_text) self.hideText(self.chip_text) self.hideText(self.fusion_text) # self.showText(self.forward_text) self.forward_text.visible = True # self.aft_button.visible = True #Put others here self.forward_plate.visible = True def aftHandler(self, item, event, clock): self.hideText(self.explore_screen_text) self.probe_forward_image.visible = False self.probe_aft_image.visible = False self.showText(self.propulsion_text) self.aft_button.visible = False door_br(a, 1) door_bl(a, 1) for i in range(60, 0, -15): blue_thruster(a, 1) time.sleep(float(i)/100) red_thruster(a, 1) time.sleep(float(i)/200) blue_thruster(a, 0) time.sleep(float(i)/100) red_thruster(a, 0) blue_thruster(a, 1) red_thruster(a, 1) time.sleep(2) areset(a) # ** Forward ** def communicationsHandler(self, item, event, clock): self.showText(self.communication_text) self.aft_button.visible = False self.forward_button.visible = True def sensorsHandler(self, item, event, clock): self.showText(self.sensor_text) self.aft_button.visible = False self.forward_button.visible = True def computerHandler(self, item, event, clock): self.showText(self.computer_text) self.aft_button.visible = False self.forward_button.visible = True def chipsHandler(self, item, event, clock): self.showText(self.chip_text) self.aft_button.visible = False self.forward_button.visible = True def powerHandler(self, item, event, clock): self.showText(self.fusion_text) self.aft_button.visible = False self.forward_button.visible = True # ** Aft ** def thrustersHandler(self, item, event, clock): self.test.visible = False def driveHandler(self, item, event, clock): self.test.visible = False def tanksHandler(self, item, event, clock): self.test.visible = False def impulseHandler(self, item, event, clock): self.test.visible = False def backForwardHandler(self, item, event, clock): self.test.visible = False def moreSensorHandler(self, item, event, clock): self.test.visible = False
class Menu: __metaclass__ = ABCMeta def __init__(self, components, state): self.state_manager = state.state_manager self.state = state self.active_component = 0 self.components = components for component in components: component.active = False self.components[self.active_component].active = True self.disable_update = [VerticalMenuOptions] # Sounds self.select_sound = None def init(self): # Initialize sounds self.select_sound = Sound(resources.get_sound('menu_select.wav')) def update(self, input_handler, delta): # If active component is not in the disabled classes for update, update it and only update the components in # the next loop to consume the events active_component = self.components[self.active_component] if not any([isinstance(active_component, disable_class) for disable_class in self.disable_update]): if input_handler.key_clicked(pygame.K_UP): self.move_up() return if input_handler.key_clicked(pygame.K_DOWN): self.move_down() return # Update menu components self.update_menu(input_handler, delta) def move_up(self): self.select_sound.play() if self.active_component != 0: self.components[self.active_component].active = False self.active_component -= 1 self.components[self.active_component].active = True def move_down(self): self.select_sound.play() if self.active_component != len(self.components) - 1: self.components[self.active_component].active = False self.active_component += 1 self.components[self.active_component].active = True @abstractmethod def update_menu(self, input_handler, delta): pass @abstractmethod def render(self, canvas): pass @abstractmethod def dispose(self): pass
class MultiPlayerState(GameState): def __init__(self, game): super(MultiPlayerState, self).__init__(game) self.listen_keys = (pygame.K_ESCAPE,) self.player1 = Player(game.input, PLAYER1, Pad(Vector2(GAME_WIDTH - PAD_DISTANCE - PAD_WIDTH, GAME_HEIGHT/2 - PAD_HEIGHT/2), dash_direction=PLAYER1_DASH), MULTIPLAYER_LIVES) self.player2 = Player(game.input, PLAYER2, Pad(Vector2(0 + PAD_DISTANCE, GAME_HEIGHT/2 - PAD_HEIGHT/2), dash_direction=PLAYER2_DASH), MULTIPLAYER_LIVES) self.balls = [] self.powerups = [] self.time_since_powerup_check = 0 self.winner = None self.instructions = True # Text rendering self.font = None self.font_renderer = None # Player 1 Text self.player1_lives_label_surface = None self.player1_lives_surface = None self.player1_charge_label_surface = None self.player1_charge_surface = None # Player 2 Text self.player2_lives_label_surface = None self.player2_lives_surface = None self.player2_charge_label_surface = None self.player2_charge_surface = None # Sounds self.wall_hit_sound = None self.pad_hit_sound = None self.powerup_sound = None def show(self): # Start the music pygame.mixer.music.load(resources.get_music('mortalkombat.ogg')) pygame.mixer.music.play(-1) self.font = resources.get_font('prstartcustom.otf') self.font_renderer = pygame.font.Font(self.font, 12) # Player 1 Text self.player1_lives_label_surface = self.font_renderer.render('Lives: ', True, NOT_SO_BLACK) self.player1_lives_surface = self.font_renderer.render(str(self.player1.lives), True, NOT_SO_BLACK) self.player1_charge_label_surface = self.font_renderer.render('Charge: ', True, NOT_SO_BLACK) self.player1_charge_surface = self.font_renderer.render(str(self.player1.pad.charge), True, NOT_SO_BLACK) # Player 2 Text self.player2_lives_label_surface = self.font_renderer.render('Lives: ', True, NOT_SO_BLACK) self.player2_lives_surface = self.font_renderer.render(str(self.player2.lives), True, NOT_SO_BLACK) self.player2_charge_label_surface = self.font_renderer.render('Charge: ', True, NOT_SO_BLACK) self.player2_charge_surface = self.font_renderer.render(str(self.player2.pad.charge), True, NOT_SO_BLACK) # Initialize the sounds self.wall_hit_sound = Sound(resources.get_sound('on_wall_hit.wav')) self.pad_hit_sound = Sound(resources.get_sound('on_pad_hit.wav')) self.powerup_sound = Sound(resources.get_sound('powerup.wav')) def add_listeners(self): super(MultiPlayerState, self).add_listeners() self.player1.add_listeners() self.player2.add_listeners() def update(self, delta): if self.instructions: pygame.time.wait(4750) self.instructions = False pygame.time.wait(250) self.game.logic_clock.tick() self.balls = [Ball()] # Check if paused if self.input.key_clicked(pygame.K_ESCAPE): from pause_state import PauseState self.state_manager.push_overlay(PauseState(self.game, MultiPlayerState(self.game))) return # Check pads self.player1.update(delta) self.check_upper_bottom_boundaries(self.player1.pad) self.player2.update(delta) self.check_upper_bottom_boundaries(self.player2.pad) # Increment counter self.time_since_powerup_check += delta if self.time_since_powerup_check > POWERUP_TIMER: if len(self.powerups) < POWERUP_MAX and randint(0, POWERUP_PROBABILITY) == 0: self.powerups += [PowerUp.get_random_powerup((randint(GAME_WIDTH * 0.3, GAME_WIDTH * 0.7), randint(POWERUP_SIZE, GAME_HEIGHT - POWERUP_SIZE)))] self.time_since_powerup_check = 0 # Check balls for b in self.balls: b.update(delta) # Check each ball if self.check_upper_bottom_boundaries(b): self.on_wall_hit() # Check each pad for p in (self.player1, self.player2): if self.check_entity_collision(delta, p.pad, b): self.on_pad_hit() self.calculate_collision(p.pad, b) if b.velocity.x < BALL_SPEED_LIMIT: b.velocity.x *= BALL_SPEED_MULTIPLIER else: b.velocity.x /= BALL_SPEED_MULTIPLIER # Transfer a portion of the speed to the ball b.velocity.y += BALL_SPEED_TRANSFER * p.pad.velocity.y b.velocity.x += BALL_SPEED_TRANSFER_DASH * p.pad.velocity.x # Add dash charge to the pad if p.pad.charge < PAD_MAX_CHARGE: p.pad.charge += p.pad.charging_rate if b.stunning and randint(0, 4) == 0: b.stunning = False p.pad.stunned = True p.pad.stunned_timer = POWERUP_STUN_DURATION b.owner = p break # Check each powerup if b.owner != None: for p in self.powerups: if self.check_entity_collision(delta, p, b): self.on_powerup() p.apply(self, b) self.powerups.remove(p) break # Check scoring if self.check_left_boundary(b, self.player1, self.player2) or \ self.check_right_boundary(b, self.player1, self.player2): with self.game.rendering: self.balls.remove(b) if not self.balls: self.balls += [Ball()] break def check_upper_bottom_boundaries(self, entity): # Check top boundary if entity.position.y < 0: entity.position.y *= -1 entity.velocity.y *= -1 return True # Check bottom boundary elif entity.position.y + entity.height > GAME_HEIGHT: entity.position.y -= (entity.position.y + entity.height - GAME_HEIGHT)*2 entity.velocity.y *= -1 return True return False def check_right_boundary(self, ball, player1, player2): if ball.position.x + ball.width >= GAME_WIDTH: player1.lives -= ball.damage if player1.lives <= 0: self.winner = player2 pygame.time.wait(5000) from menu_state import MenuState self.state_manager.set_state(MenuState(self.game)) return True return False def check_left_boundary(self, ball, player1, player2): if ball.position.x <= 0: player2.lives -= ball.damage if player2.lives <= 0: self.winner = player1 pygame.time.wait(5000) from menu_state import MenuState self.state_manager.set_state(MenuState(self.game)) return True return False def check_entity_collision(self, delta, static, moving): # Maybe a collision should've happened but wasn't detected i = 0 collision = False virtualmoving = VirtualEntity(moving.position-delta*moving.velocity, width=moving.width, height=moving.height, velocity=moving.velocity) virtualstatic = VirtualEntity(static.position-delta*static.velocity, width=static.width, height=static.height, velocity=static.velocity) while not(collision) and i < COLLISION_INTERPOLATION: virtualmoving.update(delta/COLLISION_INTERPOLATION) virtualstatic.update(delta/COLLISION_INTERPOLATION) collision = virtualmoving.get_bounds().colliderect(virtualstatic.get_bounds()) i += 1 # We were right! if collision: # Copy the virtual ball's variables moving.position = virtualmoving.position moving.velocity = virtualmoving.velocity moving.update_bounds() return collision def calculate_collision(self, entity, point): entity_angle = math.atan2(entity.height/2, entity.width/2) collision_angle = math.atan2(entity.bounds.centery - point.bounds.centery, point.bounds.centerx - entity.bounds.centerx) + entity_angle if collision_angle < 0: collision_angle += 2*math.pi if collision_angle < 2*entity_angle or (point.velocity.x < 0 and collision_angle < math.pi+2*entity_angle): point.position.x = entity.position.x + entity.width point.velocity.x *= -1 elif collision_angle < math.pi: point.position.y = entity.position.y - point.height point.velocity.y *= -1 elif collision_angle < math.pi+2*entity_angle or (point.velocity.x > 0 and collision_angle < 2*entity_angle): point.position.x = entity.position.x - point.width point.velocity.x *= -1 elif collision_angle < 2*math.pi: point.position.y = entity.position.y + entity.height point.velocity.y *= -1 def render(self, canvas): canvas.fill(NOT_SO_WHITE) if self.instructions: font = resources.get_font('prstartcustom.otf') font_renderer = pygame.font.Font(self.font, 10) font_renderer_large = pygame.font.Font(self.font, 18) fight_surface = font_renderer_large.render("PREPARE TO FIGHT.", True, NOT_SO_BLACK) instructions_player1_1_surface = font_renderer.render("USE THE UP & DOWN ARROW KEYS", True, NOT_SO_BLACK) instructions_player1_2_surface = font_renderer.render("USE LEFT ARROW KEY TO DASH", True, NOT_SO_BLACK) instructions_player2_1_surface = font_renderer.render("USE W & S", True, NOT_SO_BLACK) instructions_player2_2_surface = font_renderer.render("USE D TO DASH", True, NOT_SO_BLACK) goodluck_surface = font_renderer_large.render("GOOD LUCK.", True, NOT_SO_BLACK) canvas.blit(fight_surface, (GAME_WIDTH/2 - fight_surface.get_width()/2, GAME_HEIGHT/4)) canvas.blit(instructions_player1_1_surface, (2.57*GAME_WIDTH/4 - instructions_player1_1_surface.get_width()/2, GAME_HEIGHT/2 - instructions_player1_1_surface.get_height()/2 - 10)) canvas.blit(instructions_player1_2_surface, (2.57*GAME_WIDTH/4 - instructions_player1_2_surface.get_width()/2, GAME_HEIGHT/2 + 10)) canvas.blit(instructions_player2_1_surface, (GAME_WIDTH/4 - instructions_player2_1_surface.get_width()/2, GAME_HEIGHT/2 - instructions_player1_2_surface.get_height()/2 - 10)) canvas.blit(instructions_player2_2_surface, (GAME_WIDTH/4 - instructions_player2_2_surface.get_width()/2, GAME_HEIGHT/2 + 10)) canvas.blit(goodluck_surface, (GAME_WIDTH/2 - goodluck_surface.get_width()/2, 3*GAME_HEIGHT/4)) return elif self.winner is not None: if self.winner is self.player1: winner = "PLAYER ONE (RIGHT)" else: winner = "PLAYER TWO (LEFT)" font = resources.get_font('prstartcustom.otf') font_renderer = pygame.font.Font(self.font, 18) end_surface = font_renderer.render(winner + " IS VICTORIOUS", True, NOT_SO_BLACK) canvas.blit(end_surface, (GAME_WIDTH/2 - end_surface.get_width()/2, GAME_HEIGHT/2 - end_surface.get_height()/2)) return self.player1.render(canvas) self.player2.render(canvas) for b in self.balls: b.render(canvas) for p in self.powerups: p.render(canvas) # Render player 1 Text self.player1_lives_surface = self.font_renderer.render(str(self.player1.lives), True, NOT_SO_BLACK) self.player1_charge_surface = self.font_renderer.render(str(100*self.player1.pad.charge/PAD_MAX_CHARGE) + '%', True, NOT_SO_BLACK) canvas.blit(self.player1_lives_label_surface, (GAME_WIDTH - 20 - self.player1_lives_surface.get_width() - self.player1_lives_label_surface.get_width(), 15)) canvas.blit(self.player1_lives_surface, (GAME_WIDTH - 20 - self.player1_lives_surface.get_width(), 15)) canvas.blit(self.player1_charge_label_surface, (GAME_WIDTH - 20 - self.player1_charge_surface.get_width() - self.player1_charge_label_surface.get_width(), 35)) canvas.blit(self.player1_charge_surface, (GAME_WIDTH - 20 - self.player1_charge_surface.get_width(), 35)) # Render player 2 Text self.player2_lives_surface = self.font_renderer.render(str(self.player2.lives), True, NOT_SO_BLACK) self.player2_charge_surface = self.font_renderer.render(str(100*self.player2.pad.charge/PAD_MAX_CHARGE) + '%', True, NOT_SO_BLACK) canvas.blit(self.player2_lives_label_surface, (20, 15)) canvas.blit(self.player2_lives_surface, (20 + self.player2_lives_label_surface.get_width(), 15)) canvas.blit(self.player2_charge_label_surface, (20, 35)) canvas.blit(self.player2_charge_surface, (20 + self.player2_charge_label_surface.get_width(), 35)) def on_wall_hit(self): self.wall_hit_sound.play() def on_pad_hit(self): self.pad_hit_sound.play() def on_powerup(self): self.powerup_sound.play() def remove_listeners(self): super(MultiPlayerState, self).remove_listeners() self.player1.remove_listeners() self.player2.remove_listeners() def dispose(self): pygame.mixer.music.stop()
class Rocket: def __init__(self, obj_file, gravity, maximum_speed, maximum_acceleration, maximum_roll_rate, controls, blaster_list, blaster_color): self.gravity=gravity self.maximum_speed=maximum_speed self.maximum_acceleration=maximum_acceleration self.maximum_roll_rate=maximum_roll_rate self.controls=controls self.blaster_list=blaster_list self.blaster_color=blaster_color self.angle=0.0 self.model=OBJ(config.basedir+"/assets", obj_file) self.position=Vector2D(0.0,0.0) self.velocity=Vector2D(0.0,0.0) self.bounding_box=BoundingPolygon( (Vector2D(-1.0, 1.0), Vector2D(1.0, 1.0), Vector2D(1.0, -1.0), Vector2D(0.0, -2.0), Vector2D(-1.0, -1.0)) ) self.weight=1.0 self.beam=Beam() self.plume=Plume() self.blaster_sound=Sound(config.basedir+"/assets/Laser_Shoot_2.wav") self.engine_sound=Sound(config.basedir+"/assets/engine.wav") self.engine_sound.set_volume(0.075) self.fire_counter=3 @gl_utilities.sprites_configuration def _draw_sprites(self): self.beam.draw() self.plume.draw() @gl_utilities.shader_configuration(config.basedir+"/shaders/vertex.txt", config.basedir+"/shaders/fragment.txt") def _draw_shader(self): glPushMatrix() glRotate(self.angle,0.0,0.0,1.0) glRotate(90.0,-1.0,0.0,0.0) glCallList(self.model.gl_list) glPopMatrix() def draw(self): glPushMatrix() glTranslate(-self.position.x, -self.position.y, 0.0) self._draw_sprites() self._draw_shader() glPopMatrix() # _draw_bounding_box(self.bounding_box) def _fire(self): # angle, position, blaster_color, blaster_list): direction=Vector2D(math.sin(math.radians(self.angle)), -math.cos(math.radians(self.angle))) self.blaster_list.append(Blaster(self.blaster_color, self.position+2.001*direction, direction)) def update(self,clock): seconds_passed=clock.get_time()/1000.0 self.angle += (self.maximum_roll_rate* self.controls.get_rotate()* seconds_passed) if 0 < self.controls.get_throttle(): if self.plume.is_off(): self.plume.on() self.engine_sound.play() self.plume.throttle=self.controls.get_throttle() thrust=self.maximum_acceleration*seconds_passed*self.plume.throttle accel=Vector2D(math.sin(math.radians(self.angle))*thrust, -math.cos(math.radians(self.angle))*thrust) self.velocity += accel elif self.controls.get_throttle() <= 0 and self.plume.is_on(): self.plume.off() self.engine_sound.stop() self.velocity += self.gravity*seconds_passed speed = self.velocity.length() if self.maximum_speed < speed: self.velocity *= self.maximum_speed/speed self.position += self.velocity*seconds_passed self.bounding_box.position=self.position self.bounding_box.angle=self.angle self.bounding_box.update() if self.controls.get_beam_activated() and self.beam.is_off(): tmp_beam_angle = self.controls.get_beam_angle() if tmp_beam_angle is None: self.beam.angle = self.angle + 90 else: self.beam.angle = math.degrees(tmp_beam_angle) self.beam.on() elif not self.controls.get_beam_activated(): self.beam.off() if self.controls.fire() or (0 < self.fire_counter < 3) : if 0 < self.fire_counter: self.blaster_sound.play() self._fire() self.fire_counter -= 1 else: self.fire_counter=3 self.beam.update(clock) self.plume.update(clock) self.plume.angle = self.angle if self.beam.is_on() and not self.beam.is_extending(): self.beam.off()
class HiscoresState(GameState): def __init__(self, game): super(HiscoresState, self).__init__(game) # Listen to escape only self.listen_keys = (pygame.K_ESCAPE, pygame.K_LEFT, pygame.K_RIGHT, pygame.K_RETURN) # Model of the hiscores self.scores = self.hiscores.get_scores(10) self.back_options = HorizontalMenuOptions(['Back'], self.on_click, self.on_change, True, False) # Surfaces self.title_surface = None self.scores_surfaces = [] # Sounds self.select_sound = None def show(self): font = resources.get_font('prstartcustom.otf') # Make title font_renderer = pygame.font.Font(font, 15) self.title_surface = font_renderer.render('Hi-scores', True, NOT_SO_BLACK) # Make all scores # Get the score with highest width max_width_score = max(self.scores, key=self.score_width) # Calculate its width, and add 4 dots max_width = self.score_width(max_width_score) + 4 font_renderer = pygame.font.Font(font, 12) for score in self.scores: self.scores_surfaces.append( font_renderer.render( score.name + '.' * (max_width - self.score_width(score)) + str(score.score), True, NOT_SO_BLACK ) ) # Make the back option self.back_options.init(font, 15, True, NOT_SO_BLACK) # Load all sounds self.select_sound = Sound(resources.get_sound('menu_select.wav')) def update(self, delta): self.back_options.update(self.input) def render(self, canvas): canvas.fill(NOT_SO_WHITE) # Draw title canvas.blit(self.title_surface, (GAME_WIDTH / 2 - self.title_surface.get_width() / 2, 30)) # Draw scores for i in range(len(self.scores_surfaces)): score_surface = self.scores_surfaces[i] surface_x = GAME_WIDTH / 2 - score_surface.get_width() / 2 surface_y = i * score_surface.get_height() * 1.8 + (self.title_surface.get_height() + 15) * 2.5 canvas.blit(score_surface, (surface_x, surface_y)) # Draw back option self.back_options.render(canvas, GAME_WIDTH * 0.80, GAME_HEIGHT - 20 - self.back_options.get_height()) def score_width(self, score): return len(score.name) + len(str(score.score)) def on_click(self, option): self.select_sound.play() from menu_state import MenuState self.state_manager.pop_overlay() def on_change(self, old_option, new_option): self.select_sound.play() def dispose(self): pass
class SoundControl(object): def __init__(self, serial_port, data_folder): self.lightning = SocketControl(serial_port) self._data_folder = data_folder self._rain = Sound("%s/rain.wav" % data_folder) self._thunder = 0 self._last = 0 self.lightning.set_B(ON) self.lightning.send() def rain(self): self._rain.play(-1) def exit(self, time): pygame.mixer.fadeout(time) def smoke(self): self.lightning.set_A(ON) self.lightning.send() time.sleep(0.3) self.lightning.set_A(OFF) self.lightning.send() # 0 - 6 def thunder(self, inc): wait = random.randint(0, 2+inc) while (self._last == wait): wait = random.randint(0, 2+inc) self._last = wait print "intensity:", wait thunder = Sound("%s/thunder_0%d.wav" % (self._data_folder, wait)) if wait < 6: self.lightning.set_C(ON) self.lightning.send() time.sleep(random.uniform(0.5, 1.5)) self.lightning.set_C(OFF) self.lightning.send() time.sleep(wait) if wait < 6: self.lightning.set_B(OFF) self.lightning.send() thunder.play() if wait < 6: time.sleep(0.3) self.lightning.set_B(ON) self.lightning.send() time.sleep(thunder.get_length()-0.3) thunder.fadeout(200) time.sleep(wait) def devil(self): self.lightning.set_A(ON) self.lightning.set_C(ON) self.lightning.send() poodle = Sound("%s/poodle.wav" % (self._data_folder)) poodle.play() time.sleep(0.3) self.lightning.set_A(OFF) self.lightning.send() time.sleep(0.7) for i in range(10): wait = random.randint(0, 3) while self._last == wait: wait = random.randint(0, 3) print "devil intensity:", wait self._last = wait thunder = Sound("%s/thunder_0%d.wav" % (self._data_folder, wait)) thunder.play() if wait < 2: off_for = 0.05 + random.random() * 0.3 print "flicker for", off_for self.lightning.set_B(OFF) self.lightning.send() time.sleep(off_for) self.lightning.set_B(ON) self.lightning.send() time.sleep(2) self.lightning.set_C(OFF) self.lightning.send() time.sleep(1) self.lightning.set_B(ON) self.lightning.send()
from math import sin, pi samp_freq = 44100 pygame.mixer.pre_init(frequency=samp_freq, channels=1) pygame.mixer.init() GPIO.setmode(GPIO.BCM) wasPressed = 0 #initialize pins GPIO_IN = [21] sound1 = Sound("coin-drop-1.wav") sound2 = [sin(i) for i in np.arange(0,2*pi,2*pi/samp_freq)] for pin in GPIO_IN: GPIO.setup(pin, GPIO.IN) while True: val = GPIO.input(21) print val if val == 1 and wasPressed == 0: wasPressed=1 sound1.play() print 'played' elif val == 0 and wasPressed == 1: wasPressed = 0 print 'released' time.sleep(1.0/float(samp_freq))
def play_sound(self, filename): print "playing %s" % filename sound = Sound(filename) channel = sound.play() self.currently_playing_sound = {'sound': sound, 'channel': channel}
import pygame.mixer from pygame.mixer import Sound import time from gpiozero import MotionSensor from gpiozero import Button from signal import pause pygame.mixer.init() pir = MotionSensor(4) button = Button(2) drum = Sound("test/ka_ru_na_2.wav") while True: button.when_pressed = drum.play time.sleep(4) if pir.motion_detected: drum.play() print("Motion Detect!: !") time.sleep(4)
class ScreenMain(LcarsScreen): def setup(self, all_sprites): all_sprites.add(LcarsBackgroundImage("assets/lcars_screen_1b.png"), layer=0) # panel text all_sprites.add(LcarsText(colours.BLACK, (11, 52), "LCARS 105"), layer=1) all_sprites.add(LcarsText(colours.ORANGE, (0, 135), "HOME AUTOMATION", 2), layer=1) all_sprites.add(LcarsText(colours.BLACK, (183, 74), "LIGHTS"), layer=1) all_sprites.add(LcarsText(colours.BLACK, (222, 57), "CAMERAS"), layer=1) all_sprites.add(LcarsText(colours.BLACK, (372, 70), "ENERGY"), layer=1) all_sprites.add(LcarsText(colours.BLACK, (444, 612), "192 168 0 3"), layer=1) # info text all_sprites.add(LcarsText(colours.WHITE, (192, 174), "EVENT LOG:", 1.5), layer=3) all_sprites.add(LcarsText(colours.BLUE, (244, 174), "2 ALARM ZONES TRIGGERED", 1.5), layer=3) all_sprites.add(LcarsText(colours.BLUE, (286, 174), "14.3 kWh USED YESTERDAY", 1.5), layer=3) all_sprites.add(LcarsText(colours.BLUE, (330, 174), "1.3 Tb DATA USED THIS MONTH", 1.5), layer=3) self.info_text = all_sprites.get_sprites_from_layer(3) # date display self.stardate = LcarsText(colours.BLUE, (12, 380), "STAR DATE 2711.05 17:54:32", 1.5) self.lastClockUpdate = 0 all_sprites.add(self.stardate, layer=1) # buttons all_sprites.add(LcarsButton(colours.RED_BROWN, (6, 662), "LOGOUT", self.logoutHandler), layer=4) all_sprites.add(LcarsButton(colours.BEIGE, (107, 127), "SENSORS", self.sensorsHandler), layer=4) all_sprites.add(LcarsButton(colours.PURPLE, (107, 262), "GAUGES", self.gaugesHandler), layer=4) all_sprites.add(LcarsButton(colours.PEACH, (107, 398), "WEATHER", self.weatherHandler), layer=4) # gadgets all_sprites.add(LcarsGifImage("assets/gadgets/fwscan.gif", (277, 556), 100), layer=1) self.sensor_gadget = LcarsGifImage("assets/gadgets/lcars_anim2.gif", (235, 150), 100) self.sensor_gadget.visible = False all_sprites.add(self.sensor_gadget, layer=2) self.dashboard = LcarsImage("assets/gadgets/dashboard.png", (187, 232)) self.dashboard.visible = False all_sprites.add(self.dashboard, layer=2) self.weather = LcarsImage("assets/weather.jpg", (188, 122)) self.weather.visible = False all_sprites.add(self.weather, layer=2) #all_sprites.add(LcarsMoveToMouse(colours.WHITE), layer=1) self.beep1 = Sound("assets/audio/panel/201.wav") Sound("assets/audio/panel/220.wav").play() def update(self, fpsClock): if pygame.time.get_ticks() - self.lastClockUpdate > 1000: self.stardate.setText("STAR DATE {}".format(datetime.now().strftime("%d%m.%y %H:%M:%S"))) self.lastClockUpdate = pygame.time.get_ticks() LcarsScreen.update(self, fpsClock) def handleEvents(self, event, fpsClock): LcarsScreen.handleEvents(self, event, fpsClock) if event.type == pygame.MOUSEBUTTONDOWN: self.beep1.play() if event.type == pygame.MOUSEBUTTONUP: return False def hideInfoText(self): if self.info_text[0].visible: for sprite in self.info_text: sprite.visible = False def gaugesHandler(self, item, event, clock): self.hideInfoText() self.sensor_gadget.visible = False self.dashboard.visible = True self.weather.visible = False def sensorsHandler(self, item, event, clock): self.hideInfoText() self.sensor_gadget.visible = True self.dashboard.visible = False self.weather.visible = False def weatherHandler(self, item, event, clock): self.hideInfoText() self.sensor_gadget.visible = False self.dashboard.visible = False self.weather.visible = True def logoutHandler(self, item, event, clock): from screens.authorize import ScreenAuthorize self.loadScreen(ScreenAuthorize())