简体   繁体   中英

Python and Pyglet input

Total python beginner here.

I'm trying to make a game with the Python library Pyglet. It's been working great until I got to the part where I need the input.

I've followed the examples and docs and my code looks something like this. I will only focus on the mouse input for now as the keyboard input seems to work in the same way.

    import pyglet
    import button

from pyglet.window import key

class GameWindow(pyglet.window.Window):
    def __init__(self):
        super(GameWindow, self).__init__()
        self.button = button.Button()

    def on_draw(self):
        self.clear()

    def on_mouse_press(self, x, y, button, modifiers):
        self.button.on_mouse_press(x, y, button, modifiers)
        print("mouse pressed")

    def on_key_press(self, symbol, modifiers):
        print("key pressed")

    def on_mouse_motion(self, x, y, dx, dy):
        print("mouse moved")

    def update(dt):
        pass



#initializes window and keyboard
window = GameWindow()
keys = key.KeyStateHandler()
window.push_handlers(keys)

pyglet.clock.schedule_interval(GameWindow.update, 1/60.0)

if __name__ == '__main__':

    pyglet.app.run()

The Code works just fine but my question is this: Is this the correct way to handle input? Should I really send the parameters manually like that to my button class? Is it not possible for my button class to override the function for input so the button gathers the input itself?

Is it possible to create a window like I am and gather the input in another unrelated class like my Button class for example?

as of now I have to send the input to the buttons, the chat window, the physicsentities and to some other places. im afraid im doing it backwards and it will bite me in the ass later.

This is a basic skeleton of a good Pyglet class.
Modify it to your liking, the important thing here is that you handle mouse and keyboard I/O seperately.

import pyglet
from pyglet.gl import *

# Optional audio outputs (Linux examples):
# pyglet.options['audio'] = ('alsa', 'openal', 'silent')
key = pyglet.window.key

class Spr(pyglet.sprite.Sprite):
    def __init__(self, texture, x=None, y=None, moveable=True):
        self.texture = pyglet.image.load(texture)
        super(Spr, self).__init__(self.texture)
        self.moveable = moveable

    def move(self, x, y):
        if self.moveable:
            self.x += x
            self.y += y

class main(pyglet.window.Window):
    def __init__ (self):
        super(main, self).__init__(800, 800, fullscreen = False)
        self.x, self.y = 0, 0

        self.bg = pyglet.sprite.Sprite(pyglet.image.load('background.jpg'))
        self.sprites = {'SuperMario' : Spr('mario.jpg')}
        self.player = pyglet.media.Player()
        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_key_press(self, symbol, modifiers):
        # Do something when a key is pressed?
        # Pause the audio for instance?
        # use `if symbol == key.SPACE: ...`

        # This is just an example of how you could load the audio.
        # You could also do a standard input() call and enter a string
        # on the command line.
        if symbol == key.ENTER:
            self.player.queue(media.load('beep.mp3', streaming = False))
            if nog self.player.playing:
                self.player.play()
        if symbol == key.ESC: # [ESC]
            self.alive = 0
        elif symbol == key.LEFT:
            self.sprites['SuperMario'].move(-1, 0)
        #elif symbol == key.RIGHT: ...

    def render(self):
        self.clear()
        self.bg.draw()

        # self.sprites is a dictionary where you store sprites
        # to be rendered, if you have any.
        for sprite_name, sprite in self.sprites.items():
            sprite.draw()

        self.flip()

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()
        self.player.delete() # Free resources. (Not really needed but as an example)

x = main()
x.run()

This is an example of how you can play the sound beep.mp3 when hitting Enter and move a character of your liking to the left.

I'm not sure what you question precicely is, but this is the the class I've come to understand gives you the best performance for your buck. if you can improve it further please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM