lordmauve / pgzero

A zero-boilerplate games programming framework for Python 3, based on Pygame.
https://pygame-zero.readthedocs.io/
GNU Lesser General Public License v3.0
536 stars 189 forks source link

I want to use the code of pgzero to make a new game engine #259

Closed streetartist closed 3 years ago

streetartist commented 3 years ago

I Want to use the code of pgzero to make a new engine named Scrawl.

The engine is more similar to Scratch than pgzero.

I Am here to

A Scrawl project is like this(I Think the code is easy to understand)

I Use yield to make the muilttask, you can use while true, and make clone, broadcast function.

from scrawl import Scene, Sprite, Game

class Cat(Sprite):
    def __init__(self):
        self.image = "cat.png"

    def main(self):
        while True:
            self.move(10)
            yield 1000
            self.clone()

    def event(self):
        self.say("hello")

    def clones(self):
        self.turn_right(10)

class Background(Scene):
    def __init__(self):
        self.image = "bg.png"

    def main(self):
        while True:
            yield 500
            self.broadcast("event")

class Main(Game):
    def __init__(self):
        self.scene = Background()
        self.sprite = [
            Cat(),
        ]

Main().run(engine="pygame")
lordmauve commented 3 years ago

Pygame Zero is LGPL so you're welcome to do that as long as your new engine is licensed LGPL also.

The thing you are looking for is coroutines. I've already done a lot of work on coroutines in Wasabi2d: https://wasabi2d.readthedocs.io/en/latest/coros.html (these docs are lagging where the engine is, it is on my to-do list to write new docs).

I have been trying to work out whether coroutines belong in Pygame Zero. I think the fact that they are in Scratch is in the plus column, but I think the syntax and mental model to use them in Python might be too much complexity for complete programming beginners (and their teachers).

lordmauve commented 3 years ago

I think your approach is a bit limited if the only way you can create a coroutine here is as the main() method of one of these objects (Sprite, Scene, Game etc). You can generalise this to allow any method or function to be a coroutine:

class Cat(Sprite):
    def __init__(self):
        self.image = "cat.png"

    async def main(self):
        self.start(self.listen_broadcast())
        while True:
            self.move(10)
            await sleep(1)
            self.clone()

    async def listen_broadcast(self):
        while True:
            await listen('event')
            self.clone()

class Main(Game):
    async def main():
        self.start(Cat().main())
        while True:
            await sleep(0.5)
            broadcast('event')

Main().run()