Prg2/design patterns 1
- This is part of Programming 2 2563
เนื้อหา
Basic information
- Game Programming Patterns by Robert Nystrom
- Refactoring.Guru
- Patterns covered this week
- Observer: wikipedia, game programmming patterns
- Command: wikipedia, game programmming patterns
- State: wikipedia, game programmming patterns
- Singleton: wikipedia, game programmming patterns
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))