Beispiel #1
0
    def _event_polling(self, task):
        event_name = ""
        value = None
        for ev in pygame.event.get():
            if ev.type is pygame.JOYBUTTONDOWN or ev.type is pygame.JOYBUTTONUP:
                event_name = 'joystick%d-button%d' % (ev.joy, ev.button)
                value = ev.type is pygame.JOYBUTTONDOWN
            elif ev.type is pygame.JOYAXISMOTION:
                event_name = 'joystick%d-axis%d' % (ev.joy, ev.axis)
                value = ev.value

            in_game_name = self.events_dict.get(event_name, None)
            if in_game_name is not None:
                t0 = self.gameEngine.get_time(round_result=False)
                if event_name in self.times:
                    dt = t0 - self.times[event_name]
                else:
                    dt = 10.
                self.times[event_name] = t0

                if dt > self.firewall_time:
                    # if it is a switch, we just reverse its value
                    if in_game_name.startswith("s_"):
                        value = not self._hardware_state(in_game_name)
                    self.tasks[event_name] = self.gameEngine.task_mgr.do_method_later(1.1 * self.firewall_time,
                                                                                      self._process_event,
                                                                                      name=event_name,
                                                                                      extraArgs=[in_game_name, value])
                else:
                    # firewall !
                    if self.tasks[event_name] is not None:
                        if self.gameEngine.params("show_buttons_ghosts"):
                            Logger.warning("possible ghost from", event_name)
                        self.tasks[event_name].remove()
        return task.cont
Beispiel #2
0
    def play(self, name, loop=False, volume=None):
        if name in self._sounds:
            sound = self._sounds[name]

            # avoid playing the same sound many times
            if name == self._last_played and sound.status() == sound.PLAYING:
                return

            if loop:
                sound.setLoop(True)
            if volume is not None:
                sound.setVolume(volume)
            if name in self._protected_sounds or (
                    self.gameEngine.params("voice_sound_do_not_overlap") and ("voice" in name or "human" in name)):
                self._queue.append(sound)
                self._last_played = name
                if not self._is_playing:
                    self._start_next()
            else:
                self._last_played = name
                sound.play()
        elif name == "bips":
            self.play_bips()
        else:
            Logger.warning("Sound", name, "does not exists.")
Beispiel #3
0
 def check_constrained_led(self, event_name, value):
     if event_name in self.controlled_leds:
         if value:
             Logger.info("setting led", event_name, "on")
             self.set_led_on(self.controlled_leds[event_name])
         else:
             Logger.info("setting led", event_name, "off")
             self.set_led_off(self.controlled_leds[event_name])
Beispiel #4
0
    def __init__(self, gameEngine):
        self.task_mgr = gameEngine.task_mgr
        self.gameEngine = gameEngine
        ports = list(serial.tools.list_ports.comports())
        self.board = None
        for p in ports:
            Logger.info(p, p[2], 'description :', p.description)
            if "ttyACM0" in p.description:
                self.board = serial.Serial(p[0], 9600, timeout=5)

        if self.board is None:
            Logger.warning("no arduino connected !")
        else:
            if self.board.isOpen():
                Logger.info("port is open. Closing it")
                self.board.close()

            Logger.info("opening the port")
            self.board.open()

        time.sleep(1.0)
        self.all_off()
Beispiel #5
0
    def update_hard_state(self, state_key, value, silent=False):
        """
        Update a hardware state of the shuttle and tells the game that the shuttle is updated. This can only append if
        the variable 'listen_to_hardware' is set to True. In this case, the game checks if a leds corresponds to this
        new hardware states and switch it on/off. If the hardware states correspnds to a software one, the corresponding
        software state is automatically updated.

        @param state_key: must be one of the strings defined in self.game_states
        @param value: the new value (int, float, bool or string depending on the state_key)
        @param silent: if True, no automatic sound is played. Otherwise, the game searches for a sound corresponding to the new state of the soft_state and plays it.
        @return: True if the state exists. False otherwise
        """
        if state_key == "b_admin":
            self.hard_states[state_key] = value
            # always listen to it
            self.scenario.update_shuttle_state()

        # only do it if the key exists and if we listen to hardware and if the value is different from the previous one (to avoid spamminf of joysticks_axis = 0.0
        elif state_key in self.hard_states and self.get_soft_state(
                "listen_to_hardware") and value != self.hard_states[state_key]:
            Logger.print("(hard_state): ",
                         state_key,
                         ':',
                         value,
                         color='yellow')
            self.hard_states[state_key] = value

            # check if it is associated to one led
            self.hardware.check_constrained_led(state_key, value)

            # maybe it plays an automatic sound
            if not silent:
                if value:
                    self.sound_manager.play(state_key + "_on")
                else:
                    self.sound_manager.play(state_key + "_off")

            self.scenario.update_shuttle_state()

            # particular cases:
            if state_key == "b_freq_moins" and value:
                self.update_soft_state("freq_comm",
                                       self.get_soft_state("freq_comm") -
                                       self.params("freq_comm_increment"),
                                       silent=silent)
            elif state_key == "b_freq_plus" and value:
                self.update_soft_state("freq_comm",
                                       self.get_soft_state("freq_comm") +
                                       self.params("freq_comm_increment"),
                                       silent=silent)
            elif state_key == "b_stop_shuttle" and value:
                self.shuttle.stop()
            elif state_key == "j_sp_orientation_h":
                if value > 0 and self.get_soft_state("offset_ps_x") < 10:
                    self.update_soft_state("offset_ps_x",
                                           self.get_soft_state("offset_ps_x") +
                                           1,
                                           silent=silent)
                elif value < 0 and self.get_soft_state("offset_ps_x") > -10:
                    self.update_soft_state("offset_ps_x",
                                           self.get_soft_state("offset_ps_x") -
                                           1,
                                           silent=silent)
            elif state_key == "j_sp_orientation_v":
                if value > 0 and self.get_soft_state("offset_ps_y") < 10:
                    self.update_soft_state("offset_ps_y",
                                           self.get_soft_state("offset_ps_y") +
                                           1,
                                           silent=silent)
                elif value < 0 and self.get_soft_state("offset_ps_y") > -10:
                    self.update_soft_state("offset_ps_y",
                                           self.get_soft_state("offset_ps_y") -
                                           1,
                                           silent=silent)
            elif state_key[:-1] == 's_pilote_automatique':
                other = 's_pilote_automatique1' if state_key[
                    -1] == '2' else 's_pilote_automatique2'
                if value and self.get_hard_state(other):
                    self.update_soft_state("pilote_automatique",
                                           True,
                                           silent=silent)
                elif not value and not self.get_hard_state(other):
                    self.update_soft_state("pilote_automatique",
                                           False,
                                           silent=silent)
            else:
                # now check if it controls a software value
                self.update_soft_state(state_key.split('_', 1)[1], value)

            return True
        return False
Beispiel #6
0
    def update_soft_state(self,
                          state_key,
                          value,
                          force_power=False,
                          silent=False):
        """
        Update a software state of the shuttle and tells the game that the shuttle is updated.
        If this acton requires some power, the engine checks if this action can be performed and update the shuttle power.
        Depending on the name of state, some action are performed and the shuttle is correctly updated.

        @param state_key: must be one of the strings defined in self.game_states
        @param value: the new value (int, float, bool or string depending on the state_key)
        @param force_power: If this action consumes some power, set is to True to ignore the power limits.
        @param silent: if True, no automatic sound is played. Otherwise, the game searches for a sound corresponding to the new state of the soft_state and plays it.
        @return: True if the state exists. False otherwise
        """
        if state_key in self.soft_states:
            if (not self.params("use_power") or force_power or not value or (
                    value and self.params("use_power") and self.power.can_be_switched_on(state_key))) and \
                    self.soft_states[state_key] != value:

                # first, there may be some conditions
                if state_key in [
                        "correction_roulis", "correction_direction",
                        "correction_stabilisation"
                ] and value and not self.soft_states["pilote_automatique"]:
                    return True
                if state_key.startswith("batterie") and not state_key.endswith(
                        's') and not self.soft_states["batteries"]:
                    self.sound_manager.play("batterie_wrong")
                    return True
                if state_key.startswith(
                        "moteur") and value and self.get_soft_state(
                            "collision_occurred"):
                    self.sound_manager.play("engine_fails")
                    return True

                # now we switch it on
                Logger.print("(soft_state): ",
                             state_key,
                             ':',
                             value,
                             color='yellow')
                old_value = self.soft_states[state_key]
                self.soft_states[state_key] = value

                # check if it is associated to one led
                self.hardware.check_constrained_led(state_key, value)

                # maybe it changes the energy and maybe it plays an automatic sound
                if not value:
                    if not silent:
                        self.sound_manager.play(state_key + "_off")
                    self.power.switch_off(state_key)
                else:
                    if not silent:
                        self.sound_manager.play(state_key + "_on")
                    self.power.switch_on(state_key)

                # check for control_screen:
                self.control_screen.event("update_state", key=state_key)

                # particular actions ?
                if state_key == "offset_ps_x" or state_key == "offset_ps_y":
                    self.update_soft_state(
                        "sp_power",
                        round(
                            self.get_soft_state("sp_max_power") /
                            sqrt(1 + self.get_soft_state("offset_ps_x")**2 +
                                 self.get_soft_state("offset_ps_y")**2), 3))
                    if self.get_soft_state(
                            "offset_ps_x") == self.get_soft_state(
                                "offset_ps_y") == 0:
                        self.sound_manager.play("sp_nominal")
                        self.hardware.set_led_on("l_ps_nominal")
                    else:
                        self.hardware.set_led_off("l_ps_nominal")
                elif state_key == "sp_power":
                    power = self.get_soft_state("main_power")
                    self.update_soft_state("main_power",
                                           power + value - old_value)
                elif state_key == "pilote_automatique" and not value:
                    self.soft_states["full_pilote_automatique"] = False
                    # switch corrections off
                    for c in [
                            "correction_roulis", "correction_direction",
                            "correction_stabilisation"
                    ]:
                        self.update_soft_state(c, False)
                elif state_key in [
                        "correction_roulis", "correction_direction",
                        "correction_stabilisation"
                ]:
                    on = True
                    for c in [
                            "correction_roulis", "correction_direction",
                            "correction_stabilisation"
                    ]:
                        if not self.get_soft_state(c):
                            on = False
                            break
                    self.soft_states["full_pilote_automatique"] = on
                elif state_key.startswith("moteur") and value:
                    self.sound_manager.play("engine_starts")
                elif state_key == "pilote_automatique_failed" and value:
                    # removing it in a few frames
                    self.taskMgr.doMethodLater(
                        0.1,
                        self.update_soft_state,
                        name="paf_end",
                        extraArgs=["pilote_automatique_failed", False])

                # and tell the game that there have been a update
                self.scenario.update_shuttle_state()

                # this may append if the task is automatically fulfilled with f1.
                if state_key == "pilote_automatique_failed" and value:
                    self.soft_states["pilote_automatique_failed"] = False
                    Logger.print("(soft_state): ",
                                 state_key,
                                 ':',
                                 False,
                                 color='yellow')
            else:
                if state_key.startswith('moteur') and value:
                    self.sound_manager.play("engine_fails")
                elif value and not self.power.can_be_switched_on(state_key):
                    self.sound_manager.play("voice_energy_denied")

                    if state_key == "pilote_automatique":
                        # sets the failed to True and immediately after to False.
                        self.soft_states["pilote_automatique_failed"] = True
                        Logger.print("(soft_state): ",
                                     state_key,
                                     ':',
                                     True,
                                     color='yellow')
                        self.scenario.update_shuttle_state()
                        self.soft_states["pilote_automatique_failed"] = False
                        Logger.print("(soft_state): ",
                                     state_key,
                                     ':',
                                     False,
                                     color='yellow')
            return True
        return False
Beispiel #7
0
 def simulate_input(self, event_code, value):
     if event_code in self.events_dict:
         messenger.send(self.events_dict[event_code], [value])
     else:
         Logger.warning(event_code, "is not in the event list !")
Beispiel #8
0
 def set_led_off(self, led_name):
     for key in self.events_dict:
         if self.events_dict[key] == led_name:
             self.arduino.led_off(key)
             return
     Logger.info(led_name, "not found in self.event_dict")