简体   繁体   中英

Pyglet Into Class

Given that so far I have always used Pygame, I wanted to start using Pyglet, to understand a little how it works.

import pyglet, os

class runGame():
    widthDisplay = 1024
    heightDiplay = 576
    title = "Pokémon Life and Death: Esploratori del proprio Destino"

    wra = pyglet.image.load("wra.png")
    wrb = pyglet.image.load("wrb.png")

    def __init__(self):
        platform = pyglet.window.get_platform()
        display = platform.get_default_display()
        screen = display.get_default_screen()
        self.widthScreen = screen.width
        self.heightScreen = screen.height
        self.xDisplay = int(self.widthScreen / 2 - self.widthDisplay / 2)
        self.yDisplay = int(self.heightScreen / 2 - self.heightDiplay / 2)
        self.Display = pyglet.window.Window(width=self.widthDisplay, height=self.heightDiplay, caption=self.title, resizable=False)
        self.Display.set_location(self.xDisplay, self.yDisplay)
        pyglet.app.run()

game = runGame()

Up to here everything is fine and everything works correctly. But I was wrong, in the sense, now that I have to draw something, how should I do? In the sense, can Pyglet stay in a class like Pygame or not?

The marked solution might solve the problem.
However, in my opinion it doesn't really add more functionality than you can already achieve.

If you truly want to make Pyglet into a class, you actually gotta inherit something, or make use of the possibility of programming in a OOP way i recon.

Here's my two cents:

import pyglet
from pyglet.gl import *
from collections import OrderedDict
from time import time

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=1024, height=576, caption="Pokémon Life and Death: Esploratori del proprio Destino", fps=True, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)

        platform = pyglet.window.get_platform()
        display = platform.get_default_display()
        screen = display.get_default_screen()

        self.xDisplay = int(screen.width / 2 - self.width / 2)
        self.yDisplay = int(screen.height / 2 - self.height / 2)
        self.set_location(self.xDisplay, self.yDisplay)

        self.sprites = OrderedDict()

        if fps:
            self.sprites['fps_label'] = pyglet.text.Label('0 fps', x=10, y=10)
            self.last_update = time()
            self.fps_count = 0

        self.keys = OrderedDict()

        self.mouse_x = 0
        self.mouse_y = 0

        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_mouse_motion(self, x, y, dx, dy):
        self.mouse_x = x
        self.mouse_y = y

    def on_mouse_release(self, x, y, button, modifiers):
        print('Released mouse at {}x{}'.format(x, y))


    def on_mouse_press(self, x, y, button, modifiers):
        if button == 1:
            print('Pressed mouse at {}x{}'.format(x, y))


    def on_mouse_drag(self, x, y, dx, dy, button, modifiers):
        self.drag = True
        print('Dragging mouse at {}x{}'.format(x, y))

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        self.keys[symbol] = True

    def pre_render(self):
        pass

    def render(self):
        self.clear()

        # FPS stuff (if you want to)
        self.fps_count += 1
        if time() - self.last_update > 1: # 1 sec passed
            self.sprites['fps_label'].text = str(self.fps_count)
            self.fps_count = 0
            self.last_update = time()

        #self.bg.draw()
        self.pre_render()

        for sprite in self.sprites:
            self.sprites[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()

if __name__ == '__main__':
    x = main()
    x.run()

This way, you can actually interact with your class as if it were the pyglet class. For instance, you got on_key_press without having to use decorators etc.

You should make more functions for each thing you are doing. For example if you want to make a line you might have

import pyglet, os

class runGame():
    widthDisplay = 1024
    heightDiplay = 576
    title = "Pokémon Life and Death: Esploratori del proprio Destino"

    wra = pyglet.image.load("wra.png")
    wrb = pyglet.image.load("wrb.png")

    def __init__(self):
        platform = pyglet.window.get_platform()
        display = platform.get_default_display()
        screen = display.get_default_screen()
        self.widthScreen = screen.width
        self.heightScreen = screen.height
        self.xDisplay = int(self.widthScreen / 2 - self.widthDisplay / 2)
        self.yDisplay = int(self.heightScreen / 2 - self.heightDiplay / 2)
        self.Display = pyglet.window.Window(width=self.widthDisplay,    height=self.heightDiplay, caption=self.title, resizable=False)
        self.Display.set_location(self.xDisplay, self.yDisplay)
        pyglet.app.run()

    def drawLine(x, y):
        drawLine(x, y)

You will have to make the functions based on what you want to do, but if you aren't going to use the runGame class multiple times before you kill the program, you shouldn't use OOP programming and use Procedural Programming.

You can create a custom pyglet window, by inheriting from the pyglet.window.Window class. After that in your init method call the super classes init (this will call the the init inside pyglet.window.Window class )Then overwrite the inherited methods (on_draw, on_key_press, on_key_release etc.). After that create an update method, which will be called by the pyglet.clock.schedule_interval 60 times in a second.Lastly just call the pyglet.app.run() method.

import pyglet


class GameWindow(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def on_draw(self):
        self.clear()

    def on_mouse_press(self, x, y, button, modifiers):
        pass

    def on_mouse_release(self, x, y, button, modifiers):
        pass

    def on_mouse_motion(self, x, y, dx, dy):
        pass

    def update(self, dt):
        pass

if __name__ == "__main__":
    window = GameWindow(1280, 720, "My Window", resizable=False)
    pyglet.clock.schedule_interval(window.update, 1/60.0)
    pyglet.app.run() 

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