Prg2/design patterns 1

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
This is part of Programming 2 2563

Basic information

Codes

Observer Pattern (OO version)

File: gamelib.py
class GameApp(ttk.Frame): 
    def __init__(self, parent, canvas_width=800, canvas_height=500, update_delay=33):
        # ...
        self.on_key_pressed_observers = []
    
    # ...
 
    def register_on_key_pressed_observer(self, observer):
        self.on_key_pressed_observers.append(observer)

    def on_key_pressed(self, event):
        for observer in self.on_key_pressed_observers:
            observer.notify(event)
File: monkeys.py
class MonkeyGame(GameApp):
    class AppObserver:
        def __init__(self, app):
            self.app = app

    class SpeedAdjustmentObserver(AppObserver):
        def notify(self, event):
            app = self.app
            if event.char == '+':
                if app.speed < 10:
                    app.speed += 1
                    app.update_speed_text()
                    
            if event.char == '-':
                if app.speed > 1:
                    app.speed -= 1
                    app.update_speed_text()

    class BananaThrowingObserver(AppObserver):
        def notify(self, event):
            app = self.app
            if event.char == ' ':
                if not app.banana.is_moving:
                    app.banana.set_speed(3 * app.speed, 5 * app.speed)
                    app.banana.reset()
                    app.banana.start()

    # ...
        
    def init_game(self):
        # ...

        self.register_on_key_pressed_observer(MonkeyGame.SpeedAdjustmentObserver(self))
        self.register_on_key_pressed_observer(MonkeyGame.BananaThrowingObserver(self))

Observer Pattern (functions)

Command Pattern

State Pattern