コード例 #1
0
 def __init__(self, log='console', log_length=5):
     self.time = Time()
     self.time_i = self.get_time()
     self.dtime = []
     self.number = 0
     self.log = None
     self.log_list = None
     self.log_num = 0
     self.log_scroll = True
     self.set_log(log, log_length)
コード例 #2
0
ファイル: display.py プロジェクト: jggatc/pyjsdl-ts
 def __init__(self, size, buffered):
     Surface.__init__(self, size)
     if isinstance(buffered, bool):
         self._bufferedimage = buffered
     else:
         self._bufferedimage = True
     try:
         if self.impl.canvasContext:
             self._isCanvas = True
     except:
         self._isCanvas = False
         self._bufferedimage = False
     if self._bufferedimage:
         self.surface = Surface(size)
     else:
         self.surface = self
     self.images = {}
     self.image_list = []
     self.callback = None
     self.time = Time()
     self.event = env.event
     self.addMouseListener(self)
     self.addKeyEventListener(self)
     self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP | Event.ONMOUSEMOVE
                     | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL
                     | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP)
     self.onContextMenu = None
     self.preventContextMenu()
     self.evt = self.event.eventObj
     self.modKey = self.event.modKey
     self.specialKey = self.event.specialKey
     self.modKeyCode = self.event.modKeyCode
     self.specialKeyCode = self.event.specialKeyCode
     self.keyRepeat = self.event.keyRepeat
     self.keyHeld = self.event.keyHeld
     self.mouse_entered = True
     self.event._initiate_touch_listener(self)
     self._touch_callback = self.event.touchlistener.callback
     self._rect_list = []
     self._rect_len = 0
     self._rect_num = 0
     self._framerate = 0
     self._frametime = 0
     self._rendertime = self.time.time()
     self._pause = False
     self._canvas_init()
     self.run = None
     self.initialized = False
コード例 #3
0
ファイル: mixer.py プロジェクト: jggatc/pyjsdl
 def __init__(self, id):
     self._id = id
     self._sound = None
     self._active = False
     self._pause = False
     self._loops = 0
     self._volume = 1.0
     self._lvolume = 1.0
     self._rvolume = 1.0
     self._mixer._register_channel(self)
     self._time = Time()
     self._nonimplemented_methods()
コード例 #4
0
 def __init__(self, size, buffered):
     Surface.__init__(self, size)
     MouseWheelHandler.__init__(self, True)
     if isinstance(buffered, bool):
         self._bufferedimage = buffered
     else:
         self._bufferedimage = True
     try:
         if self.impl.canvasContext:
             self._isCanvas = True
     except:
         self._isCanvas = False
         self._bufferedimage = False
     if self._bufferedimage:
         self.surface = Surface(size)
     else:
         self.surface = self
     self.images = {}
     self.image_list = []
     self.callback = None
     self.time = Time()
     self.event = pyjsdl.event
     self.addMouseListener(self)
     self.addMouseWheelListener(self)
     self.addKeyboardListener(self)
     self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP | Event.ONMOUSEMOVE
                     | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL
                     | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP)
     self.modKey = pyjsdl.event.modKey
     self.specialKey = pyjsdl.event.specialKey
     self.event._initiate_touch_listener(self)
     self._touch_callback = self.event.touchlistener.callback
     self._repaint = False
     self._rect_list = []
     self._rect_len = 0
     self._rect_num = 0
     self._framerate = 0
     self._frametime = 0
     self._canvas_init()
     self.initialized = False
コード例 #5
0
ファイル: mixer.py プロジェクト: jggatc/pyjsdl-ts
 def __init__(self):
     Sound._mixer = self
     Channel._mixer = self
     self.Sound = Sound
     self.Channel = self._get_channel
     self._channel_max = 8
     self._channels = {}
     self._channel_available = [id for id in
                                range(self._channel_max-1,-1,-1)]
     self._channel_active = []
     self._channel_reserved = []
     self._channel_reserved_num = 0
     self._channel_process = set()
     self._channel_process_end = set()
     for id in range(self._channel_max):
         self._get_channel(id)
     self.music = Music()
     self._time = Time()
     self._timerid = 0
     self._processing = False
     self._active = False
     self._initialized = True
コード例 #6
0
def init():
    """
    Initialize module.
    """
    global time, display, image, event, key, mouse, mixer, _initialized
    if _initialized:
        return
    else:
        _initialized = True
    event = Event()
    env.set_env('event', event)
    time = Time()
    display = Display()
    image = Image()
    mixer = Mixer()
    mouse = Mouse()
    key = Key()
コード例 #7
0
ファイル: display.py プロジェクト: jggatc/pyjsdl
 def __init__(self, size, buffered):
     Surface.__init__(self, size)
     MouseWheelHandler.__init__(self, True)
     if isinstance(buffered, bool):
         self._bufferedimage = buffered
     else:
         self._bufferedimage = True
     try:
         if self.impl.canvasContext:
             self._isCanvas = True
     except:
         self._isCanvas = False
         self._bufferedimage = False
     if self._bufferedimage:
         self.surface = Surface(size)
     else:
         self.surface = self
     self.images = {}
     self.image_list = []
     self.callback = None
     self.time = Time()
     self.event = pyjsdl.event
     self.addMouseListener(self)
     self.addMouseWheelListener(self)
     self.addKeyboardListener(self)
     self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP| Event.ONMOUSEMOVE | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP)
     self.modKey = pyjsdl.event.modKey
     self.specialKey = pyjsdl.event.specialKey
     self.event._initiate_touch_listener(self)
     self._touch_callback = self.event.touchlistener.callback
     self._repaint = False
     self._rect_list = []
     self._rect_len = 0
     self._rect_num = 0
     self._framerate = 0
     self._frametime = 0
     self._canvas_init()
     self.initialized = False
コード例 #8
0
class Timer(object):
    """
    Simple profiling timer.
    Output log can be directed to 'console' or to 'textarea'.
    If output is to textarea, may specify log length.
    """

    def __init__(self, log='console', log_length=5):
        self.time = Time()
        self.time_i = self.get_time()
        self.dtime = []
        self.number = 0
        self.log = None
        self.log_list = None
        self.log_num = 0
        self.log_scroll = True
        self.set_log(log, log_length)

    def get_time(self):
        """
        Get current time.
        """
        return self.time.time()

    def set_time(self):
        """
        Set current time.
        """
        self.time_i = self.get_time()

    def lap_time(self, time_i=None, time_f=None, number=100, print_result=True):
        """
        Time lapsed since previous set_time.
        Optional arguments time_i and time_f, number of calls to average, and print_results to output result.
        """
        if time_i is None:
            time_i = self.time_i
        if time_f is None:
            time_f = self.get_time()
        self.dtime.append(time_f-time_i)
        self.number += 1
        if self.number >= number:
            t_ave = ( sum(self.dtime)/number )
            self.dtime = []
            self.number = 0
            if print_result:
                if self.log_type == 'console':
                    self.log_num += 1
                    entry = "Time %d: %s" % (self.log_num, t_ave)
                    print(entry)
                else:
                    self.log_num += 1
                    entry = "Time %d: %s" % (self.log_num, t_ave)
                    self.print_log(entry)
            return t_ave

    def set_log(self, log, log_length=5):
        """
        Set log output.
        Argument log can be 'console' or 'textarea'.
        """
        if log in ('console','textarea'):
            self.log_type = log
            if log == 'textarea':
                if not self.log:
                    size = env.canvas.surface.width-5, 102
                    self.log = env.canvas.surface._display.Textarea(size)
                    self.log.setReadonly(True)
                    self.log.addMouseListener(self)
                    self.onMouseUp = lambda sender,x,y: None
                    self.onMouseMove = lambda sender,x,y: None
                    self.onMouseEnter = lambda sender: None
                    self.log_list = ['' for i in range(log_length)]
                self.log.toggle(True)
            else:
                if self.log:
                    self.log.toggle(False)
                    self.log_list = []

    def onMouseDown(self, sender, x, y):
        self.log_scroll = False

    def onMouseLeave(self, sender):
        self.log_scroll = True

    def print_log(self, text):
        """
        Print text to output.
        """
        if self.log_type == 'console':
            print(text)
        else:
            self.log_list.pop(0)
            self.log_list.append(text+'\n')
            text = ''.join(self.log_list)
            self.log.setText(text)
            if self.log_scroll:
                self.log.setCursorPos(len(text))
コード例 #9
0
ファイル: mixer.py プロジェクト: jggatc/pyjsdl-ts
class Mixer:
    """
    **pyjsdl.mixer**
    
    * pyjsdl.mixer.init
    * pyjsdl.mixer.quit
    * pyjsdl.mixer.get_init
    * pyjsdl.mixer.stop
    * pyjsdl.mixer.pause
    * pyjsdl.mixer.unpause
    * pyjsdl.mixer.fadeout
    * pyjsdl.mixer.set_num_channels
    * pyjsdl.mixer.get_num_channels
    * pyjsdl.mixer.set_reserved
    * pyjsdl.mixer.find_channel
    * pyjsdl.mixer.get_busy
    * pyjsdl.mixer.Sound
    * pyjsdl.mixer.Channel
    * pyjsdl.mixer.music
    """

    def __init__(self):
        Sound._mixer = self
        Channel._mixer = self
        self.Sound = Sound
        self.Channel = self._get_channel
        self._channel_max = 8
        self._channels = {}
        self._channel_available = [id for id in
                                   range(self._channel_max-1,-1,-1)]
        self._channel_active = []
        self._channel_reserved = []
        self._channel_reserved_num = 0
        self._channel_process = set()
        self._channel_process_end = set()
        for id in range(self._channel_max):
            self._get_channel(id)
        self.music = Music()
        self._time = Time()
        self._timerid = 0
        self._processing = False
        self._active = False
        self._initialized = True

    def init(self, *args, **kwargs):
        """
        Mixer initialization.
        """
        if not self._initialized:
            self._initialized = True
        return None

    def pre_init(self,  *args, **kwargs):
        """
        Mixer initialization.
        """
        self.init()
        return None

    def quit(self):
        """
        Stop mixer processing and release resources.
        """
        self.music._channel.stop()
        self.stop()
        self._initialized = False
        return None

    def get_init(self):
        """
        Get the audio format initialized.
        """
        if self._initialized:
            return self._initialized
        else:
            return None

    def stop(self):
        """
        Stop mixer channels.
        """
        for id in self._channel_active:
            if id > -1:
                self._channels[id].stop()
        return None

    def fadeout(self, time):
        """
        Fadeout mixer channels in given time.
        """
        for id in self._channel_active:
            if id > -1:
                self._channels[id].fadeout(time)
        return None

    def pause(self):
        """
        Pause mixer channels.
        """
        for id in self._channel_active:
            if id > -1:
                self._channels[id].pause()
        return None

    def unpause(self):
        """
        Unpause mixer channels.
        """
        for id in self._channel_active:
            if id > -1:
                self._channels[id].unpause()
        return None

    def set_num_channels(self, count):
        """
        Set maximum mixer channels.
        Argument channel count.
        """
        if count >= self._channel_max:
            for id in range(self._channel_max, count):
                self._get_channel(id)
                self._channel_available.insert(0, id)
            self._channel_max = count
        elif count >= 0:
            for id in range(count, self._channel_max):
                if str(id) in self._channels.keys():
                    if self._channels[id] is not None:
                        self._channels[id].stop()
                    del self._channels[id]
                if id in self._channel_available:
                    self._channel_available.remove(id)
            self._channel_max = count
        return None

    def get_num_channels(self):
        """
        Get maximum mixer channels.
        """
        return self._channel_max

    def set_reserved(self, count):
        """
        Reserve channel.
        Argument reserved channel count.
        """
        if count > self._channel_max:
            count = self._channel_max
        elif count < 0:
            count = 0
        self._channel_reserved_num = count
        self._channel_reserved = []
        for id in range(self._channel_reserved_num):
            self._channel_reserved.append(id)
            if id in self._channel_available:
                self._channel_available.remove(id)
        return None

    def find_channel(self, force=False):
        """
        Get an inactive mixer channel.
        Optional force attribute return longest running channel if all active.
        """
        if len(self._channel_available) > 0:
            id = self._channel_available.pop()
            self._channel_available.insert(0, id)
            return self._channels[id]
        if self._channel_reserved_num:
            if len(self._channel_reserved) > 0:
                id = self._channel_reserved.pop()
                self._channel_reserved.insert(0, id)
                return self._channels[id]
        if not force:
            return None
        longest = None
        longest_reserved = None
        for id in self._channel_active:
            if id > self._channel_reserved_num-1:
                longest = id
                break
            elif id > -1:
                if longest_reserved is None:
                    longest_reserved = id
        if longest is not None:
            channel = longest
        else:
            if longest_reserved is not None:
                channel = longest_reserved
            else:
                channel = 0
        return self._channels[channel]

    def get_busy(self):
        """
        Check if mixer channels are actively processing.
        """
        for id in self._channel_active:
            if id > -1:
                if self._channels[id]._active:
                    return True
        return False

    def _process(self, id):
        self._channel_process.add(id)
        if not self._processing:
            self._processing = True
            self._timerid = self._time.set_interval(self, 10)

    def run(self):
        if self._active:
            for id in self._channel_process:
                complete = self._channels[id]._process()
                if complete:
                    self._channel_process_end.add(id)
            if len(self._channel_process_end) > 0:
                for i in range(len(self._channel_process_end)):
                    id = self._channel_process_end.pop()
                    self._channel_process.discard(id)
                if len(self._channel_process) == 0:
                    self._processing = False
                    self._time.clear_interval(self._timerid)
        else:
            if len(self._channel_process) > 0:
                for i in range(len(self._channel_process)):
                    self._channel_process.pop()
            self._processing = False
            self._time.clear_interval(self._timerid)

    def _activate_channel(self, id):
        if id > self._channel_reserved_num-1:
            self._channel_available.remove(id)
        elif id > -1:
            self._channel_reserved.remove(id)
        self._channel_active.append(id)
        self._active = True

    def _deactivate_channel(self, id):
        self._channel_active.remove(id)
        if len(self._channel_active) == 0:
            self._active = False

    def _restore_channel(self, id):
        if id > self._channel_reserved_num-1:
            self._channel_available.append(id)
        elif id > -1:
            self._channel_reserved.append(id)

    def _retrieve_channel(self):
        if len(self._channel_available) > 0:
            id = self._channel_available.pop()
            self._channel_active.append(id)
            self._active = True
            return self._channels[id]
        else:
            return None

    def _get_channel(self, id):
        if str(id) in self._channels.keys():
            return self._channels[id]
        else:
            return Channel(id)

    def _register_channel(self, channel):
        id = channel._id
        if id < self._channel_max:
            self._channels[id] = channel
        else:
            raise AttributeError('Channel not available.')
コード例 #10
0
ファイル: mixer.py プロジェクト: jggatc/pyjsdl
class Channel:
    """
    **pyjsdl.mixer.Channel**
    
    * Channel.play
    * Channel.stop
    * Channel.pause
    * Channel.unpause
    * Channel.set_volume
    * Channel.get_volume
    * Channel.get_busy
    * Channel.get_sound
    """

    _mixer = None

    def __init__(self, id):
        self._id = id
        self._sound = None
        self._active = False
        self._pause = False
        self._loops = 0
        self._volume = 1.0
        self._lvolume = 1.0
        self._rvolume = 1.0
        self._mixer._register_channel(self)
        self._time = Time()
        self._nonimplemented_methods()

    def _set_sound(self, sound):
        if self._sound:
            self._sound._channel = None
        self._sound = sound

    def _play(self):
        self._volume = 1.0
        self._lvolume = 1.0
        self._rvolume = 1.0
        self._active = True
        self._sound._sound_object.play()
        self._time.timeout(self._sound._sound_object.getDuration()*1000, self)

    def _play_repeat(self, loops):
        if loops > 0:
            self._loops = loops
        else:
            self._loops = -1
        self._play()

    def play(self, sound, loops=0, maxtime=0, fade_ms=0):
        """
        Play sound on channel.
        Argument sound to play and loops is number of repeats or -1 for continuous.
        """
        if self._sound:
            self.stop()
        self._set_sound(sound)
        if not loops:
            self._play()
        else:
            self._play_repeat(loops)
        return None

    def run(self):
        if not self._loops:
            self._active = False
        else:
            if self._loops > 0:
                self._loops -= 1
            self._play()

    def stop(self):
        """
        Stop sound on channel.
        """
        if self._sound:
            self._sound._sound_object.pause()
            self._sound._sound_object.setCurrentTime(0)
            self._pause = False
            self._loops = 0
            self._active = False
        return None

    def pause(self):
        """
        Pause sound on channel.
        """
        if self._sound:
            if not self._pause:
                self._sound._sound_object.pause()
                self._pause = True
        return None

    def unpause(self):
        """
        Unpause sound on channel.
        """
        if self._sound:
            if self._pause:
                self._sound._sound_object.play()
                self._pause = False
        return None

    def set_volume(self, volume):
        """
        Set channel volume of sound playing.
        """
        if volume < 0.0:
            volume = 0.0
        elif volume > 1.0:
            volume = 1.0
        self._volume = volume
        if self._sound:
            self._sound._sound_object.setVolume(self._volume * self._sound._sound_object._volume)
        else:
            self._volume = 1.0
        return None

    def get_volume(self):
        """
        Get channel volume for current sound.
        """
        return self._volume

    def get_busy(self):
        """
        Check if channel is processing sound.
        """
        return self._active

    def get_sound(self):
        """
        Get sound open by channel.
        """
        return self._sound

    def _nonimplemented_methods(self):
        """
        Non-implemented methods.
        """
        self.fadeout = lambda *arg: None
        self.queue = lambda *arg: None
        self.get_queue = lambda *arg: None
        self.set_endevent = lambda *arg: None
        self.get_endevent = lambda *arg: 0
コード例 #11
0
class Canvas(Surface, MouseWheelHandler):
    def __init__(self, size, buffered):
        Surface.__init__(self, size)
        MouseWheelHandler.__init__(self, True)
        if isinstance(buffered, bool):
            self._bufferedimage = buffered
        else:
            self._bufferedimage = True
        try:
            if self.impl.canvasContext:
                self._isCanvas = True
        except:
            self._isCanvas = False
            self._bufferedimage = False
        if self._bufferedimage:
            self.surface = Surface(size)
        else:
            self.surface = self
        self.images = {}
        self.image_list = []
        self.callback = None
        self.time = Time()
        self.event = pyjsdl.event
        self.addMouseListener(self)
        self.addMouseWheelListener(self)
        self.addKeyboardListener(self)
        self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP | Event.ONMOUSEMOVE
                        | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL
                        | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP)
        self.modKey = pyjsdl.event.modKey
        self.specialKey = pyjsdl.event.specialKey
        self.event._initiate_touch_listener(self)
        self._touch_callback = self.event.touchlistener.callback
        self._repaint = False
        self._rect_list = []
        self._rect_len = 0
        self._rect_num = 0
        self._framerate = 0
        self._frametime = 0
        self._canvas_init()
        self.initialized = False

    def _canvas_init(self):
        global _canvas, _ctx, _img, _wnd
        _canvas = self
        _ctx = self.impl.canvasContext
        _img = self.surface.canvas
        _wnd = requestAnimationFrameInit()

    def onMouseMove(self, sender, x, y):
        event = DOM.eventGetCurrentEvent()
        event.pos = (x, y)
        self.event.mouseMove['x'], self.event.mouseMove['y'] = x, y
        self.event._updateQueue(event)

    def onMouseDown(self, sender, x, y):
        event = DOM.eventGetCurrentEvent()
        event.pos = (x, y)
        self.event.mousePress[event.button] = True
        self.event._updateQueue(event)

    def onMouseUp(self, sender, x, y):
        event = DOM.eventGetCurrentEvent()
        event.pos = (x, y)
        self.event.mousePress[event.button] = False
        self.event._updateQueue(event)

    def onMouseLeave(self, sender):
        self.event.mousePress[0], self.event.mousePress[
            1], self.event.mousePress[2] = False, False, False
        self.event.mouseMove['x'], self.event.mouseMove['y'] = -1, -1
        self.event.mouseMoveRel['x'], self.event.mouseMoveRel['y'] = None, None
        for keycode in self.modKey:
            if self.event.keyPress[keycode]:
                self.event.keyPress[keycode] = False

    def onMouseWheel(self, sender, velocity):
        event = DOM.eventGetCurrentEvent()
        if event.type == 'mousewheel':
            #TODO: update for changes in mousewheel implementation
            if hasattr(event, 'wheelDeltaX'):
                self.onMouseWheel = self._onMouseWheel
                self._onMouseWheel(sender, velocity)
            else:
                self.onMouseWheel = self._onMouseWheelY
                DOM.eventGetMouseWheelVelocityY = eventGetMouseWheelVelocityY
                self._onMouseWheelY(sender, eventGetMouseWheelVelocityY(event))
        else:  #DOMMouseScroll
            self.onMouseWheel = self._onMouseScroll
            self._onMouseScroll(sender, velocity)

    def _onMouseWheel(self, sender, velocity):
        event = DOM.eventGetCurrentEvent()
        if not event.wheelDeltaX:
            if velocity < 0:
                button = 4
                events = velocity / -3
            else:
                button = 5
                events = velocity / 3
        else:
            if velocity < 0:
                button = 6
                events = velocity / -3
            else:
                button = 7
                events = velocity / 3
        event.btn = button
        event.pos = (self.event.mouseMove['x'], self.event.mouseMove['y'])
        for evt in range(events):
            self.event._updateQueue(event)

    def _onMouseWheelY(self, sender, velocity):
        event = DOM.eventGetCurrentEvent()
        if velocity < 0:
            button = 4
            events = velocity / -3
        else:
            button = 5
            events = velocity / 3
        event.btn = button
        event.pos = (self.event.mouseMove['x'], self.event.mouseMove['y'])
        for evt in range(events):
            self.event._updateQueue(event)

    def _onMouseScroll(self, sender, velocity):
        event = DOM.eventGetCurrentEvent()
        if velocity > 1 or velocity < -1:
            if velocity < 0:
                button = 4
            else:
                button = 5
        else:
            if velocity < 0:
                button = 6
            else:
                button = 7
        event.btn = button
        event.pos = (self.event.mouseMove['x'], self.event.mouseMove['y'])
        self.event._updateQueue(event)

    def onKeyDown(self, sender, keycode, modifiers):
        if keycode in self.modKey:
            event = DOM.eventGetCurrentEvent()
            self.event.keyPress[keycode] = True
            self.event._updateQueue(event)
            DOM.eventPreventDefault(event)
        elif keycode in self.specialKey:
            event = DOM.eventGetCurrentEvent()
            self.event._updateQueue(event)
            DOM.eventPreventDefault(event)

    def onKeyPress(self, sender, keycode, modifiers):
        event = DOM.eventGetCurrentEvent()
        if not (event.keyCode and event.keyCode in self.specialKey):
            self.event._updateQueue(event)
        DOM.eventPreventDefault(event)

    def onKeyUp(self, sender, keycode, modifiers):
        event = DOM.eventGetCurrentEvent()
        if keycode in self.modKey:
            self.event.keyPress[keycode] = False
        self.event._updateQueue(event)

    def onTouchInitiate(self, event):
        self.event.touchlistener.activate()
        for callback in self._touch_callback:
            if hasattr(callback, 'onTouchInitiate'):
                callback.onTouchInitiate(event)
        self.onTouchStart(event)

    def onTouchStart(self, event):
        for callback in self._touch_callback:
            callback.onTouchStart(event)

    def onTouchEnd(self, event):
        for callback in self._touch_callback:
            callback.onTouchEnd(event)

    def onTouchMove(self, event):
        for callback in self._touch_callback:
            callback.onTouchMove(event)

    def onTouchCancel(self, event):
        for callback in self._touch_callback:
            callback.onTouchCancel(event)

    def resize(self, width, height):
        Surface.resize(self, width, height)
        if self._bufferedimage:
            self.surface.resize(width, height)
        self.surface._display._surface_rect = self.surface.get_rect()

    def set_callback(self, cb):
        if not hasattr(cb, 'run'):
            self.callback = Callback(cb)
        else:
            self.callback = cb

    def load_images(self, images):
        if images:
            image_list = []
            for image in images:
                if isinstance(image, str):
                    image_list.append(image)
                    self.image_list.append(image)
                else:
                    name = image[0]
                    if isinstance(image[1], str):
                        data = image[1]
                    else:
                        data = base64.b64encode(image[1].getvalue())
                    if not data.startswith('data:'):
                        ext = name.strip().split('.')[-1]
                        data = "data:%s;base64,%s" % (ext, data)
                        #data:[<mediatype>][;base64],<data>
                    image_list.append(data)
                    self.image_list.append(name)
            loadImages(image_list, self)
        else:
            self.start()

    def onImagesLoaded(self, images):
        for i, image in enumerate(self.image_list):
            self.images[image] = images[i].getElement()
        self.start()

    def start(self):
        if not self.initialized:
            self.initialized = True
            _wnd.requestAnimationFrame(run)
            self.time.timeout(0, self)

    def stop(self):
        global run
        run = lambda ts: None
        self.run = lambda: None

    def _get_rect(self):
        if self._rect_num < self._rect_len:
            return self._rect_list[self._rect_num]
        else:
            self._rect_list.append(Rect(0, 0, 0, 0))
            self._rect_len += 1
            return self._rect_list[self._rect_num]

    def run(self):
        if not self._repaint:
            self.callback.run()
            self._repaint = True
        self.time.timeout(0, self)
コード例 #12
0
class Canvas(Surface, MouseWheelHandler):

    def __init__(self, size, buffered):
        Surface.__init__(self, size)
        MouseWheelHandler.__init__(self, True)
        if isinstance(buffered, bool):
            self._bufferedimage = buffered
        else:
            self._bufferedimage = True
        try:
            if self.impl.canvasContext:
                self._isCanvas = True
        except:
            self._isCanvas = False
            self._bufferedimage = False
        if self._bufferedimage:
            self.surface = Surface(size)
        else:
            self.surface = self
        self.images = {}
        self.image_list = []
        self.callback = None
        self.time = Time()
        self.event = pyjsdl.event
        self.addMouseListener(self)
        self.addMouseWheelListener(self)
        self.addKeyboardListener(self)
        self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP| Event.ONMOUSEMOVE | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP)
        self.modKey = pyjsdl.event.modKey
        self.specialKey = pyjsdl.event.specialKey
        self._repaint = False
        self._rect_list = []
        self._rect_len = 0
        self._rect_num = 0
        self._framerate = 0
        self._frametime = 0
        self._canvas_init()
        self.initialized = False

    def _canvas_init(self):
        global _canvas, _ctx, _img, _wnd
        _canvas = self
        _ctx = self.impl.canvasContext
        _img = self.surface.canvas
        _wnd = requestAnimationFrameInit()

    def onMouseMove(self, sender, x, y):
        event = DOM.eventGetCurrentEvent()
        event.pos = (x, y)
        self.event.mouseMove['x'], self.event.mouseMove['y'] = x, y
        self.event._updateQueue(event)

    def onMouseDown(self, sender, x, y):
        event = DOM.eventGetCurrentEvent()
        event.pos = (x, y)
        self.event.mousePress[event.button] = True
        self.event._updateQueue(event)

    def onMouseUp(self, sender, x, y):
        event = DOM.eventGetCurrentEvent()
        event.pos = (x, y)
        self.event.mousePress[event.button] = False
        self.event._updateQueue(event)

    def onMouseLeave(self, sender):
        self.event.mousePress[0], self.event.mousePress[1], self.event.mousePress[2] = False, False, False
        self.event.mouseMove['x'], self.event.mouseMove['y'] = -1, -1
        self.event.mouseMoveRel['x'], self.event.mouseMoveRel['y'] = None, None
        for keycode in self.modKey:
            if self.event.keyPress[keycode]:
                self.event.keyPress[keycode] = False

    def onMouseWheel(self, sender, velocity):
        event = DOM.eventGetCurrentEvent()
        if event.type == 'mousewheel':
            #TODO: update for changes in mousewheel implementation
            if hasattr(event, 'wheelDeltaX'):
                self.onMouseWheel = self._onMouseWheel
                self._onMouseWheel(sender, velocity)
            else:
                self.onMouseWheel = self._onMouseWheelY
                DOM.eventGetMouseWheelVelocityY = eventGetMouseWheelVelocityY
                self._onMouseWheelY(sender, eventGetMouseWheelVelocityY(event))
        else:       #DOMMouseScroll
            self.onMouseWheel = self._onMouseScroll
            self._onMouseScroll(sender, velocity)

    def _onMouseWheel(self, sender, velocity):
        event = DOM.eventGetCurrentEvent()
        if not event.wheelDeltaX:
            if velocity < 0:
                button = 4
                events = velocity / -3
            else:
                button = 5
                events = velocity / 3
        else:
            if velocity < 0:
                button = 6
                events = velocity / -3
            else:
                button = 7
                events = velocity / 3
        event.btn = button
        event.pos = (self.event.mouseMove['x'], self.event.mouseMove['y'])
        for evt in range(events):
            self.event._updateQueue(event)

    def _onMouseWheelY(self, sender, velocity):
        event = DOM.eventGetCurrentEvent()
        if velocity < 0:
            button = 4
            events = velocity / -3
        else:
            button = 5
            events = velocity / 3
        event.btn = button
        event.pos = (self.event.mouseMove['x'], self.event.mouseMove['y'])
        for evt in range(events):
            self.event._updateQueue(event)

    def _onMouseScroll(self, sender, velocity):
        event = DOM.eventGetCurrentEvent()
        if velocity > 1 or velocity < -1:
            if velocity < 0:
                button = 4
            else:
                button = 5
        else:
            if velocity < 0:
                button = 6
            else:
                button = 7
        event.btn = button
        event.pos = (self.event.mouseMove['x'], self.event.mouseMove['y'])
        self.event._updateQueue(event)

    def onKeyDown(self, sender, keycode, modifiers):
        if keycode in self.modKey:
            event = DOM.eventGetCurrentEvent()
            self.event.keyPress[keycode] = True
            self.event._updateQueue(event)
            DOM.eventPreventDefault(event)
        elif keycode in self.specialKey:
            event = DOM.eventGetCurrentEvent()
            self.event._updateQueue(event)
            DOM.eventPreventDefault(event)

    def onKeyPress(self, sender, keycode, modifiers):
        event = DOM.eventGetCurrentEvent()
        if not (event.keyCode and event.keyCode in self.specialKey):
            self.event._updateQueue(event)
        DOM.eventPreventDefault(event)

    def onKeyUp(self, sender, keycode, modifiers):
        event = DOM.eventGetCurrentEvent()
        if keycode in self.modKey:
            self.event.keyPress[keycode] = False
        self.event._updateQueue(event)

    def resize(self, width, height):
        Surface.resize(self, width, height)
        if self._bufferedimage:
            self.surface.resize(width, height)
        self.surface._display._surface_rect = self.surface.get_rect()

    def set_callback(self, cb):
        if not hasattr(cb, 'run'):
            self.callback = Callback(cb)
        else:
            self.callback = cb

    def load_images(self, images):
        if images:
            image_list = []
            for image in images:
                if isinstance(image, str):
                    image_list.append(image)
                    self.image_list.append(image)
                else:
                    name = image[0]
                    if isinstance(image[1], str):
                        data = image[1]
                    else:
                        data = base64.b64encode(image[1].getvalue())
                    if not data.startswith('data:'):
                        ext = name.strip().split('.')[-1]
                        data = "data:%s;base64,%s" %(ext, data)
                        #data:[<mediatype>][;base64],<data>
                    image_list.append(data)
                    self.image_list.append(name)
            loadImages(image_list, self)
        else:
            self.start()

    def onImagesLoaded(self, images):
        for i, image in enumerate(self.image_list):
            self.images[image] = images[i].getElement()
        self.start()

    def start(self):
        if not self.initialized:
            self.initialized = True
            _wnd.requestAnimationFrame(run)
            self.time.timeout(0, self)

    def stop(self):
        global run
        run = lambda ts: None
        self.run = lambda: None

    def _get_rect(self):
        if self._rect_num < self._rect_len:
            return self._rect_list[self._rect_num]
        else:
            self._rect_list.append(Rect(0,0,0,0))
            self._rect_len += 1
            return self._rect_list[self._rect_num]

    def run(self):
        if not self._repaint:
            self.callback.run()
            self._repaint = True
        self.time.timeout(0, self)
コード例 #13
0
ファイル: display.py プロジェクト: jggatc/pyjsdl
class Canvas(Surface):
    def __init__(self, size, buffered):
        Surface.__init__(self, size)
        if isinstance(buffered, bool):
            self._bufferedimage = buffered
        else:
            self._bufferedimage = True
        try:
            if self.impl.canvasContext:
                self._isCanvas = True
        except:
            self._isCanvas = False
            self._bufferedimage = False
        if self._bufferedimage:
            self.surface = Surface(size)
        else:
            self.surface = self
        self.images = {}
        self.image_list = []
        self.callback = None
        self.time = Time()
        self.event = env.event
        self.addMouseListener(self)
        self.addKeyEventListener(self)
        self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP | Event.ONMOUSEMOVE
                        | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL
                        | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP)
        self.onContextMenu = None
        self.preventContextMenu()
        self.evt = self.event.eventObj
        self.modKey = self.event.modKey
        self.specialKey = self.event.specialKey
        self.modKeyCode = self.event.modKeyCode
        self.specialKeyCode = self.event.specialKeyCode
        self.keyRepeat = self.event.keyRepeat
        self.keyHeld = self.event.keyHeld
        self.mouse_entered = True
        self.event._initiate_touch_listener(self)
        self._touch_callback = self.event.touchlistener.callback
        self._rect_list = []
        self._rect_len = 0
        self._rect_num = 0
        self._framerate = 0
        self._frametime = 0
        self._rendertime = self.time.time()
        self._pause = False
        self._canvas_init()
        self.initialized = False

    def _canvas_init(self):
        global _canvas, _ctx, _img, _wnd
        _canvas = self
        _ctx = self.impl.canvasContext
        _img = self.surface.canvas
        _wnd = requestAnimationFrameInit()

    def onMouseMove(self, sender, x, y):
        event = DOM.eventGetCurrentEvent()
        if event.type in self.event.events:
            if not self.mouse_entered:
                self.event.mouseMovePre['x'] = self.event.mouseMove['x']
                self.event.mouseMovePre['y'] = self.event.mouseMove['y']
            else:
                self.event.mouseMovePre['x'] = x
                self.event.mouseMovePre['y'] = y
                self.mouse_entered = False
            self.event._updateQueue(self.evt[event.type](event, x, y))
        self.event.mouseMove['x'] = x
        self.event.mouseMove['y'] = y

    def onMouseDown(self, sender, x, y):
        event = DOM.eventGetCurrentEvent()
        if event.type in self.event.events:
            self.event._updateQueue(self.evt[event.type](event, x, y))
        self.event.mousePress[event.button] = True

    def onMouseUp(self, sender, x, y):
        event = DOM.eventGetCurrentEvent()
        if event.type in self.event.events:
            self.event._updateQueue(self.evt[event.type](event, x, y))
        self.event.mousePress[event.button] = False

    def onMouseEnter(self, sender):
        self.mouse_entered = True

    def onMouseLeave(self, sender):
        self.event.mousePress[0] = False
        self.event.mousePress[1] = False
        self.event.mousePress[2] = False
        self.event.mouseMove['x'] = -1
        self.event.mouseMove['y'] = -1
        self.event.mouseMoveRel['x'] = None
        self.event.mouseMoveRel['y'] = None
        for keycode in self.modKeyCode:
            if self.event.keyPress[keycode]:
                self.event.keyPress[keycode] = False

    def onMouseWheel(self, event):
        if event.type in self.event.events:
            r = self.canvas.getBoundingClientRect()
            x = event.clientX - round(r.left)
            y = event.clientY - round(r.top)
            self.event._updateQueue(self.evt[event.type](event, x, y))
        DOM.eventPreventDefault(event)

    def onKeyEvent(self, event):
        self.removeKeyEventListener(self)
        self.addKeyboardListener(self)
        DOM.currentEvent = event
        if hasattr(event, 'key') and hasattr(event, 'code'):
            self.onKeyDown(self, event.key, 0)
        else:
            self.event._set_key_event()
            self.onKeyDown = self._onKeyDown
            self.onKeyUp = self._onKeyUp
            self.onKeyPress = self._onKeyPress
            keycode = event.which or event.keyCode or 0
            self._onKeyDown(self, keycode, 0)

    def onKeyDown(self, sender, keycode, mods):
        event = DOM.eventGetCurrentEvent()
        if event.key in self.modKey:
            self.event.keyPress[self.modKey[event.key]] = True
        if event.type in self.event.events:
            if not self._isPaused(event.key):
                self.event._updateQueue(self.evt[event.type](event))
        DOM.eventPreventDefault(event)

    def onKeyUp(self, sender, keycode, mods):
        event = DOM.eventGetCurrentEvent()
        if event.key in self.modKey:
            self.event.keyPress[self.modKey[event.key]] = False
        if event.key in self.keyHeld:
            self.keyHeld[event.key]['pressed'] = False
        if event.type in self.event.events:
            self.event._updateQueue(self.evt[event.type](event))

    def _onKeyDown(self, sender, keycode, mods):
        event = DOM.eventGetCurrentEvent()
        if keycode in self.modKeyCode:
            self.event.keyPress[keycode] = True
        if event.type in self.event.events:
            if not self._isPaused(keycode):
                self.event.keyCode = keycode
                if keycode in self.specialKeyCode:
                    self.event._updateQueue(self.evt[event.type](event,
                                                                 keycode))
                    DOM.eventPreventDefault(event)
            else:
                DOM.eventPreventDefault(event)

    def _onKeyUp(self, sender, keycode, mods):
        event = DOM.eventGetCurrentEvent()
        if keycode in self.modKeyCode:
            self.event.keyPress[keycode] = False
        if keycode in self.keyHeld:
            self.keyHeld[keycode]['pressed'] = False
        if event.type in self.event.events:
            self.event._updateQueue(self.evt[event.type](event, keycode))

    def _onKeyPress(self, sender, keycode, mods):
        event = DOM.eventGetCurrentEvent()
        if event.type in self.event.events:
            self.event.keyPressCode[self.event.keyCode] = keycode
            self.event._updateQueue(self.evt[event.type](event, keycode))
        event.preventDefault()

    def _isPaused(self, keycode):
        if keycode not in self.keyHeld:
            self.keyHeld[keycode] = {
                'pressed': False,
                'delay': False,
                'time': 0
            }
        key = self.keyHeld[keycode]
        if not key['pressed']:
            key['pressed'] = True
            paused = False
            if self.keyRepeat[0]:
                key['delay'] = True
                key['time'] = self.time.time()
        else:
            paused = True
            if self.keyRepeat[0]:
                time = self.time.time()
                if key['delay']:
                    if time - key['time'] > self.keyRepeat[0]:
                        key['time'] = time
                        key['delay'] = False
                        paused = False
                elif time - key['time'] > self.keyRepeat[1]:
                    key['time'] = time
                    paused = False
        return paused

    def onTouchInitiate(self, event):
        self.event.touchlistener.activate()
        for callback in self._touch_callback:
            if hasattr(callback, 'onTouchInitiate'):
                callback.onTouchInitiate(event)
        self.onTouchStart(event)

    def onTouchStart(self, event):
        for callback in self._touch_callback:
            callback.onTouchStart(event)

    def onTouchEnd(self, event):
        for callback in self._touch_callback:
            callback.onTouchEnd(event)

    def onTouchMove(self, event):
        for callback in self._touch_callback:
            callback.onTouchMove(event)

    def onTouchCancel(self, event):
        for callback in self._touch_callback:
            callback.onTouchCancel(event)

    def preventContextMenu(self, setting=True):
        """
        Control contextmenu event.
        Optional bool setting to prevent event, default to True.
        """
        if setting:
            if self.onContextMenu: return
            element = self.getElement()
            self.onContextMenu = lambda event: event.preventDefault()
            element.addEventListener('contextmenu', self.onContextMenu)
        else:
            if not self.onContextMenu: return
            element = self.getElement()
            element.removeEventListener('contextmenu', self.onContextMenu)
            self.onContextMenu = None

    def resize(self, width, height):
        Surface.resize(self, width, height)
        if self._bufferedimage:
            self.surface.resize(width, height)
        self.surface._display._surface_rect = self.surface.get_rect()

    def set_callback(self, cb):
        if not hasattr(cb, 'run'):
            self.callback = Callback(cb)
        else:
            self.callback = cb

    def load_images(self, images):
        if images:
            image_list = []
            for image in images:
                if isinstance(image, str):
                    image_list.append(image)
                    self.image_list.append(image)
                else:
                    name = image[0]
                    if isinstance(image[1], str):
                        data = image[1]
                    else:
                        data = base64.b64encode(image[1].getvalue())
                    if not data.startswith('data:'):
                        ext = name.strip().split('.')[-1]
                        data = "data:%s;base64,%s" % (ext, data)
                        #data:[<mediatype>][;base64],<data>
                    image_list.append(data)
                    self.image_list.append(name)
            loadImages(image_list, self)
        else:
            self.start()

    def onImagesLoaded(self, images):
        for i, image in enumerate(self.image_list):
            self.images[image] = images[i].getElement()
        self.start()

    def start(self):
        if not self.initialized:
            self.initialized = True
            _wnd.requestAnimationFrame(run)

    def stop(self):
        global run
        run = lambda ts: None
        self.run = lambda: None

    def _get_rect(self):
        if self._rect_num < self._rect_len:
            return self._rect_list[self._rect_num]
        else:
            self._rect_list.append(Rect(0, 0, 0, 0))
            self._rect_len += 1
            return self._rect_list[self._rect_num]

    def update(self, timestamp):
        if not self._framerate:
            self._frametime = timestamp - self._rendertime
            self.run()
        else:
            self._frametime += timestamp - self._rendertime
            if self._frametime > self._framerate:
                self.run()
                self._frametime = 0
        self._rendertime = timestamp

    def render(self):
        while self._rect_num:
            rect = self._rect_list[self._rect_num - 1]
            x, y, width, height = rect.x, rect.y, rect.width, rect.height
            _ctx.drawImage(_img, x, y, width, height, x, y, width, height)
            self._rect_num -= 1

    def run(self):
        self.callback.run()
コード例 #14
0
ファイル: __init__.py プロジェクト: junzew/game-of-life
from pyjsdl.draw import Draw
from pyjsdl.event import Event
from pyjsdl.key import Key
from pyjsdl.mouse import Mouse
from pyjsdl.transform import Transform
from pyjsdl.surfarray import Surfarray
from pyjsdl.color import Color
from pyjsdl.mixer import Mixer
from pyjsdl.time import Time
from pyjsdl import mask
from pyjsdl import font
from pyjsdl import sprite
from pyjsdl import cursors
from pyjsdl.locals import *

time = Time()
display = Display()
image = Image()
draw = Draw()
transform = Transform()
surfarray = Surfarray()
mixer = Mixer()
event = Event()
mouse = Mouse()
key = Key()

init = lambda: None


def quit():
    canvas = display.get_canvas()