Exemplo n.º 1
0
class KeyboardTest(TestCase):
    @patch('event.EventManager')
    def get_keyboard(self, EventManager: Any) -> None:
        self.keyboard = Keyboard(EventManager())

    def setUp(self) -> None:
        self.get_keyboard()

    def test_quit(self) -> None:
        quit_event = [pygame.event.Event(pygame.QUIT, {'unicode': 'esc'})]
        self.keyboard.get_pygame_events = MagicMock(return_value=quit_event)

        self.keyboard.notify(Event.TICK)

        self.keyboard.event_manager.post.assert_called_once_with(Event.QUIT)

    def test_unbound_key_posts_no_events(self) -> None:
        quit_event = [
            pygame.event.Event(pygame.KEYDOWN, {
                'unicode': 'a',
                'key': 97
            })
        ]
        self.keyboard.get_pygame_events = MagicMock(return_value=quit_event)

        self.keyboard.notify(Event.TICK)

        self.keyboard.event_manager.post.never_called()

    def test_bound_key_posts_bound_event(self) -> None:
        self.keyboard.get_binding = MagicMock(return_value=Event.OPEN_SETTINGS)
        event = [
            pygame.event.Event(pygame.KEYDOWN, {
                'unicode': 'x',
                'key': 97
            })
        ]
        self.keyboard.get_pygame_events = MagicMock(return_value=event)

        self.keyboard.notify(Event.TICK)

        self.keyboard.event_manager.post.assert_called_once_with(
            Event.OPEN_SETTINGS)

    def test_mouse_click_posts_mouse_event(self) -> None:
        mouse = (460, 680)
        mouse_event = InputEvent(Event.MOUSE_CLICK, mouse=mouse)
        event = [
            pygame.event.Event(pygame.MOUSEBUTTONDOWN, {
                'unicode': '',
                'key': 97
            })
        ]
        self.keyboard.get_pygame_events = MagicMock(return_value=event)
        self.keyboard.mouse_event = MagicMock(return_value=mouse_event)

        self.keyboard.notify(Event.TICK)

        self.keyboard.event_manager.post.assert_called_once_with(mouse_event)
Exemplo n.º 2
0
    def tick(self, surface, delta, fontmap):
        scr = None

        # Paint the background
        surface.fill(pygame.color.Color("#222222"))

        # Paint game over
        go = fontmap["title"].render("Game Over!", True, pygame.color.Color("#FFFFFF"))
        (w, h) = fontmap["title"].size("Game Over!")
        surface.blit(go, (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT // 4 + h // 2))

        # Paint the score
        txt = "Distance: %0.1fkm" % self.value
        sc = fontmap["score"].render(txt, True, pygame.color.Color("#CCCCCC"))
        (w, h) = fontmap["score"].size(txt)
        surface.blit(sc, (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT // 2 + h // 2))

        # Paint the return to main menu message
        txt = "Press <enter> to return to the Main Menu"
        msg = fontmap["hud"].render(txt, True, pygame.color.Color("#999999"))
        (w, h) = fontmap["hud"].size(txt)
        surface.blit(msg, (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT - h - 10))

        # Check to see if enter is pressed
        if Keyboard.released(pygame.K_RETURN):
            scr = MainMenu

        return scr
Exemplo n.º 3
0
    def tick(self, surface, delta, fontmap):
        scr = None

        # Paint the background
        surface.fill(pygame.color.Color("#222222"))

        # Paint the title
        ttl = fontmap["title"].render(Constants.TITLE, True, pygame.color.Color("#FFFFFF"))
        (w, h) = fontmap["title"].size(Constants.TITLE)
        surface.blit(ttl, (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT // 4 + h // 2))

        # Paint the options
        msel = -1
        for i, option in enumerate(MainMenu.options):
            # Get the bounding box
            (w, h) = fontmap["option"].size(option)
            (x, y) = (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT // 2 + i * h * 2)
            # Determine if the option is highlighted or if the mouse is hovering over it
            m = Mouse.getX() in xrange(x, x + w) and Mouse.getY() in xrange(y, y + h)
            msel = i if m else msel
            s = self.sel == i or m
            # Paint the option
            txt = fontmap["option"].render(option, True, pygame.color.Color("#00FF00" if s else "#CCCCCC"))
            surface.blit(txt, (x, y))

        # Check for input
        if len(MainMenu.options) > 0:
            if Keyboard.released(pygame.K_DOWN):
                # If not at bottom, move the selection down
                Sound.play('menumove')
                self.sel = min(self.sel + 1, len(MainMenu.options) - 1)
            elif Keyboard.released(pygame.K_UP):
                # If not at top, move the selection up
                Sound.play('menumove')
                self.sel = max(0, self.sel - 1)
            elif Keyboard.released(pygame.K_RETURN):
                # Select the highlighted option
                Sound.play('menuselect')
                scr = MainMenu.screens[self.sel]
            elif msel >= 0 and Mouse.leftReleased():
                # Select the option that mouse is hovering over
                Sound.play('menuselect')
                scr = MainMenu.screens[msel]

        return scr
Exemplo n.º 4
0
    def run(self, time_delta):
        if Keyboard.just_pressed("escape"):
            self.parent.running = False

        if Keyboard.just_pressed("r"):
            self.t -= 10

        if Keyboard.pressed("r"):
            self.direction = -1
        else:
            self.direction = 1

        if Mouse.pressed("right"):
            self.direction *= 0.5

        if Mouse.pressed("left"):
            self.direction *= 2.0

        self.t += self.direction
Exemplo n.º 5
0
 def __init__(self):
     sys.path.append(os.path.abspath('.'))
     config = data_make.load()
     self.screen = Screen(config)
     try:
         self.modules = Modules('Games', self.screen)
     except:
         pass
     #self.interface = Interface(self.screen)
     self.clock = pygame.time.Clock()
     pygame.mouse.set_visible(True)
     self.mouse_focus = False
     self._pause = False
     self._fps = 120 #2*2*2*3*5
     self._running = True
     self.timers = Timers(self._fps)
     self.timers.add_new("ta_move", self.screen.textareas.move, 10, type='s')
     self.timers.add_new("pause", lambda:self.screen.indicators.state('pause'), 2, None, 's')
     #self.timers.add_new("focus_test", self.focusTest, 2, type='s')
     #print self.timers.listType('s')
     sys_keys = {
         #(key, KEYUP/KEYDOWN): (func, modifiers expected, modifiers allowed)
         (K_p, KEYDOWN): (self.pause, KMOD_CTRL),
         (K_i, KEYDOWN): (self.edit, KMOD_CTRL),
         #(K_e, KEYDOWN): (lambda:self.screen.textareas[0].edit(not bool(self.screen.textareas[0].edit())), KMOD_CTRL),
         (K_q, KEYDOWN): (self.stop, KMOD_CTRL),
         (K_r, KEYDOWN): (lambda:self.screen.displays.main.fill((random.randint(0,8), random.randint(0, 18), random.randint(1,10), random.randint(1, 20)), 0x81, random.randint(0, 0xffffff), 0), None),
         (K_t, KEYDOWN): (lambda:self.screen.displays.main.put_text((random.randint(0,8), random.randint(0, 18), random.randint(1,10), random.randint(1, 20)), 'test', random.randint(0, 0xffffff), 0), None),
         (K_l, KEYDOWN): (self.test, KMOD_CTRL),
         (K_c, KEYDOWN): (self.compile_conf, KMOD_CTRL),
     }
     self.keyboard = Keyboard(sys_keys, {})
     self.rects = (
     #    (self.screen.textarea1, Rect(self.screen.textarea1)),
     )
     self.clicked = -1
     self.pos = [0,0]
     self.editing = False # <<<<<<<<<<<
     #self.test()
     self.ui = UI(self.screen)
     self.run()
Exemplo n.º 6
0
    def __init__(self) -> None:
        self.event_manager = EventManager()
        super(Game, self).__init__(self.event_manager)
        self.inialize_pygame()

        self.clock: pygame.Clock = Clock()
        self.screen: pygame.Surface = pygame.display.set_mode(
            constants.SCREEN_SIZE)

        self.keyboard = Keyboard(self.event_manager)

        self.state = GameState.LOAD_SCREEN
        self.controller = LaunchController(self.event_manager, self.screen)
Exemplo n.º 7
0
    def __init__(self):

        self.clock = pygame.time.Clock()
        self.running = False
        self.current_mode = None

        self.fps = 30

        self.display = DisplaySystem()

        self.key = Keyboard()
        self.mouse = Mouse()
        self.resman = ResourceManager()
Exemplo n.º 8
0
    def __init__(self):
        pygame.init()
        pygame.mouse.set_visible(1) #Set mouse to visible

        self.clock = pygame.time.Clock()
        self.running = False
        self.current_mode = None

        self.fps = 30

        self.width=768; self.height=768
        self.screen=pygame.display.set_mode((self.width,self.height))

        pygame.display.set_caption("A game")

        self.key = Keyboard()
        self.mouse = Mouse()
Exemplo n.º 9
0
    def tick(self, surface, delta, fontmap):
        scr = None

        # Paint the background
        surface.fill(pygame.color.Color("#222222"))

        # Paint title
        go = fontmap["title"].render("Credits", True, pygame.color.Color("#FFFFFF"))
        (w, h) = fontmap["title"].size("Credits")
        surface.blit(go, (Constants.WIDTH // 2 - w // 2, 60))

        # Paint the sections
        yoff = -200
        for section in ("krx\nProgrammer and Special Effects", "RedSoxFan\nProgrammer",
                        "Spetsnaz\nGame Idea", "s.a.x Software\nSaxMono Font", "Game Made In\nPython with pygame",
                        "Sound Effects Made In\nBFXR + LabChirp", "Music By\nSiriusBeat", "EXE Creation\npy2exe with pygame2exe script"):
            for i, text in enumerate(section.split("\n")):
                ttype = "msgtitle" if i == 0 else "msgbody"
                col = pygame.color.Color("#CCCCCC" if ttype == "msgtitle" else "#888888")
                sc = fontmap[ttype].render(text, True, col)
                (w, h) = fontmap[ttype].size(text)
                surface.blit(sc, (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT // 2 - h // 2 + yoff))
                yoff += h + 2
            yoff += 15

        # Paint the return to main menu message
        txt = "Press <enter> to return to the Main Menu"
        msg = fontmap["hud"].render(txt, True, pygame.color.Color("#999999"))
        (w, h) = fontmap["hud"].size(txt)
        surface.blit(msg, (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT - h - 10))

        # Check to see if enter is pressed
        if Keyboard.released(pygame.K_RETURN):
            Sound.play('menuselect')
            scr = MainMenu

        return scr
Exemplo n.º 10
0
class Game(object):
    def __init__(self):
        pygame.init()
        pygame.mouse.set_visible(1) #Set mouse to visible

        self.clock = pygame.time.Clock()
        self.running = False
        self.current_mode = None

        self.fps = 30

        self.width=768; self.height=768
        self.screen=pygame.display.set_mode((self.width,self.height))

        pygame.display.set_caption("A game")

        self.key = Keyboard()
        self.mouse = Mouse()

    def set_title(self, caption):
        """Set window title to 'caption'"""
        pygame.display.set_caption(caption)

    def start(self): pass
    def stop(self): pass

    def set_mode(self, mode):
        mode._attach_parent(self)
        if self.running:
            self.current_mode.stop()

        self.current_mode = mode

        #Initialize frame variable of given mode so users don't have to call Mode.__init__ (don't like this ugly Python inheritance :<)
        if "frame" not in self.current_mode.__dict__:
            self.current_mode.frame = 0

        if self.running:
            self.current_mode.start()

    def run(self):
        self.start()

        if self.current_mode == None: return

        self.current_mode.start()
        self.running = True

        while(self.running):
            self.clock.tick(self.fps)

            self.check_events()

            #Run a frame of the current mode and render
            self.current_mode.run(1.0 / self.fps) #For now let's just pretend the fps is perfect
            self.current_mode.frame += 1 #Increment frame count of active mode
            self.current_mode.render(self.screen)
            pygame.display.flip()

        self.current_mode.stop()
        self.stop()

        pygame.quit()

    def check_events(self):
        self.key._on_enter_frame()
        self.mouse._on_enter_frame()

        for event in pygame.event.get():
            if   event.type == pygame.QUIT:
                self.running = False #No arguing

            elif event.type == pygame.KEYDOWN:
                #Some alt+key special hotkeys. TODO: Move this elsewhere
                if pygame.key.get_mods() & pygame.KMOD_ALT:
                    if event.key == pygame.K_ESCAPE:
                        self.running = False
                    if event.key == pygame.K_F12:
                        pygame.image.save(self.screen, utils.join_path("user", "screenshot.png"))

                self.key._on_key_down(event)

            elif event.type == pygame.KEYUP:
                self.key._on_key_up(event)

            elif event.type == pygame.MOUSEMOTION:
                self.mouse._on_mouse_motion(event)

            elif event.type == pygame.MOUSEBUTTONDOWN:
                self.mouse._on_mouse_button_down(event)

            elif event.type == pygame.MOUSEBUTTONUP:
                self.mouse._on_mouse_button_up(event)
Exemplo n.º 11
0
    def tick(self, surface, delta, platforms):
        msgs = []
        if self.disphealth > self.health:
            self.disphealth = Arithmetic.clamp(self.health, self.maxhealth, self.disphealth - ceil((self.disphealth - self.health) / 30.0))

        if Settings.GRAPHICS >= 2 and self.innerfire:
            self.generateInnerFire()

        # If alive, tick
        if self.health > 0:
            # Check for a resize
            if Keyboard.down(Constants.GROW_KEY):
                width = min(self.rect.width + Constants.SIZE_INTERVAL, Constants.MAX_PLAYER_WIDTH)
                height = min(self.rect.height + Constants.SIZE_INTERVAL, Constants.MAX_PLAYER_HEIGHT)
                self.image = pygame.transform.scale(self.image, (width, height)).convert_alpha()
                center = self.rect.center
                self.rect.size = self.image.get_rect().size
                self.rect.center = center
                self.__draw_image()
            elif Keyboard.down(Constants.SHRINK_KEY):
                width = max(Constants.MIN_PLAYER_WIDTH, self.rect.width - Constants.SIZE_INTERVAL)
                height = max(Constants.MIN_PLAYER_HEIGHT, self.rect.height - Constants.SIZE_INTERVAL)
                self.image = pygame.transform.scale(self.image, (width, height)).convert_alpha()
                center = self.rect.center
                self.rect.size = self.image.get_rect().size
                self.rect.center = center
                self.__draw_image()
            # If not in the center, fall to center of the screen
            if self.rect.centery < Constants.HEIGHT // 4:
                self.rect.y += ceil(Constants.GRAVITY / Constants.FPS * delta)
                self.rect.y = min(Constants.HEIGHT // 4, self.rect.y)
            else:
                self.ready = True
            # Check collision with platforms
            for p in pygame.sprite.spritecollide(self, platforms, False):
                if not p.can_break(self.force):
                    msgs.append(Message("Splat\n-%d" % self.health, self.rect.right + 100, self.rect.centery, "bad"))
                    self.health = 0
                    break
                elif p.can_splinter(self.force):
                    Sound.play('hit{}'.format(randint(1, 3)))
                    self.health = max(0, self.health - p.damage)
                    self.destroyPlatform(p, True)
                    p.kill()
                    msgs.append(Message("Splinter\n-%d" % p.damage, self.rect.right + 100, self.rect.centery, "bad"))
                else:
                    Sound.play('hit{}'.format(randint(1, 3)))
                    self.destroyPlatform(p, False)
                    p.kill()
        else:
            # Death sequence
            if self.rect.width > 2:
                # Shrink until tiny
                width = Arithmetic.clamp(2, Constants.MAX_PLAYER_WIDTH, self.rect.width - 3 * Constants.SIZE_INTERVAL)
                height = Arithmetic.clamp(2, Constants.MAX_PLAYER_HEIGHT, self.rect.height - 3 * Constants.SIZE_INTERVAL)
                self.image = pygame.transform.scale(self.image, (width, height)).convert_alpha()
                center = self.rect.center
                self.rect.size = self.image.get_rect().size
                self.rect.center = center
                self.__draw_image()
            elif not self.sploded:
                # splode
                Sound.play('explode')
                self.sploded = True
                self.innerfire = False
                self.image.fill(pygame.Color(0, 0, 0))

                # Line particles
                for i in xrange(randint(20, 40)):
                    angle = random() * 2.0 * pi
                    speed = random() * 5.0 + 2.5
                    rotRate = random() * (0.5 * pi) - (0.25 * pi)
                    size = randint(3, 17)
                    self.particles.append(FlippyLineParticle([self.rect.center[0], self.rect.center[1]], size, [speed * cos(angle), speed * sin(angle)], pygame.Color(0, 255, 0), random() * 2.0 * pi, rotRate, mingfx=1))

                # Fire particles
                for i in xrange(randint(200, 500)):
                    angle = random() * 2.0 * pi
                    speed = random() * 5.0 + 1.0
                    size = randint(1, 3)
                    self.particles.append(FadingParticle([self.rect.center[0], self.rect.center[1]], size, [speed * cos(angle), speed * sin(angle)], pygame.Color(0, 255, 0), 6, mingfx=1))

        # If on screen, paint
        if self.rect.bottom > 0:
            surface.blit(self.image, (self.rect.x, self.rect.y))
        return msgs
Exemplo n.º 12
0
    def tick(self, surface, delta, fontmap):
        scr = None

        # Paint the background
        surface.fill(pygame.color.Color("#222222"))

        # Paint title
        go = fontmap["title"].render("Info", True, pygame.color.Color("#FFFFFF"))
        (w, h) = fontmap["title"].size("Info")
        surface.blit(go, (Constants.WIDTH // 2 - w // 2, 100))

        # Paint the sections
        yoff = 200
        for section in ("Objective\nTo get as far down the abyss as possible",
                        "Controls\nUp Arrow - Grow\nDown Arrow - Shrink",
                        "How To Play\n[Grow or shrink the player to either reduce or increase force. You "
                        "will need to have enough force to break the platform (40% of the width). If you "
                        "don't, you will splat and die. Also, if you have enough force to break the "
                        "platform, but not cleanly (60% of the width), you will cause the platform "
                        "to splinter, which will damage you.]"):
            for i, text in enumerate(section.split("\n")):
                ttype = "msgtitle" if i == 0 else "msgbody"
                col = pygame.color.Color("#CCCCCC" if ttype == "msgtitle" else "#888888")
                if text.startswith("[") and text.endswith("]"):
                    words = text[1:-1].split(" ")
                    text = ""
                    while len(words) > 0:
                        (w, h) = fontmap[ttype].size("%s %s" % (text, words[0]))
                        if w < Constants.WIDTH - 20:
                            text = "%s %s" % (text, words[0])
                            words = words[1:]
                        else:
                            sc = fontmap[ttype].render(text, True, col)
                            (w, h) = fontmap[ttype].size(text)
                            surface.blit(sc, (Constants.WIDTH // 2 - w // 2, yoff))
                            yoff += h + 2
                            text = ""
                    if len(text) > 0:
                        sc = fontmap[ttype].render(text, True, col)
                        (w, h) = fontmap[ttype].size(text)
                        surface.blit(sc, (Constants.WIDTH // 2 - w // 2, yoff))
                        yoff += h + 2
                else:
                    # Line
                    sc = fontmap[ttype].render(text, True, col)
                    (w, h) = fontmap[ttype].size(text)
                    surface.blit(sc, (Constants.WIDTH // 2 - w // 2, yoff))
                    yoff += h + 2
            yoff += 20

        # Paint the return to main menu message
        txt = "Press <enter> to return to the Main Menu"
        msg = fontmap["hud"].render(txt, True, pygame.color.Color("#999999"))
        (w, h) = fontmap["hud"].size(txt)
        surface.blit(msg, (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT - h - 10))

        # Check to see if enter is pressed
        if Keyboard.released(pygame.K_RETURN):
            Sound.play('menuselect')
            scr = MainMenu

        return scr
Exemplo n.º 13
0
    def tick(self, surface, delta, fontmap):
        scr = None

        # Paint the background
        surface.fill(pygame.color.Color("#222222"))

        # Paint the title
        ttl = fontmap["title"].render("Settings", True, pygame.color.Color("#FFFFFF"))
        (w, h) = fontmap["title"].size("Settings")
        surface.blit(ttl, (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT // 4 + h // 2))

        # Paint the options
        mcb = None
        yoff = 0
        for i, key in enumerate(sorted(self.options.keys())):
            # Get the bounding box
            (w, h) = fontmap["msgtitle"].size(key.replace("~", ""))
            (x, y) = (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT // 2 + yoff)
            # Paint the option
            txt = fontmap["msgtitle"].render(key.replace("~", ""), True, pygame.color.Color("#CCCCCC"))
            surface.blit(txt, (x, y))
            yoff += h + 2

            for j, (txt, val, cb) in enumerate(self.options[key]):
                # Get the bounding box
                (w, h) = fontmap["msgbody"].size(txt)
                (x, y) = (Constants.WIDTH // 2 - w // 2, Constants.HEIGHT // 2 + yoff)
                # Determine if the option is highlighted or if the mouse is hovering over it
                m = Mouse.getX() in xrange(x, x + w) and Mouse.getY() in xrange(y, y + h)
                mcb = cb if m else mcb
                s = self.sel == (i, j) or m
                # Paint the option
                col = "#008800" if val() else "#CCCCCC"
                txt = fontmap["msgbody"].render(txt, True, pygame.color.Color("#00FF00" if s else col))
                surface.blit(txt, (x, y))
                yoff += h + 2

            yoff += 20

        # Check for input
        if len(MainMenu.options) > 0:
            if Keyboard.released(pygame.K_DOWN):
                # If not at bottom, move the selection down
                if self.sel[1] < len(self.options[sorted(self.options.keys())[self.sel[0]]]) - 1:
                    self.sel = (self.sel[0], self.sel[1] + 1)
                    Sound.play('menumove')
                elif self.sel[0] < len(self.options.keys()) - 1:
                    self.sel = (self.sel[0] + 1, 0)
                    Sound.play('menumove')
            elif Keyboard.released(pygame.K_UP):
                # If not at top, move the selection up
                if self.sel[1] > 0:
                    self.sel = (self.sel[0], self.sel[1] - 1)
                    Sound.play('menumove')
                elif self.sel[0] > 0:
                    self.sel = (self.sel[0] - 1, len(self.options[sorted(self.options.keys())[self.sel[0] - 1]]) - 1)
                    Sound.play('menumove')
            elif Keyboard.released(pygame.K_RETURN):
                # Select the highlighted option
                scr = self.options[sorted(self.options.keys())[self.sel[0]]][self.sel[1]][2]()
                Sound.play('menuselect')
            elif mcb is not None and Mouse.leftReleased():
                # Select the option that mouse is hovering over
                scr = mcb()
                Sound.play('menuselect')

        return scr
Exemplo n.º 14
0
class Game(object):
    def __init__(self):

        self.clock = pygame.time.Clock()
        self.running = False
        self.current_mode = None

        self.fps = 30

        self.display = DisplaySystem()

        self.key = Keyboard()
        self.mouse = Mouse()
        self.resman = ResourceManager()


    def on_start(self): pass
    def on_stop(self): pass

    def start(self):
        self.run()

    def stop(self):
        self.running = False

    def set_mode(self, mode):
        mode._attach_parent(self)
        if self.running:
            self.current_mode.stop()

        self.current_mode = mode

        if self.running:
            self.current_mode.start()

    def run(self):
        self.on_start()

        if self.current_mode == None: return

        self.current_mode.start()
        self.running = True

        while(self.running):
            time_elapsed = self.clock.tick(self.fps)

            self.check_events()

            #Run a frame of the current mode
            self.current_mode.run(time_elapsed) #For now let's just pretend the fps is perfect
            self.current_mode.scene.update(time_elapsed)
            self.current_mode.frame += 1 #Increment frame count of active mode

            self.current_mode.camera.render()

            self.display.blit(self.current_mode.camera.surface)

        self.current_mode.stop()
        self.on_stop()

        pygame.quit()

    def check_events(self):
        self.key._on_enter_frame()
        self.mouse._on_enter_frame()
        self.resman._on_enter_frame()
        self.display._on_enter_frame()

        for event in pygame.event.get():
            if   event.type == pygame.QUIT:
                self.running = False #No arguing

            elif event.type == pygame.KEYDOWN:
                #Some alt+key special hotkeys. TODO: Move this elsewhere
                if pygame.key.get_mods() & pygame.KMOD_ALT:
                    if event.key == pygame.K_ESCAPE:
                        self.running = False
                    if event.key == pygame.K_F12:
                        pygame.image.save(self.screen, utils.join_path("user", "screenshot.png"))

                self.key._on_key_down(event)

            elif event.type == pygame.KEYUP:
                self.key._on_key_up(event)

            elif event.type == pygame.MOUSEMOTION:
                self.mouse._on_mouse_motion(event)

            elif event.type == pygame.MOUSEBUTTONDOWN:
                self.mouse._on_mouse_button_down(event)

            elif event.type == pygame.MOUSEBUTTONUP:
                self.mouse._on_mouse_button_up(event)
Exemplo n.º 15
0
class Game(object):
    def __init__(self):
        sys.path.append(os.path.abspath('.'))
        config = data_make.load()
        self.screen = Screen(config)
        try:
            self.modules = Modules('Games', self.screen)
        except:
            pass
        #self.interface = Interface(self.screen)
        self.clock = pygame.time.Clock()
        pygame.mouse.set_visible(True)
        self.mouse_focus = False
        self._pause = False
        self._fps = 120 #2*2*2*3*5
        self._running = True
        self.timers = Timers(self._fps)
        self.timers.add_new("ta_move", self.screen.textareas.move, 10, type='s')
        self.timers.add_new("pause", lambda:self.screen.indicators.state('pause'), 2, None, 's')
        #self.timers.add_new("focus_test", self.focusTest, 2, type='s')
        #print self.timers.listType('s')
        sys_keys = {
            #(key, KEYUP/KEYDOWN): (func, modifiers expected, modifiers allowed)
            (K_p, KEYDOWN): (self.pause, KMOD_CTRL),
            (K_i, KEYDOWN): (self.edit, KMOD_CTRL),
            #(K_e, KEYDOWN): (lambda:self.screen.textareas[0].edit(not bool(self.screen.textareas[0].edit())), KMOD_CTRL),
            (K_q, KEYDOWN): (self.stop, KMOD_CTRL),
            (K_r, KEYDOWN): (lambda:self.screen.displays.main.fill((random.randint(0,8), random.randint(0, 18), random.randint(1,10), random.randint(1, 20)), 0x81, random.randint(0, 0xffffff), 0), None),
            (K_t, KEYDOWN): (lambda:self.screen.displays.main.put_text((random.randint(0,8), random.randint(0, 18), random.randint(1,10), random.randint(1, 20)), 'test', random.randint(0, 0xffffff), 0), None),
            (K_l, KEYDOWN): (self.test, KMOD_CTRL),
            (K_c, KEYDOWN): (self.compile_conf, KMOD_CTRL),
        }
        self.keyboard = Keyboard(sys_keys, {})
        self.rects = (
        #    (self.screen.textarea1, Rect(self.screen.textarea1)),
        )
        self.clicked = -1
        self.pos = [0,0]
        self.editing = False # <<<<<<<<<<<
        #self.test()
        self.ui = UI(self.screen)
        self.run()

    def fps(self, fps = None):
        """set frame rate

        fps is frame rate value
        Return old frame rate
        """
        tmp = self._fps
        if fps:
            self._fps = fps
        return tmp

    def mouse(self, event):
        for i in  range(len(self.rects)):
            if self.rects[i][1].collidepoint(*event.pos):
                try:
                    if event.type in (MOUSEBUTTONDOWN, MOUSEBUTTONUP):
                        if event.button == 1:
                            self.rects[i][0].on_mouse_click(event.pos)
                    elif event.type == MOUSEMOTION:
                        if event.buttons[0]:
                            print (event.pos[0]-self.pos[0], event.pos[1]-self.pos[1])
                            self.rects[i][0].on_mouse_move(event.pos,
                                (event.pos[0]-self.pos[0], event.pos[1]-self.pos[1]))
                except AttributeError:
                    pass
                else:
                    self.clicked = i
                    break

    def test(self):
        try:
            test = __import__('test')
            test.test(self.screen)
        except:
            pass

    def compile_conf(self):
        try:
            cfg = __import__('config')
            data_make.pack(cfg.config, 'config.dat')
            print 'new config.dat created'
        except ImportError:
            print 'No config.py file found'

    def pause(self, state=None):
        if state is None:
            self._pause = not self._pause
        else:
            self._pause = bool(state)
        if self._pause == True:
            self.screen.indicators.state('pause', True)
            self.timers.unpause("pause")
        else:
            self.timers.pause("pause")
            self.screen.indicators.state('pause', False)

    def stop(self):
        self._running = False

    def edit(self, action=''):
        if action == True and self.editing == False:
            print "Input mode"+'<'*10
            self.editing = True
            self.keyboard.mode('i', self.edit)
            self.screen.textareas.main.edit(True)
            self.timers.pause("ta_move")
            #self.timers.add_new("ta_blink", self.screen.textareas.main.blink, 3, type='s')
        elif action == False and self.editing == True:
            pass
        else:
            print "editing:", action
            #self.screen.textareas.main.replace(str[0]+' ')
            self.screen.textareas.main.edit(str[1])

    def run(self):
        while self._running:
            for event in pygame.event.get():
                if event.type == QUIT:
                    return
                if event.type == ACTIVEEVENT:
                    if event.state in (2, 6): # APPINPUTFOCUS and APPACTIVE
                        if event.gain == 0:
                            #prev_fps, self._fps = self._fps, 2
                            #self.timers.add_new(lambda:self.screen.indicators.state('pause'), 2)
                            self.prev_fps, self._fps = self._fps, 10
                            self.timers.add_new("pause", lambda:self.screen.indicators.state('pause'), 10, 0, 's')
                            print ">> Lost input focus <<"
                        else:
                            self._fps = self.prev_fps
                            self.timers.add_new("pause", lambda:self.screen.indicators.state('pause'), 10, None, 's')
                            self.screen.indicators.state('pause', False)
                            print ">> Gain input focus <<"
                elif event.type in (KEYDOWN, KEYUP):
                    self.keyboard.process(event.type, event.key, event.mod)
            self.screen.update()
            self.timers.tick()
            self.clock.tick(self._fps)
Exemplo n.º 16
0
 def get_keyboard(self, EventManager: Any) -> None:
     self.keyboard = Keyboard(EventManager())