Files
coding-bench/tests/referenz/d-10/index.html

25 lines
2.1 KiB
HTML

<!doctype html><html lang="de"><head><meta charset="utf-8"><title>Snake</title>
<style>
html,body{margin:0;background:#111;color:#eee;font-family:sans-serif}
#top{padding:8px}
#board{display:grid;grid-template-columns:repeat(20,24px);grid-auto-rows:24px;gap:1px;width:max-content;margin:8px auto;background:#222}
.cell{background:#1c1c1c}.snake{background:#4c4}.head{background:#9f9}.food{background:#e44}
</style></head><body>
<div id="top"><button id="start">Start</button> Punkte: <span id="score">0</span> · <span id="status">bereit</span></div>
<div id="board"></div>
<script>
const N=20,board=document.getElementById("board"),cells=[];
for(let y=0;y<N;y++)for(let x=0;x<N;x++){const c=document.createElement("div");c.className="cell";c.dataset.x=x;c.dataset.y=y;board.appendChild(c);cells.push(c)}
let snake,dir,next,food,score,timer,alive=false;
const at=(x,y)=>cells[y*N+x];
function place(){let x,y;do{x=Math.floor(Math.random()*N);y=Math.floor(Math.random()*N)}while(snake.some(s=>s[0]==x&&s[1]==y));food=[x,y]}
function draw(){cells.forEach(c=>c.className="cell");snake.forEach((s,i)=>at(s[0],s[1]).classList.add("snake",...(i==0?["head"]:[])));at(food[0],food[1]).classList.add("food");document.getElementById("score").textContent=score}
function start(){clearInterval(timer);snake=[[10,10],[9,10],[8,10]];dir=[1,0];next=dir;score=0;alive=true;place();draw();document.getElementById("status").textContent="läuft";timer=setInterval(step,150)}
function step(){if(!alive)return;dir=next;const h=[snake[0][0]+dir[0],snake[0][1]+dir[1]];
const eat=h[0]==food[0]&&h[1]==food[1];const body=eat?snake:snake.slice(0,-1);
if(h[0]<0||h[1]<0||h[0]>=N||h[1]>=N||body.some(s=>s[0]==h[0]&&s[1]==h[1])){alive=false;clearInterval(timer);document.getElementById("status").textContent="vorbei";return}
snake.unshift(h);if(eat){score++;place()}else snake.pop();draw()}
document.addEventListener("keydown",e=>{const m={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]}[e.key];if(!m)return;e.preventDefault();if(m[0]==-dir[0]&&m[1]==-dir[1])return;next=m});
document.getElementById("start").onclick=start;
</script></body></html>