99 lines
2.5 KiB
Python
99 lines
2.5 KiB
Python
from dataclasses import dataclass, field, replace
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Particle:
|
|
position: tuple = (0, 0)
|
|
velocity: tuple = (0, 0)
|
|
acceleration: tuple = (0, 0)
|
|
history: tuple = () # Vorversionen, älteste zuerst
|
|
max_history: int = 5 # Begrenzung gegen Ausufern
|
|
|
|
def update(self):
|
|
new_velocity = (self.velocity[0] + self.acceleration[0],
|
|
self.velocity[1] + self.acceleration[1])
|
|
new_position = (self.position[0] + new_velocity[0],
|
|
self.position[1] + new_velocity[1])
|
|
# Vorversion ohne eigene History merken, sonst entsteht eine Kette
|
|
previous = replace(self, history=())
|
|
new_history = (self.history + (previous,))[-self.max_history:]
|
|
return replace(self,
|
|
position=new_position,
|
|
velocity=new_velocity,
|
|
history=new_history)
|
|
|
|
def undo(self):
|
|
if not self.history:
|
|
return self
|
|
return replace(self.history[-1], history=self.history[:-1])
|
|
|
|
|
|
# ---------- Tests ----------
|
|
|
|
def test_update_bewegt_particle_und_merkt_vorversion():
|
|
# Arrange
|
|
p = Particle(position=(0, 0), velocity=(1, 0), acceleration=(1, 2))
|
|
|
|
# Act
|
|
p2 = p.update()
|
|
|
|
# Assert
|
|
assert p2.velocity == (2, 2)
|
|
assert p2.position == (2, 2)
|
|
assert len(p2.history) == 1
|
|
assert p2.history[-1].position == (0, 0)
|
|
|
|
|
|
def test_update_veraendert_original_nicht():
|
|
# Arrange
|
|
p = Particle(velocity=(1, 1))
|
|
|
|
# Act
|
|
p.update()
|
|
|
|
# Assert
|
|
assert p.position == (0, 0)
|
|
assert p.history == ()
|
|
|
|
|
|
def test_undo_stellt_vorversion_wieder_her():
|
|
# Arrange
|
|
p = Particle(velocity=(1, 0))
|
|
p3 = p.update().update().update() # position = (3, 0)
|
|
|
|
# Act
|
|
zurueck = p3.undo()
|
|
|
|
# Assert
|
|
assert zurueck.position == (2, 0)
|
|
assert len(zurueck.history) == 2
|
|
|
|
|
|
def test_undo_ohne_history_gibt_self_zurueck():
|
|
# Arrange
|
|
p = Particle(position=(1, 1))
|
|
|
|
# Act
|
|
ergebnis = p.undo()
|
|
|
|
# Assert
|
|
assert ergebnis == p
|
|
|
|
|
|
def test_history_ist_begrenzt():
|
|
# Arrange
|
|
p = Particle(velocity=(1, 0), max_history=3)
|
|
|
|
# Act
|
|
for _ in range(10):
|
|
p = p.update()
|
|
|
|
# Assert
|
|
assert len(p.history) == 3
|
|
assert p.history[0].position == (7, 0) # älteste gemerkte
|
|
|
|
test_update_bewegt_particle_und_merkt_vorversion()
|
|
test_update_veraendert_original_nicht()
|
|
test_undo_stellt_vorversion_wieder_her()
|
|
test_undo_ohne_history_gibt_self_zurueck()
|
|
test_history_ist_begrenzt() |