Voici un petit prototype de jeu qui rappelle le principe de Subway Surfer : un coureur qui avance sans fin sur trois voies, doit éviter des obstacles et peut glisser sous ou sauter par-dessus ceux‑ci.
Le tout est codé en HTML + CSS + JavaScript et fonctionne directement dans un navigateur (pas besoin d’installer quoi que ce soit).
⚠️ Avertissement
Ce n’est qu’une version très basique : aucune animation sophistiquée, aucune monétisation, aucun graphisme professionnel. Vous pouvez l’enrichir (textures, sons, scores en ligne, etc.) à votre guise.
1️⃣ Structure du projet
code
subway‑surfer‑clone/
│
├─ index.html ← page principale
├─ style.css ← styles
└─ script.js ← logique du jeu
Vous pouvez créer ces trois fichiers dans un même dossier et les ouvrir avec votre navigateur.
/* -------------------------------------------------------------
Mini‑Subway Surfer – version HTML5 Canvas
------------------------------------------------------------- */
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const UI_SCORE = document.getElementById('score');
const UI_RESTART = document.getElementById('restartBtn');
const GAME = {
width: canvas.width,
height: canvas.height,
laneCount: 3,
laneWidth: canvas.width / 3,
speed: 4, // vitesse de défilement du sol
accel: 0.001, // accélération progressive
maxSpeed: 12,
gravity: 0.6,
jumpPower: -12,
slideDuration: 30, // frames
obstacleFreq: 120, // frames entre obstacles (diminué avec la vitesse)
frameCount: 0,
score: 0,
running: true
};
/* -------------------------------------------------------------
Joueur
------------------------------------------------------------- */
class Player {
constructor() {
this.width = 40;
this.height = 60;
this.x = Math.floor(GAME.laneCount / 2) * GAME.laneWidth + (GAME.laneWidth - this.width) / 2;
this.y = GAME.height - this.height - 10;
this.vy = 0;
this.lane = Math.floor(GAME.laneCount / 2); // 0,1,2
this.isJumping = false;
this.isSliding = false;
this.slideTimer = 0;
}
moveLeft() {
if (this.lane > 0) {
this.lane--;
this.x = this.lane * GAME.laneWidth + (GAME.laneWidth - this.width) / 2;
}
}
moveRight() {
if (this.lane < GAME.laneCount - 1) {
this.lane++;
this.x = this.lane * GAME.laneWidth + (GAME.laneWidth - this.width) / 2;
}
}
jump() {
if (!this.isJumping && !this.isSliding) {
this.vy = GAME.jumpPower;
this.isJumping = true;
}
}
slide() {
if (!this.isSliding && !this.isJumping) {
this.isSliding = true;
this.slideTimer = GAME.slideDuration;
this.height = 30; // on réduit la hauteur pour passer sous les obstacles bas
this.y += 30; // ajuster la position
}
}
update() {
// Gravité
this.vy += GAME.gravity;
this.y += this.vy;
// Touchdown
const groundY = GAME.height - this.height - 10;
if (this.y >= groundY) {
this.y = groundY;
this.vy = 0;
this.isJumping = false;
}
// Slide timer
if (this.isSliding) {
this.slideTimer--;
if (this.slideTimer <= 0) {
this.isSliding = false;
this.height = 60;
this.y -= 30; // remettre le sprite à la bonne hauteur
}
}
}
draw() {
ctx.fillStyle = '#ff0';
ctx.fillRect(this.x, this.y, this.width, this.height);
}
getBounds() {
return {
left: this.x,
right: this.x + this.width,
top: this.y,
bottom: this.y + this.height
};
}
}
/* -------------------------------------------------------------
Obstacles
------------------------------------------------------------- */
class Obstacle {
constructor() {
// Choix aléatoire du type
const types = ['low', 'high', 'train'];
this.type = types[Math.floor(Math.random() * types.length)];
// Choix de la voie
this.lane = Math.floor(Math.random() * GAME.laneCount);
this.x = this.lane * GAME.laneWidth + (GAME.laneWidth - this.width) / 2;
// Dimensions selon le type
if (this.type === 'low') {
this.width = 40;
this.height = 30;
this.y = GAME.height - this.height - 10; // au sol
} else if (this.type === 'high') {
this.width = 40;
this.height = 80;
this.y = GAME.height - this.height - 10; // plus haut
} else { // train (large obstacle qui bloque toute la largeur)
this.width = GAME.laneWidth * GAME.laneCount;
this.height = 120;
this.lane = 0; // occupe toutes les voies
this.x = 0;
this.y = GAME.height - this.height - 10;
}
// Vitesse relative au sol
this.speed = GAME.speed;
}
update() {
this.y -= this.speed;
}
draw() {
if (this.type === 'low') ctx.fillStyle = '#0f0';
else if (this.type === 'high') ctx.fillStyle = '#f00';
else ctx.fillStyle = '#555';
ctx.fillRect(this.x, this.y, this.width, this.height);
}
isOffScreen() {
return this.y + this.height < 0;
}
getBounds() {
return {
left: this.x,
right: this.x + this.width,
top: this.y,
bottom: this.y + this.height
};
}
}
/* -------------------------------------------------------------
Gestion du sol (défilement)
------------------------------------------------------------- */
class Ground {
constructor() {
this.tiles = [];
const tileHeight = 40;
const rows = Math.ceil(GAME.height / tileHeight) + 1;
for (let i = 0; i < rows; i++) {
this.tiles.push({
y: GAME.height - i * tileHeight,
height: tileHeight
});
}
}
update() {
// Déplacer les tuiles vers le haut
for (let tile of this.tiles) {
tile.y -= GAME.speed;
}
// Réutiliser la tuile qui sort de l'écran
if (this.tiles[0].y + this.tiles[0].height < 0) {
const removed = this.tiles.shift();
removed.y = this.tiles[this.tiles.length - 1].y + removed.height;
this.tiles.push(removed);
}
}
draw() {
ctx.fillStyle = '#777';
for (let tile of this.tiles) {
ctx.fillRect(0, tile.y, GAME.width, tile.height);
}
}
}
/* -------------------------------------------------------------
Variables globales du jeu
------------------------------------------------------------- */
let player = new Player();
let ground = new Ground();
let obstacles = [];
/* -------------------------------------------------------------
Boucle principale
------------------------------------------------------------- */
function gameLoop() {
if (!GAME.running) return;
// ----- Logique -----
GAME.frameCount++;
GAME.speed = Math.min(GAME.maxSpeed, GAME.speed + GAME.accel);
GAME.score = Math.floor(GAME.frameCount / 5);
UI_SCORE.textContent = `Score : ${GAME.score}`;
// Gestion des entrées (déplacées dans les écouteurs ci‑dessous)
// Mise à jour du joueur et du décor
player.update();
ground.update();
// Création d’obstacles
if (GAME.frameCount % Math.max(30, GAME.obstacleFreq - GAME.speed * 5) === 0) {
obstacles.push(new Obstacle());
}
// Mise à jour des obstacles
obstacles.forEach(o => o.update());
obstacles = obstacles.filter(o => !o.isOffScreen());
// Détection de collision
const pBounds = player.getBounds();
for (let o of obstacles) {
const b = o.getBounds();
const intersect = !(pBounds.right < b.left ||
pBounds.left > b.right ||
pBounds.bottom < b.top ||
pBounds.top > b.bottom);
if (intersect) {
// Game Over
GAME.running = false;
UI_RESTART.style.display = 'inline-block';
break;
}
}
// ----- Rendu -----
ctx.clearRect(0, 0, GAME.width, GAME.height);
// Décor (sol)
ground.draw();
// Obstacles
obstacles.forEach(o => o.draw());
// Joueur
player.draw();
// Boucle
requestAnimationFrame(gameLoop);
}
/* -------------------------------------------------------------
Contrôles clavier / tactile
------------------------------------------------------------- */
function handleKey(e) {
if (!GAME.running) return;
switch (e.code) {
case 'ArrowLeft':
case 'KeyA':
player.moveLeft();
break;
case 'ArrowRight':
case 'KeyD':
player.moveRight();
break;
case 'ArrowUp':
case 'KeyW':
case 'Space':
player.jump();
break;
case 'ArrowDown':
case 'KeyS':
player.slide();
break;
}
}
document.addEventListener('keydown', handleKey);
/* Touches mobiles (swipe) */
let touchStartX = null;
let touchStartY = null;
canvas.addEventListener('touchstart', e => {
const touch = e.changedTouches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
});
canvas.addEventListener('touchend', e => {
if (!touchStartX) return;
const touch = e.changedTouches[0];
const dx = touch.clientX - touchStartX;
const dy = touch.clientY - touchStartY;
const absX = Math.abs(dx);
const absY = Math.abs(dy);
const threshold = 30; // pixels
if (absX > absY) {
if (dx > threshold) player.moveRight();
else if (dx < -threshold) player.moveLeft();
} else {
if (dy > threshold) player.slide();
else if (dy < -threshold) player.jump();
}
touchStartX = null;
touchStartY = null;
});
/* -------------------------------------------------------------
Redémarrage
------------------------------------------------------------- */
UI_RESTART.addEventListener('click', () => {
// Réinitialiser tout
player = new Player();
ground = new Ground();
obstacles = [];
GAME.frameCount = 0;
GAME.speed = 4;
GAME.score = 0;
GAME.running = true;
UI_RESTART.style.display = 'none';
UI_SCORE.textContent = 'Score : 0';
requestAnimationFrame(gameLoop);
});
/* -------------------------------------------------------------
Lancement du jeu
------------------------------------------------------------- */
requestAnimationFrame(gameLoop);
3️⃣ Comment jouer ?
Action
Clavier (PC)
Mobile (toucher)
Aller à gauche
← / A
Glisser vers la droite → gauche
Aller à droite
→ / D
Glisser vers la droite → droite
Sauter
↑ / W / Space
Glisser vers le haut
Glisser (slide)
↓ / S
Glisser vers le bas
Objectif : éviter les obstacles le plus longtemps possible. Le score augmente au fur et à mesure que le temps passe.
Game Over : dès qu’une collision est détectée, le jeu s’arrête. Cliquez sur « Recommencer » pour repartir.
4️⃣ Extensions possibles (à vous de jouer !)
Graphismes & textures – Remplacez les rectangles colorés par des images PNG (personnage, barrières, panneaux, etc.).
Sons – Ajoutez des effets sonores pour le saut, le slide, la collision et une musique d’ambiance.
Power‑ups – Implémentez des pièces à collecter, des boucliers temporaires ou des boosts de vitesse.
Gestion du score – Sauvegardez le meilleur score dans le localStorage et affichez‑le.
Niveaux de difficulté – Accélérez la génération d’obstacles, ajoutez des trains qui bloquent toutes les voies, etc.
Responsive design – Adaptez la taille du canvas à la largeur de l’écran (utilisez window.innerWidth/innerHeight).
5️⃣ Licence & droits
Le code fourni ici est public domain (vous pouvez le copier, le modifier et le redistribuer librement).
Aucun asset protégé par le droit d’auteur n’est inclus : seules des formes géométriques simples sont utilisées.
Si vous ajoutez vos propres images ou musiques, assurez‑vous d’en posséder les droits (ou utilisez des ressources libres de droits).
🎉 Amusez‑vous bien !
Si vous avez besoin d’aide pour ajouter une fonctionnalité particulière (ex. : système de pièces, tableau des scores en ligne, etc.), n’hésitez pas à me le demander. Bonne programmation !