How to use pinglet in the classroom

In all the tutorials on the Internet I've seen with Pyglet, it doesn't seem that any of them used classes to store an instance of pyglet.window.Window. For example, most textbooks seem to be something like

import pyglet

game_window = pyglet.window.Window()

@game_window.event
def on_draw():
    #dostuff

while __name__ == "__main__":
    pyglet.app.run()

I have problems restructuring this code into a class. My code that is designed for this is here:

import pyglet
from pyglet.gl import *
from Board import Board

class Frontend:
    def __init__(self,xs, ys):
        self.GameInstance = Board(xs,ys)
        self.GameWindow = pyglet.window.Window(width=512, height=512,visible=False)

    @GameWindow.event
    def on_draw(self):
        self.GameWindow.clear()

f = Frontend()

When I run this code, I get the following error:

Traceback (most recent call last):
  File "C:/Users/PycharmProjects/Nothing/2048/Frontend.py", line 7, in <module>
    class Frontend:
  File "C:/Users/PycharmProjects/Nothing/2048/Frontend.py", line 13, in Frontend
    @GameWindow.event
NameError: name 'GameWindow' is not defined

When I replace @GameWindow.eventwith @self.GameWindow.eventin an attempt to resolve the NameE error, I get:

Traceback (most recent call last):
    File "C:/Users/PycharmProjects/Nothing/2048/Frontend.py", line 7, in <module>
    class Frontend:
    File "C:/Users/PycharmProjects/Nothing/2048/Frontend.py", line 13, in Frontend
    @self.GameWindow.event
NameError: name 'self' is not defined

What i expect. However, I am not sure why this code does not work - can someone explain why and how to fix it?

+5
source share
3

Window. :

class Frontend(pyglet.window.Window):
    def __init__(self, xs, ys):
        self.GameInstance = Board(xs,ys)
        super().__init__(width=512, height=512,visible=False)

    def on_draw(self):
        self.clear()

, Frontend . Frontend, - :

class Frontend:
    window = pyglet.window.Window()
    def __init__(self):
        ...
    @window.event
    def on_draw():
        ...
+5

ragezor, .

, , EventDispatcher: http://pyglet.org/doc-current/programming_guide/events.html#creating-your-own-event-dispatcher

, , Frontend, . . , , , , Window, , Window .

(, , ragezor ):

class Frontend:

def __init__(self,xs, ys):
    self.GameInstance = Board(xs,ys)
    self.GameWindow = pyglet.window.Window(width=512, height=512,visible=False)

    self.on_draw = self.GameWindow.event(self.on_draw)

def on_draw(self):
    self.GameWindow.clear()

, @GameWindow.event .

, camelcase , PEP8 . game_window.

+2

I guess you need to do

@self.Gamewindow.event
-1
source

Source: https://habr.com/ru/post/1547638/


All Articles