Demos (Gruppe D): Image cb-web, Aufgaben d-10 Snake, d-11 Sonnensystem, d-12 Highscore auf eigener Lösung, Browser-Prüfung mit Screenshot und Checkliste, Aufgaben mit depends_on
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
20
images/cb-web/Containerfile
Normal file
20
images/cb-web/Containerfile
Normal file
@ -0,0 +1,20 @@
|
||||
# cb-web: Python 3 mit Playwright und Chromium für die Demo-Aufgaben (Gruppe D).
|
||||
# Bauen: podman build -t cb-web:latest images/cb-web
|
||||
# Die Seite des Modells wird in der Prüfung im Browser geöffnet, ohne Netz.
|
||||
FROM docker.io/library/python:3.12-slim
|
||||
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONPATH=/opt/cb \
|
||||
HOME=/tmp
|
||||
|
||||
RUN pip install --no-cache-dir playwright \
|
||||
&& playwright install --with-deps chromium \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /work /opt/cb \
|
||||
&& chmod -R a+rX /ms-playwright
|
||||
|
||||
# Gemeinsame Hilfen für die Prüfungen der Demo-Aufgaben.
|
||||
COPY webcheck.py snakecheck.py /opt/cb/
|
||||
|
||||
WORKDIR /work
|
||||
170
images/cb-web/snakecheck.py
Normal file
170
images/cb-web/snakecheck.py
Normal file
@ -0,0 +1,170 @@
|
||||
"""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)
|
||||
121
images/cb-web/webcheck.py
Normal file
121
images/cb-web/webcheck.py
Normal file
@ -0,0 +1,121 @@
|
||||
"""Gemeinsame Hilfen für die Prüfung der Demo-Aufgaben (Gruppe D).
|
||||
|
||||
Eine Prüfung öffnet die Seite des Modells (`/work/index.html`) im Browser, arbeitet eine Checkliste ab
|
||||
und schreibt zuletzt eine JSON-Zeile `{"score": 0.0 bis 1.0, "notes": "..."}`. Ein Screenshot und ein
|
||||
Bericht landen in `/checks/out/` und werden von coding-bench eingesammelt.
|
||||
Die Seite hat kein Netz. Jeder Versuch, ins Netz zu gehen, wird abgebrochen und gezählt.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
OUT = "/checks/out"
|
||||
PAGE = "/work/index.html"
|
||||
ALLOWED_SCHEMES = ("file:", "data:", "blob:", "about:")
|
||||
|
||||
|
||||
class Checklist:
|
||||
"""Sammelt Prüfpunkte mit Gewicht. Der Score ist der Anteil der bestandenen Gewichte."""
|
||||
|
||||
def __init__(self):
|
||||
self.items = []
|
||||
|
||||
def add(self, name, ok, note="", weight=1):
|
||||
self.items.append({"name": name, "ok": bool(ok), "note": note, "weight": weight})
|
||||
mark = "ok " if ok else "FEHL"
|
||||
print(f"[{mark}] {name}" + (f" ({note})" if note and not ok else ""), file=sys.stderr)
|
||||
|
||||
def guard(self, name, fn, weight=1):
|
||||
"""Führt eine Prüfung aus. Eine Ausnahme zählt als nicht bestanden, nicht als Absturz."""
|
||||
try:
|
||||
result = fn()
|
||||
if isinstance(result, tuple):
|
||||
self.add(name, result[0], result[1] if len(result) > 1 else "", weight)
|
||||
else:
|
||||
self.add(name, result, "", weight)
|
||||
except Exception as e: # noqa: BLE001 - jede Störung der Seite ist ein Prüfergebnis
|
||||
self.add(name, False, f"{type(e).__name__}: {str(e)[:120]}", weight)
|
||||
|
||||
def finish(self):
|
||||
total = sum(i["weight"] for i in self.items) or 1
|
||||
got = sum(i["weight"] for i in self.items if i["ok"])
|
||||
failed = [i["name"] for i in self.items if not i["ok"]]
|
||||
passed = sum(1 for i in self.items if i["ok"])
|
||||
notes = f"{passed} von {len(self.items)} Punkten"
|
||||
if failed:
|
||||
notes += ". Fehlt: " + "; ".join(failed[:6]) + (" …" if len(failed) > 6 else "")
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
with open(os.path.join(OUT, "report.json"), "w") as f:
|
||||
json.dump({"items": self.items, "score": got / total}, f, ensure_ascii=False, indent=1)
|
||||
print(json.dumps({"score": round(got / total, 4), "notes": notes}, ensure_ascii=False))
|
||||
|
||||
|
||||
class Session:
|
||||
"""Chromium mit der Seite des Modells. Netzwerk- und Konsolenfehler werden mitgeschrieben."""
|
||||
|
||||
def __init__(self, path=PAGE, width=1280, height=800):
|
||||
self.path = path
|
||||
self.size = {"width": width, "height": height}
|
||||
self.errors = []
|
||||
self.blocked = []
|
||||
|
||||
def __enter__(self):
|
||||
self._pw = sync_playwright().start()
|
||||
self.browser = self._pw.chromium.launch(args=["--no-sandbox", "--disable-dev-shm-usage"])
|
||||
self.context = self.browser.new_context(viewport=self.size)
|
||||
# Kurze Zeitlimits: Fehlt ein Element, soll die Prüfung zügig mit „nicht bestanden“ weitergehen
|
||||
# (Standard wären 30 Sekunden je Zugriff, dann liefe die ganze Prüfung ins Zeitlimit).
|
||||
self.context.set_default_timeout(2500)
|
||||
self.context.set_default_navigation_timeout(15000)
|
||||
self.context.route("**/*", self._route)
|
||||
self.page = self.context.new_page()
|
||||
self.page.on("pageerror", lambda e: self.errors.append(f"pageerror: {e}"))
|
||||
self.page.on(
|
||||
"console", lambda m: self.errors.append(f"console: {m.text}") if m.type == "error" else None
|
||||
)
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
try:
|
||||
self.browser.close()
|
||||
finally:
|
||||
self._pw.stop()
|
||||
|
||||
def _route(self, route):
|
||||
url = route.request.url
|
||||
if url.startswith(ALLOWED_SCHEMES):
|
||||
route.continue_()
|
||||
else:
|
||||
self.blocked.append(url)
|
||||
route.abort()
|
||||
|
||||
def open(self):
|
||||
"""Öffnet die Seite. Gibt False zurück, wenn die Datei fehlt."""
|
||||
if not os.path.isfile(self.path):
|
||||
return False
|
||||
self.page.goto("file://" + self.path, wait_until="load", timeout=15000)
|
||||
return True
|
||||
|
||||
def screenshot(self, name="screenshot.png"):
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
try:
|
||||
self.page.screenshot(path=os.path.join(OUT, name), full_page=False)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"Screenshot nicht möglich: {e}", file=sys.stderr)
|
||||
|
||||
def center(self, selector):
|
||||
"""Mittelpunkt (x, y) des ersten Elements oder None."""
|
||||
box = self.page.locator(selector).first.bounding_box()
|
||||
if not box:
|
||||
return None
|
||||
return (box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
|
||||
|
||||
def wait(self, seconds):
|
||||
self.page.wait_for_timeout(int(seconds * 1000))
|
||||
|
||||
|
||||
def distance(a, b):
|
||||
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5
|
||||
Reference in New Issue
Block a user