Exemplo n.º 1
0
def readMouse(startTime, button, duration=None):
    iKeyboard = Keyboard()
    if duration is not None:
        while int((get_time() - startTime) * 1000) <= duration:
            alle = pygame.event.get()
            rt = int((get_time() - startTime)*1000)
            for e in alle:
                if e.type == pygame.MOUSEBUTTONDOWN and e.button == button:
                    return rt, coordinates2position(e.pos)

            if iKeyboard.process_control_keys():
                break

        return None, None

    else:
        while True:
            alle = pygame.event.get()
            rt = int((get_time() - startTime)*1000)
            for e in alle:
                if e.type == pygame.MOUSEBUTTONDOWN and e.button == button:
                    return rt, coordinates2position(e.pos)

            if iKeyboard.process_control_keys():
                break
Exemplo n.º 2
0
    def _wait(self, frame=None):
        """Wait until frame was shown or end of movie and update screen.

        Parameters
        ----------
        frame : int, optional
            number of the frame to stop after

        """

        while self.is_playing:
            expyriment._active_exp._execute_wait_callback()
            old_frame = self._frame
            self.update()
            new_frame = self._frame
            if frame is not None and new_frame > frame:
                self.stop()
                break
            diff = new_frame - old_frame
            if diff > 1:
                warn_message = repr(diff - 1) + " video frames dropped!"
                print warn_message
                expyriment._active_exp._event_file_warn(
                                            "Video,warning," + warn_message)
            for event in pygame.event.get(pygame.KEYDOWN):
                if event.type == pygame.KEYDOWN and (\
                   event.key == expyriment.control.defaults.quit_key or \
                   event.key == expyriment.control.defaults.pause_key):
                    self.stop()
                    Keyboard.process_control_keys(event)
                    self.play()
Exemplo n.º 3
0
def readMouse(startTime, button, duration=None):
    iKeyboard = Keyboard()
    if duration is not None:
        while int((get_time() - startTime) * 1000) <= duration:
            alle = pygame.event.get()
            rt = int((get_time() - startTime) * 1000)
            for e in alle:
                if e.type == pygame.MOUSEBUTTONDOWN and e.button == button:
                    return rt, coordinates2position(e.pos)

            if iKeyboard.process_control_keys():
                break

        return None, None

    else:
        while True:
            alle = pygame.event.get()
            rt = int((get_time() - startTime) * 1000)
            for e in alle:
                if e.type == pygame.MOUSEBUTTONDOWN and e.button == button:
                    return rt, coordinates2position(e.pos)

            if iKeyboard.process_control_keys():
                break
Exemplo n.º 4
0
    def _wait(self, frame=None):
        """Wait until frame was shown or end of movie and update screen.

        Parameters
        ----------
        frame : int, optional
            number of the frame to stop after

        See Also
        --------
        design.experiment.register_wait_callback_function

        """

        while self.is_playing:
            rtn_callback = expyriment._active_exp._execute_wait_callback()
            if isinstance(rtn_callback, expyriment.control.CallbackQuitEvent):
                return rtn_callback

            old_frame = self._frame
            self.update()
            new_frame = self._frame
            if frame is not None and new_frame > frame:
                self.stop()
                break
            diff = new_frame - old_frame
            if diff > 1:
                warn_message = repr(diff - 1) + " video frames dropped!"
                print warn_message
                expyriment._active_exp._event_file_warn(
                    "Video,warning," + warn_message)
            for event in pygame.event.get(pygame.KEYDOWN):
                if event.type == pygame.KEYDOWN and (
                   event.key == Keyboard.get_quit_key() or
                   event.key == Keyboard.get_pause_key()):
                    self.stop()
                    Keyboard.process_control_keys(event)
                    self.play()
Exemplo n.º 5
0
    def _wait(self, frame=None):
        """Wait until frame was shown or end of movie and update screen.

        Parameters
        ----------
        frame : int, optional
            number of the frame to stop after

        See Also
        --------
        design.experiment.register_wait_callback_function

        """

        while self.is_playing:
            rtn_callback = expyriment._active_exp._execute_wait_callback()
            if isinstance(rtn_callback, expyriment.control.CallbackQuitEvent):
                return rtn_callback

            old_frame = self._frame
            self.update()
            new_frame = self._frame
            if frame is not None and new_frame > frame:
                self.stop()
                break
            diff = new_frame - old_frame
            if diff > 1:
                warn_message = repr(diff - 1) + " video frames dropped!"
                print warn_message
                expyriment._active_exp._event_file_warn("Video,warning," +
                                                        warn_message)
            for event in pygame.event.get(pygame.KEYDOWN):
                if event.type == pygame.KEYDOWN and (
                        event.key == Keyboard.get_quit_key()
                        or event.key == Keyboard.get_pause_key()):
                    self.stop()
                    Keyboard.process_control_keys(event)
                    self.play()
def initialize(experiment=None):
    """Initialize an experiment.

    This initializes an experiment defined by 'experiment' as well as the
    underlying expyriment system. If 'experiment' is None, a new Experiment
    object will be created and returned. Furthermore, a screen, a clock, a
    keyboard and a event file are created and added to the experiment. The
    initialization screen is shown for a short delay to ensure that Python
    is fully initialized and time accurate. Afterwards, "Preparing
    experiment..." is presented on the screen.

    After experiment initialize the following additional properties are
    available:

    - experiment.screen   -- the current screen
    - experiment.clock    -- the main clock
    - experiment.keyboard -- the main keyboard
    - experiment.mouse    -- the main mouse
    - experiment.event    -- the main event file

    Parameters
    ----------
    experiment : design.Experiment, optional
        the experiment to initialize

    Returns
    -------
    exp : design.Experiment
        initialized experiment

    """

    if experiment is None:
        experiment = design.Experiment()

    if experiment.log_level is None:
        experiment.set_log_level(defaults.event_logging)

    if is_interactive_mode() and not expyriment.control.defaults.window_mode \
        and not hasattr(experiment, "testsuite"):
        print """
Python is running in an interactive shell but Expyriment wants to initialize a
fullscreen."""
        quest = "Do you want to switch to windows mode?"
        ans = raw_input(quest + " (Y/n) ").strip().lower()
        if ans == "" or ans == "y" or ans == "yes":
            print "Switched to windows mode"
            expyriment.control.defaults.window_mode = True

    stdout_logging = defaults.stdout_logging
    expyriment._active_exp = experiment
    old_logging = experiment.log_level
    experiment.set_log_level(0)  # switch off for the first screens

    _keyboard.quit_key = defaults.quit_key
    _keyboard.pause_key = defaults.pause_key
    _keyboard.refresh_key = defaults.refresh_key
    _keyboard.end_function = end
    _keyboard.pause_function = pause

    mixer.pre_init(defaults.audiosystem_sample_rate,
                   defaults.audiosystem_bit_depth,
                   defaults.audiosystem_channels,
                   defaults.audiosystem_buffer_size)
    if defaults.audiosystem_autostart:
        mixer.init()
        mixer.init()  # Needed on some systems

    experiment._clock = misc.Clock()
    experiment._screen = Screen(colour=(0, 0, 0),
                                open_gl=defaults.open_gl,
                                window_mode=defaults.window_mode,
                                window_size=defaults.window_size)
    # Hack for IDLE: quit pygame and call atexit functions when crashing
    if is_idle_running() and sys.argv[0] != "":
        try:
            import idlelib.run

            def wrap(orig_func):
                def newfunc(*a, **kw):
                    pygame.quit()
                    import atexit
                    atexit._run_exitfuncs()
                    idlelib.run.flush_stdout = orig_func
                    return orig_func(*a, **kw)

                return newfunc

            idlelib.run.flush_stdout = wrap(idlelib.run.flush_stdout)
        except ImportError:
            pass
    experiment._data = None
    experiment._subject = None
    experiment._is_initialized = True  # required before EventFile
    if old_logging > 0:
        experiment._events = EventFile(
            additional_suffix=experiment.filename_suffix, time_stamp=True)
        if stdout_logging:
            _set_stdout_logging(experiment._events)
    else:
        experiment._events = None
    experiment._keyboard = Keyboard()
    experiment._mouse = Mouse(show_cursor=False)

    logo = stimuli.Picture(misc.constants.EXPYRIMENT_LOGO_FILE,
                           position=(0, 100))
    logo.scale((0.7, 0.7))
    text = stimuli.TextLine("Version {0}".format(expyriment.get_version()),
                            text_size=14,
                            text_colour=misc.constants.C_EXPYRIMENT_ORANGE,
                            background_colour=(0, 0, 0),
                            position=(0, 40))
    canvas = stimuli.Canvas((600, 300), colour=(0, 0, 0))
    canvas2 = stimuli.Canvas((600, 300), colour=(0, 0, 0))
    logo.plot(canvas)
    text.plot(canvas)
    hash_ = expyriment.get_experiment_secure_hash()
    if hash_ is not None:
        txt = "{0} ({1})".format(os.path.split(sys.argv[0])[1], hash_)
        if len(expyriment._secure_hash.module_hashes_as_string()) > 0:
            txt += ", {0}".format(
                expyriment._secure_hash.module_hashes_as_string())
        text2 = stimuli.TextLine(
            txt,
            text_size=14,
            text_colour=misc.constants.C_EXPYRIMENT_ORANGE,
            background_colour=(0, 0, 0),
            position=(0, 10))
        text2.plot(canvas)
    canvas.preload(True)
    canvas._set_surface(canvas._get_surface().convert())
    start = experiment.clock.time
    r = [x for x in range(256) if x % 5 == 0]
    stopped = False
    if defaults.initialize_delay > 0:
        for x in r:
            canvas._get_surface().set_alpha(x)
            canvas2.clear_surface()
            canvas.plot(canvas2)
            canvas2.present()
            experiment.clock.wait(1)
            key = experiment.keyboard.check(pygame.K_ESCAPE,
                                            check_for_control_keys=False)
            if key is not None:
                stopped = True
                break
        duration = experiment.clock.time - start
        if duration < 2000 and not stopped:
            start = experiment.clock.time
            while experiment.clock.time - start < 2000:
                key = experiment.keyboard.check(pygame.K_ESCAPE,
                                                check_for_control_keys=False)
                if key is not None:
                    stopped = True
                    break
        r = [x for x in range(256)[::-1] if x % 5 == 0]
        if not stopped:
            for x in r:
                canvas._get_surface().set_alpha(x)
                canvas2.clear_surface()
                canvas.plot(canvas2)
                canvas2.present()
                experiment.clock.wait(1)
                key = experiment.keyboard.check(pygame.K_ESCAPE,
                                                check_for_control_keys=False)
                if key is not None:
                    break
    stimuli.TextLine("Preparing experiment...",
                     text_size=24,
                     text_colour=misc.constants.C_EXPYRIMENT_PURPLE).present()
    experiment._screen.colour = experiment.background_colour
    experiment.set_log_level(old_logging)
    stimuli._stimulus.Stimulus._id_counter = 0
    return experiment
def end(goodbye_text=None,
        goodbye_delay=None,
        confirmation=False,
        fast_quit=None,
        system_exit=False):
    """End expyriment.

    Parameters
    ----------
    goodbye_text  : str, optional
        text to present on the screen when quitting
    goodbye_delay : int, optional
        period to show the goodbye_text
    confirmation : bool, optional
        ask for confirmation (default = False)
    fast_quit : bool, optional
        quit faster by hiding the screen before actually quitting
        (default = None)
    system_exit : bool, optional
        call Python's sys.exit() method when ending expyriment (default = False)

    Returns
    -------
    out : bool
        True if Expyriment (incl. Pygame) has been quit.

    """

    if not expyriment._active_exp.is_initialized:
        pygame.quit()
        if system_exit:
            sys.exit()
        return True
    experiment = expyriment._active_exp
    if confirmation:
        experiment._event_file_log("Experiment,paused")
        screen_colour = experiment.screen.colour
        experiment._screen.colour = [0, 0, 0]
        if android is not None:
            position = (0, 200)
        else:
            position = (0, 0)
        stimuli.TextLine("Quitting Experiment? (y/n)",
                         position=position,
                         text_colour=misc.constants.C_EXPYRIMENT_ORANGE,
                         text_size=24).present()
        stimuli._stimulus.Stimulus._id_counter -= 1
        char = Keyboard().wait_char(["y", "n"], check_for_control_keys=False)
        if char[0] == "n":
            experiment._screen.colour = screen_colour
            experiment._event_file_log("Experiment,resumed")
            return False
    experiment._event_file_log("Experiment,ended")
    if goodbye_text is None:
        goodbye_text = defaults.goodbye_text
    if goodbye_delay is None:
        goodbye_delay = defaults.goodbye_delay
    if experiment.events is not None:
        experiment.events.save()
    if experiment.data is not None:
        experiment.data.save()
    if fast_quit is None:
        fast_quit = defaults.fast_quit
    if fast_quit and experiment.is_started:
        if experiment.screen.window_mode:
            pygame.display.set_mode(experiment.screen._window_size)
            pygame.display.iconify()

    try:
        experiment._screen.colour = [0, 0, 0]
        stimuli.TextLine(goodbye_text,
                         position=(0, 0),
                         text_colour=misc.constants.C_EXPYRIMENT_PURPLE,
                         text_size=24).present()
        stimuli._stimulus.Stimulus._id_counter -= 1
    except:
        pass

    if not fast_quit:
        misc.Clock().wait(goodbye_delay)
    expyriment._active_exp = design.Experiment("None")
    pygame.quit()
    return True