0
我有問題pygame的瞭解遊戲場景管理器(FSM),我嘗試從這個網站複製:https://nicolasivanhoe.wordpress.com/2014/03/10/game-scene-manager-in-python-pygame/爲什麼場景將場景管理器作爲參數?
我會複製代碼:
# -*- encoding: utf-8 -*-
# Modules
import pygame, sys
class Director:
"""Represents the main object of the game.
The Director object keeps the game on, and takes care of updating it,
drawing it and propagate events.
This object must be used with Scene objects that are defined later."""
def __init__(self):
self.screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Game Name")
self.scene = None
self.quit_flag = False
self.clock = pygame.time.Clock()
def loop(self):
"Main game loop."
while not self.quit_flag:
time = self.clock.tick(60)
# Exit events
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.quit()
# Detect events
self.scene.on_event()
# Update scene
self.scene.on_update()
# Draw the screen
self.scene.on_draw(self.screen)
pygame.display.flip()
def change_scene(self, scene):
"Changes the current scene."
self.scene = scene
def quit(self):
self.quit_flag = True
class Scene:
"""Represents a scene of the game.
Scenes must be created inheriting this class attributes
in order to be used afterwards as menus, introduction screens,
etc."""
def __init__(self, director):
self.director = director
def on_update(self):
"Called from the director and defined on the subclass."
raise NotImplementedError("on_update abstract method must be defined in subclass.")
def on_event(self, event):
"Called when a specific event is detected in the loop."
raise NotImplementedError("on_event abstract method must be defined in subclass.")
def on_draw(self, screen):
"Se llama cuando se quiere dibujar la pantalla."
raise NotImplementedError("on_draw abstract method must be defined in subclass.")
class SceneHome(Scene):
""" Welcome screen of the game, the first one to be loaded."""
def __init__(self, director):
Scene.__init__(self, director)
def on_update(self):
pass
def on_event(self):
pass
def on_draw(self):
pass
def main():
dir = Director()
scene = SceneHome(dir)
dir.change_scene(scene)
dir.loop()
if __name__ == '__main__':
pygame.init()
main()
在主要功能導演對象和場景對象被實例化。我明白那個。然後它調用方法change_scene並傳遞scenehome對象。但我不明白爲什麼導演對象是SceneHome類中的參數。它似乎什麼都不做。它看起來像是一個通告,但我不知道它的作用。爲什麼需要Scene類中的導演?
非常感謝! –