86 lines
2.9 KiB
Python
86 lines
2.9 KiB
Python
import pygame
|
|
from dataclasses import dataclass, replace
|
|
|
|
from game import Game
|
|
|
|
MAX_HISTORY = 5
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Doodle:
|
|
strokes: tuple = () # Tuple von Strichen, jeder Strich = Tuple von Punkten
|
|
drawing: bool = False # Stift gerade aufgesetzt?
|
|
history: tuple = () # alte Strich-Zustände, älteste zuerst
|
|
|
|
def start_stroke(self, pos):
|
|
"""Maustaste gedrückt: neuer Strich, alter Zustand wandert in die Historie."""
|
|
history = (self.history + (self.strokes,))[-MAX_HISTORY:]
|
|
return replace(self,
|
|
strokes=self.strokes + ((pos,),),
|
|
drawing=True,
|
|
history=history)
|
|
|
|
def add_point(self, pos):
|
|
"""Mausbewegung: Punkt an den aktuellen Strich hängen (nur bei aufgesetztem Stift)."""
|
|
if not self.drawing:
|
|
return self
|
|
current = self.strokes[-1] + (pos,)
|
|
return replace(self, strokes=self.strokes[:-1] + (current,))
|
|
|
|
def end_stroke(self):
|
|
"""Maustaste losgelassen: Stift abheben."""
|
|
return replace(self, drawing=False)
|
|
|
|
def undo(self):
|
|
"""Backspace: letzten Zustand aus der Historie wiederherstellen."""
|
|
if not self.history:
|
|
return self
|
|
return replace(self,
|
|
strokes=self.history[-1],
|
|
drawing=False,
|
|
history=self.history[:-1])
|
|
|
|
|
|
class DoodleGame(Game):
|
|
def __init__(self):
|
|
super().__init__("Undo Doodle", 60, (640, 480))
|
|
self.doodle = Doodle()
|
|
|
|
def handle_event(self, event) -> None:
|
|
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
|
|
self.doodle = self.doodle.start_stroke(event.pos)
|
|
elif event.type == pygame.MOUSEMOTION:
|
|
self.doodle = self.doodle.add_point(event.pos)
|
|
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
|
|
self.doodle = self.doodle.end_stroke()
|
|
elif event.type == pygame.KEYDOWN and event.key == pygame.K_BACKSPACE:
|
|
self.doodle = self.doodle.undo()
|
|
else:
|
|
return # andere Events nicht ausgeben
|
|
self.debug_print()
|
|
|
|
def debug_print(self) -> None:
|
|
d = self.doodle
|
|
print("---")
|
|
print("Striche aktuell :", len(d.strokes))
|
|
print("Stift aufgesetzt:", d.drawing)
|
|
print("Historie :", len(d.history), "Zustände")
|
|
for i, zustand in enumerate(d.history):
|
|
print(f" [{i}] {len(zustand)} Striche")
|
|
|
|
def update_game(self) -> bool:
|
|
return True
|
|
|
|
def draw_game(self) -> None:
|
|
self.screen.fill((255, 255, 255))
|
|
for stroke in self.doodle.strokes:
|
|
if len(stroke) == 1:
|
|
pygame.draw.circle(self.screen, (0, 0, 0), stroke[0], 1)
|
|
else:
|
|
pygame.draw.lines(self.screen, (0, 0, 0), False, stroke, 2)
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
game = DoodleGame()
|
|
game.run() |