Code moi un jeu Snake en seulement 50 lignes en HTML
- User
Code moi un jeu Snake en seulement 50 lignes en HTML
Assistant
Voici un jeu Snake complet et fonctionnel en exactement 33 lignes de code (HTML, CSS et JS inclus). Copie ce code dans un fichier
.htmlet ouvre-le dans ton navigateur.html<!DOCTYPE html> <html> <head> <style> body { background: #222; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } canvas { border: 2px solid #fff; background: #000; } </style> </head> <body> <canvas id="c" width="400" height="400"></canvas> <script> const ctx = c.getContext('2d'); let snake = [{x:10, y:10}], food = {x:15, y:15}, dir = {x:1, y:0}, score = 0; document.onkeydown = e => { if (e.key == 'ArrowLeft' && dir.x == 0) dir = {x:-1, y:0}; if (e.key == 'ArrowRight' && dir.x == 0) dir = {x:1, y:0}; if (e.key == 'ArrowUp' && dir.y == 0) dir = {x:0, y:-1}; if (e.key == 'ArrowDown' && dir.y == 0) dir = {x:0, y:1}; }; setInterval(() => { let head = {x: snake[0].x + dir.x, y: snake[0].y + dir.y}; if (head.x < 0 || head.x > 19 || head.y < 0 || head.y > 19 || snake.some(s => s.x == head.x && s.y == head.y)) { snake = [{x:10, y:10}]; dir = {x:1, y:0}; score = 0; alert('Perdu !'); } snake.unshift(head); if (head.x == food.x && head.y == food.y) { food = {x: ~~(Math.random() * 20), y: ~~(Math.random() * 20)}; score++; } else { snake.pop(); } ctx.fillStyle = '#000'; ctx.fillRect(0, 0, 400, 400); ctx.fillStyle = '#0f0'; snake.forEach(s => ctx.fillRect(s.x*20, s.y*20, 18, 18)); ctx.fillStyle = '#f00'; ctx.fillRect(food.x*20, food.y*20, 18, 18); ctx.fillStyle = '#fff'; ctx.fillText('Score: ' + score, 10, 20); }, 100); </script> </body> </html>
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.