"""Gemeinsame Prüfpunkte für das Snake-Spiel (d-10) und seinen Folgeauftrag (d-12). Anker laut Aufgabentext: `#board` mit 400 Zellen `.cell` (data-x, data-y von 0 bis 19), Klassen `snake`, `head`, `food` auf den Zellen, `#score`, `#start`, `#status` mit „läuft“ oder „vorbei“. """ import re SIZE = 20 STATE_JS = """() => { const q = (s) => document.querySelector(s); const pos = (e) => e ? [Number(e.dataset.x), Number(e.dataset.y)] : null; return { head: pos(q('#board .head')), food: pos(q('#board .food')), snake: document.querySelectorAll('#board .snake').length, heads: document.querySelectorAll('#board .head').length, foods: document.querySelectorAll('#board .food').length, status: (q('#status') || {}).innerText || '', score: (q('#score') || {}).innerText || '', }; }""" KEY = {"right": "ArrowRight", "left": "ArrowLeft", "up": "ArrowUp", "down": "ArrowDown"} OPPOSITE = {"right": "left", "left": "right", "up": "down", "down": "up"} def state(s): return s.page.evaluate(STATE_JS) def number(text): m = re.search(r"-?\d+", text or "") return int(m.group()) if m else None def new_game(s): s.page.locator("#start").first.click(timeout=3000) s.wait(0.12) def running(st): return "läuft" in st["status"].lower() or "lauf" in st["status"].lower() def over(st): return "vorbei" in st["status"].lower() def seek_food(s, timeout=25.0): """Steuert die Schlange mit den Pfeiltasten zum Futter. Gibt den letzten Zustand zurück.""" direction = "right" prev = state(s)["head"] waited = 0.0 while waited < timeout: st = state(s) if over(st) or st["head"] is None or st["food"] is None: return st if number(st["score"]) and number(st["score"]) >= 1: return st h, f = st["head"], st["food"] if prev and h != prev: dx, dy = h[0] - prev[0], h[1] - prev[1] direction = "right" if dx > 0 else "left" if dx < 0 else "down" if dy > 0 else "up" prev = h want = [] if f[0] != h[0]: want.append("right" if f[0] > h[0] else "left") if f[1] != h[1]: want.append("down" if f[1] > h[1] else "up") want = [w for w in want if w != OPPOSITE[direction]] or ["down" if h[1] < SIZE // 2 else "up"] if want[0] != direction: s.page.keyboard.press(KEY[want[0]]) s.wait(0.04) waited += 0.05 return state(s) def run_snake_checks(cl, s): """Gibt zurück, ob die Seite geöffnet wurde. Der Aufrufer hat sie schon geladen.""" page = s.page def board(): n = page.locator("#board .cell").count() coords = page.eval_on_selector_all( "#board .cell", "els => els.map(e => e.dataset.x + ',' + e.dataset.y)" ) ok = n == SIZE * SIZE and len(set(coords)) == SIZE * SIZE and all( 0 <= int(c.split(",")[0]) < SIZE and 0 <= int(c.split(",")[1]) < SIZE for c in coords if "," in c and "undefined" not in c ) return ok, f"{n} Zellen" cl.guard("Spielfeld #board mit 400 Zellen (data-x, data-y)", board) start = {} def begin(): new_game(s) st = state(s) start.update(st) ok = st["snake"] == 3 and st["heads"] == 1 and st["foods"] == 1 and running(st) return ok, f"Schlange {st['snake']}, Köpfe {st['heads']}, Futter {st['foods']}, Status {st['status'][:20]!r}" cl.guard("Start: 3 Schlangenzellen, 1 Kopf, 1 Futter, Status „läuft“", begin) def right(): h0 = state(s)["head"] s.wait(0.5) h1 = state(s)["head"] return bool(h0 and h1 and h1[0] > h0[0] and h1[1] == h0[1]), f"Kopf {h0} -> {h1}" cl.guard("Schlange läuft von selbst nach rechts", right) def turn(key, axis, sign): def run(): h0 = state(s)["head"] page.keyboard.press(key) s.wait(0.7) st = state(s) h1 = st["head"] if over(st) or not (h0 and h1): return False, f"Spiel vorbei oder Kopf fehlt ({h0} -> {h1})" return (h1[axis] - h0[axis]) * sign > 0, f"Kopf {h0} -> {h1}" return run cl.guard("Pfeil nach unten steuert nach unten", turn("ArrowDown", 1, 1)) cl.guard("Pfeil nach links steuert nach links", turn("ArrowLeft", 0, -1)) cl.guard("Pfeil nach oben steuert nach oben", turn("ArrowUp", 1, -1)) def no_reverse(): new_game(s) h0 = state(s)["head"] page.keyboard.press("ArrowLeft") s.wait(0.7) st = state(s) h1 = st["head"] return (not over(st)) and bool(h0 and h1 and h1[0] >= h0[0]), f"Kopf {h0} -> {h1}, Status {st['status'][:20]!r}" cl.guard("Umkehr um 180 Grad wird ignoriert", no_reverse) def eat(): new_game(s) st = seek_food(s) sc = number(st["score"]) return (sc == 1 and st["snake"] == 4), f"Punkte {st['score']!r}, Schlange {st['snake']}" cl.guard("Futter fressen: Punkte +1 und Schlange wächst um 1", eat) def wall(): new_game(s) # Geradeaus bis zur Wand. Bis zu 12 Sekunden Geduld, auch bei langsamem Takt. for _ in range(60): if over(state(s)): break s.wait(0.2) st = state(s) h0 = st["head"] s.wait(0.8) h1 = state(s)["head"] return over(st) and h0 == h1, f"Status {st['status'][:20]!r}, Kopf {h0} -> {h1}" cl.guard("Wand beendet das Spiel („vorbei“), danach bewegt sich nichts", wall) def restart(): new_game(s) st = state(s) return running(st) and number(st["score"]) == 0 and st["snake"] == 3, f"Status {st['status'][:20]!r}, Punkte {st['score']!r}" cl.guard("Neustart nach dem Ende: Punkte 0, 3 Zellen, „läuft“", restart)