Bien sûr ! Voici un exemple complet d'un jeu Snake codé en HTML, CSS et JavaScript, le tout dans un seul fichier .html. Vous pouvez copier-coller ce code dans un fichier .html et l'ouvrir avec votre navigateur pour jouer.
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<title>Jeu Snake</title>
<style>
body {
background: #222;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
color: #eee;
user-select: none;
}
canvas {
background-color: #111;
border: 3px solid #4CAF50;
border-radius: 8px;
box-shadow: 0 0 20px #4CAF50;
}
#score {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
font-size: 24px;
letter-spacing: 1.2px;
}
#gameOver {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,0.8);
padding: 30px 40px;
border: 2px solid #4CAF50;
border-radius: 10px;
font-size: 28px;
text-align: center;
display: none;
}
#restartBtn {
margin-top: 20px;
background-color: #4CAF50;
border: none;
color: #111;
padding: 10px 20px;
font-size: 18px;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.3s ease;
}
#restartBtn:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div id="score">Score: 0</div>
<canvas id="game" width="400" height="400"></canvas>
<div id="gameOver">
<div id="gameOverText">Game Over!</div>
<button id="restartBtn">Recommencer</button>
</div>
<script>
(() => {
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const scoreDisplay = document.getElementById('score');
const gameOverDiv = document.getElementById('gameOver');
const restartBtn = document.getElementById('restartBtn');
const gridSize = 20; // taille d'une case (20x20 pixels)
const tileCount = canvas.width / gridSize;
let snake = [
{ x: 9, y: 9 },
];
let velocity = { x: 0, y: 0 };
let food = { x: 0, y: 0 };
let score = 0;
let gameRunning = true;
function placeFood() {
// Place nourriture sur une case qui n'est pas occupée par le serpent
let newFoodPos;
while(true) {
newFoodPos = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount),
};
let collision = snake.some(part => part.x === newFoodPos.x && part.y === newFoodPos.y);
if (!collision) break;
}
food = newFoodPos;
}
function drawRect(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * gridSize, y * gridSize, gridSize, gridSize);
}
function draw() {
// Fond du canvas
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Dessine la nourriture
drawRect(food.x, food.y, '#e74c3c');
// Dessine le serpent
snake.forEach((part, index) => {
const color = index === 0 ? '#4CAF50' : '#2ecc71'; // tête différente
drawRect(part.x, part.y, color);
});
// Affiche le score
scoreDisplay.textContent = `Score: ${score}`;
}
function update() {
if (!gameRunning) return;
// Nouvelle position de la tête
const head = { x: snake[0].x + velocity.x, y: snake[0].y + velocity.y };
// Vérifie collisions bordures
if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
endGame();
return;
}
// Vérifie collisions avec le corps
if (snake.some(part => part.x === head.x && part.y === head.y)) {
endGame();
return;
}
// Ajoute la nouvelle tête au serpent
snake.unshift(head);
// Vérifie si a mangé la nourriture
if (head.x === food.x && head.y === food.y) {
score++;
placeFood();
} else {
// enlève la dernière partie du serpent
snake.pop();
}
}
function gameLoop() {
update();
draw();
}
function changeDirection(e) {
const key = e.key;
// Empêche le serpent de revenir sur lui même
switch(key) {
case 'ArrowUp':
case 'z':
case 'Z':
if (velocity.y !== 1) {
velocity = { x: 0, y: -1 };
}
break;
case 'ArrowDown':
case 's':
case 'S':
if (velocity.y !== -1) {
velocity = { x: 0, y: 1 };
}
break;
case 'ArrowLeft':
case 'q':
case 'Q':
if (velocity.x !== 1) {
velocity = { x: -1, y: 0 };
}
break;
case 'ArrowRight':
case 'd':
case 'D':
if (velocity.x !== -1) {
velocity = { x: 1, y: 0 };
}
break;
}
}
function endGame() {
gameRunning = false;
gameOverDiv.style.display = 'block';
}
function restartGame() {
snake = [{ x: 9, y: 9 }];
velocity = { x: 0, y: 0 };
score = 0;
placeFood();
gameOverDiv.style.display = 'none';
gameRunning = true;
}
// Initialisation
placeFood();
// Boucle principale toutes les 100 ms
setInterval(gameLoop, 100);
// Gestion clavier
window.addEventListener('keydown', changeDirection);
restartBtn.addEventListener('click', restartGame);
})();
</script>
</body>
</html>
Fonctionnalités :
- Jeu Snake qui s'affiche sur un canvas 400x400 pixels.
- Contrôles avec les flèches ou touches ZQSD (pratique pour clavier AZERTY).
- Le serpent grandit en mangeant la nourriture rouge.
- Le jeu s'arrête si le serpent touche un mur ou se mord la queue.
- Affichage du score en haut.
- Message de "Game Over" avec bouton pour recommencer.
Amusez-vous bien ! Si vous voulez des fonctionnalités ou styles supplémentaires, n'hésitez pas à demander.