Below is an example of a single‐file HTML “Sensible Soccer”–inspired game. (Be aware that this is a “toy” simulation; implementing every nuance of realistic physics, tactics, AI and commentary in a single file is a challenge—even one inspired by the classic Sensible Soccer—and so many details are simplified. You can expand and refine this code further.)
Just copy the code below to a file (for example, index.html), open it in your browser, and enjoy the playful match!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sensible Soccer-Inspired Game</title>
<style>
html, body {
margin: 0;
padding: 0;
background: #222;
color: #fff;
font-family: sans-serif;
overflow: hidden;
}
canvas {
background: green;
display: block;
border: 4px solid #003300;
}
#hud {
position: absolute;
top: 10px;
left: 10px;
z-index: 100;
background: rgba(0,0,0,0.6);
padding: 10px;
border-radius: 5px;
}
#commentary {
position: absolute;
bottom: 10px;
left: 10px;
z-index: 100;
background: rgba(0,0,0,0.7);
padding: 8px;
border-radius: 5px;
font-size: 14px;
max-width: 400px;
}
</style>
</head>
<body>
<div id="hud">
<div>Time: <span id="timer">00:00</span></div>
<div>Score: <span id="score">0 - 0</span></div>
</div>
<div id="commentary">Kick Off!</div>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
// ========== Utility Functions ==========
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(v) { return new Vector(this.x+v.x, this.y+v.y); }
subtract(v) { return new Vector(this.x-v.x, this.y-v.y); }
multiply(s) { return new Vector(this.x * s, this.y * s); }
length() { return Math.sqrt(this.x*this.x + this.y*this.y); }
normalize() {
let len = this.length();
return len === 0 ? new Vector(0,0) : new Vector(this.x/len, this.y/len);
}
distance(v) { return this.subtract(v).length(); }
}
function clamp(val, min, max) {
return Math.max(min, Math.min(max, val));
}
// ========== Global Configurations ==========
const CONFIG = {
fieldWidth: 1600,
fieldHeight: 1200,
goalWidth: 200,
goalDepth: 50,
ballRadius: 8,
playerRadius: 12,
playerSpeed: 1.2,
playerAccel: 0.12,
friction: 0.005,
ballFriction: 0.995, // multiplier per tick
weatherWetBallFriction: 0.998, // on rain, the field is slippery so ball doesn't slow as fast
cameraLerp: 0.07,
matchDuration: 90, // minutes simulated in seconds (simulate faster)
fps: 60,
// For a more playful twist:
celebrationTimeout: 120, // frames to celebrate
rain: false, // set to true for weather effect
};
// ========== Game Objects ==========
class Ball {
constructor(x, y) {
this.pos = new Vector(x, y);
this.vel = new Vector(0, 0);
// For spin/curve effects (simplified)
this.spin = new Vector(0, 0);
this.inPossession = null; // which player is holding, if any
}
update() {
// If possessed, we stick closely to the possessor
if(this.inPossession) {
this.pos = this.inPossession.pos.add(new Vector(15,0));
this.vel = new Vector(0,0);
return;
}
// Update physics
this.pos = this.pos.add(this.vel);
// Apply friction (weather affects ball friction if raining)
const frictionFactor = CONFIG.rain ? CONFIG.weatherWetBallFriction : CONFIG.ballFriction;
this.vel = this.vel.multiply(frictionFactor);
// Add subtle spin that curves the ball (just a little wiggle)
this.vel = this.vel.add(this.spin.multiply(0.001));
// Stop if very slow
if(this.vel.length() < 0.1) this.vel = new Vector(0,0);
// Bounce off field boundaries (simulate goal bounds too)
if(this.pos.x < CONFIG.ballRadius || this.pos.x > CONFIG.fieldWidth - CONFIG.ballRadius) {
this.vel.x *= -1;
this.pos.x = clamp(this.pos.x, CONFIG.ballRadius, CONFIG.fieldWidth-CONFIG.ballRadius);
}
if(this.pos.y < CONFIG.ballRadius || this.pos.y > CONFIG.fieldHeight - CONFIG.ballRadius) {
this.vel.y *= -1;
this.pos.y = clamp(this.pos.y, CONFIG.ballRadius, CONFIG.fieldHeight-CONFIG.ballRadius);
}
}
draw(ctx, camera) {
ctx.beginPath();
ctx.arc(this.pos.x - camera.x, this.pos.y - camera.y, CONFIG.ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#fff";
ctx.fill();
ctx.strokeStyle = "#000";
ctx.stroke();
}
}
class Player {
constructor(x, y, team, number, isControlled=false, role="field") {
this.pos = new Vector(x, y);
this.vel = new Vector(0, 0);
this.team = team; // "home" or "away"
this.number = number;
this.isControlled = isControlled; // user-controlled?
this.role = role; // can be "GK", "field", etc.
this.tiredness = Math.random(); // random attribute affecting speed sometimes
this.target = null;
this.hasBall = false;
}
update(game) {
// If user-controlled and near ball, we let keyboard input control.
if(this.isControlled) {
let input = game.input;
let dir = new Vector(0, 0);
if(input.up) dir.y -= 1;
if(input.down) dir.y += 1;
if(input.left) dir.x -= 1;
if(input.right) dir.x += 1;
if(dir.length() > 0) {
dir = dir.normalize();
// Acceleration
this.vel = this.vel.add(dir.multiply(CONFIG.playerAccel));
// Apply max speed (modulated by tiredness)
let maxSpeed = CONFIG.playerSpeed * (1 - 0.5*this.tiredness);
if(this.vel.length() > maxSpeed) {
this.vel = this.vel.normalize().multiply(maxSpeed);
}
} else {
// Gradually slow down
this.vel = this.vel.multiply(0.94);
}
// Manual pass/shoot: if space pressed, try to shoot or pass.
if(input.action && this.hasBall) {
// For simplicity we assume a shoot if near goal, otherwise pass to nearest teammate.
let goal = (this.team === "home") ?
new Vector(CONFIG.fieldWidth, CONFIG.fieldHeight/2) :
new Vector(0, CONFIG.fieldHeight/2);
let distToGoal = this.pos.distance(goal);
if(distToGoal < 400) {
// Shoot: add velocity to ball in goal direction
let shootDir = goal.subtract(this.pos).normalize();
game.ball.inPossession = null;
game.ball.vel = shootDir.multiply(10);
// Add spin
game.ball.spin = new Vector(Math.random()-0.5, Math.random()-0.5);
this.hasBall = false;
game.addCommentary(`Player ${this.number} shoots!`);
game.goalAttempt = true;
} else {
// Pass: find best positioned teammate (simplified)
let mate = game.getNearestTeammate(this);
if(mate) {
let passDir = mate.pos.subtract(this.pos).normalize();
game.ball.inPossession = null;
game.ball.vel = passDir.multiply(8);
game.ball.spin = new Vector(Math.random()-0.5, Math.random()-0.5);
this.hasBall = false;
game.addCommentary(`Player ${this.number} passes to ${mate.number}`);
}
}
input.action = false; // reset action key
}
} else {
// AI behavior: if in possession of ball, look to move toward goal.
if (this.hasBall) {
let goal = (this.team === "home") ?
new Vector(CONFIG.fieldWidth, CONFIG.fieldHeight/2) :
new Vector(0, CONFIG.fieldHeight/2);
this.target = goal;
// Occasionally, add a random wiggle to simulate dribbling
this.target = this.target.add(new Vector((Math.random()-0.5)*20, (Math.random()-0.5)*20));
} else {
// Not in possession: if ball is loose, target it;
// or else reposition based on formation (simplified: maintain original spawn positions with a bit of noise)
if(game.ball.inPossession === null) {
this.target = game.ball.pos;
} else {
// return to formation position (we saved initial pos in formation property)
this.target = this.formationPos ? this.formationPos : this.pos;
}
}
// Simple acceleration toward target if exists.
if(this.target) {
let desired = this.target.subtract(this.pos);
let dist = desired.length();
if(dist > 1) {
desired = desired.normalize();
this.vel = this.vel.add(desired.multiply(CONFIG.playerAccel));
let maxSpeed = CONFIG.playerSpeed * (1 - 0.5*this.tiredness);
if(this.vel.length() > maxSpeed)
this.vel = this.vel.normalize().multiply(maxSpeed);
}
}
// Tackling: if close and ball is owned by an opponent, and within tackling range, try to steal the ball.
if(game.ball.inPossession && game.ball.inPossession.team !== this.team &&
this.pos.distance(game.ball.inPossession.pos) < 30) {
// Simple tackle: random success based on timing (here, 40% chance)
if(Math.random() < 0.4) {
game.ball.inPossession.hasBall = false;
game.ball.inPossession = this;
this.hasBall = true;
game.addCommentary(`Tackle by ${this.team} player ${this.number}! Ball stolen!`);
}
}
// Slow down if no input
this.vel = this.vel.multiply(0.95);
}
// Update position
this.pos = this.pos.add(this.vel);
// Constrain to field boundaries
this.pos.x = clamp(this.pos.x, CONFIG.playerRadius, CONFIG.fieldWidth - CONFIG.playerRadius);
this.pos.y = clamp(this.pos.y, CONFIG.playerRadius, CONFIG.fieldHeight - CONFIG.playerRadius);
}
draw(ctx, camera) {
ctx.beginPath();
ctx.arc(this.pos.x - camera.x, this.pos.y - camera.y, CONFIG.playerRadius, 0, Math.PI*2);
if(this.team === "home") {
ctx.fillStyle = this.isControlled ? "#00f" : "#0cf";
} else {
ctx.fillStyle = "#f00";
}
ctx.fill();
ctx.strokeStyle = "#000";
ctx.stroke();
// Draw number
ctx.fillStyle = "#fff";
ctx.font = "10px sans-serif";
ctx.fillText(this.number, this.pos.x - camera.x - 4, this.pos.y - camera.y + 3);
}
}
// ========== Main Game Class ==========
class Game {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.camera = new Vector(0, 0);
this.lastUpdate = Date.now();
this.elapsed = 0;
this.matchTime = CONFIG.matchDuration; // seconds (simulate faster match time)
this.score = { home: 0, away: 0 };
this.goalAttempt = false;
this.celebrationTimer = 0;
// Input state
this.input = { up:false, down:false, left:false, right:false, action:false };
// Setup ball at center
this.ball = new Ball(CONFIG.fieldWidth/2, CONFIG.fieldHeight/2);
// Create players randomly arranged in formations.
// For simplicity: 5 players per team including goalkeeper.
this.players = [];
// Home Team (left side)
let homeFormation = [
{x: CONFIG.fieldWidth*0.2, y: CONFIG.fieldHeight/2 - 150},
{x: CONFIG.fieldWidth*0.2, y: CONFIG.fieldHeight/2 + 150},
{x: CONFIG.fieldWidth*0.35, y: CONFIG.fieldHeight/2 - 80},
{x: CONFIG.fieldWidth*0.35, y: CONFIG.fieldHeight/2 + 80},
{x: CONFIG.fieldWidth*0.1, y: CONFIG.fieldHeight/2} // GK
];
for(let i=0; i < homeFormation.length; i++){
// Let the first player in formation be under user control (if not the GK)
let isControlled = (i===0 && i!==4);
let p = new Player(homeFormation[i].x, homeFormation[i].y, "home", i+1, isControlled);
p.formationPos = new Vector(homeFormation[i].x, homeFormation[i].y);
if(i===4) p.role = "GK";
this.players.push(p);
}
// Away Team (right side)
let awayFormation = [
{x: CONFIG.fieldWidth*0.8, y: CONFIG.fieldHeight/2 - 150},
{x: CONFIG.fieldWidth*0.8, y: CONFIG.fieldHeight/2 + 150},
{x: CONFIG.fieldWidth*0.65, y: CONFIG.fieldHeight/2 - 80},
{x: CONFIG.fieldWidth*0.65, y: CONFIG.fieldHeight/2 + 80},
{x: CONFIG.fieldWidth*0.9, y: CONFIG.fieldHeight/2} // GK
];
for(let i=0; i < awayFormation.length; i++){
let p = new Player(awayFormation[i].x, awayFormation[i].y, "away", i+1, false);
p.formationPos = new Vector(awayFormation[i].x, awayFormation[i].y);
if(i===4) p.role = "GK";
this.players.push(p);
}
// Set camera initially centered on ball.
this.camera = new Vector(this.ball.pos.x - this.canvas.width/2, this.ball.pos.y - this.canvas.height/2);
this.setupInput();
this.loop();
}
setupInput(){
window.addEventListener("keydown", (e) => {
switch(e.key){
case "ArrowUp": this.input.up = true; break;
case "ArrowDown": this.input.down = true; break;
case "ArrowLeft": this.input.left = true; break;
case "ArrowRight": this.input.right = true; break;
case " ": this.input.action = true; break;
}
});
window.addEventListener("keyup", (e) => {
switch(e.key){
case "ArrowUp": this.input.up = false; break;
case "ArrowDown": this.input.down = false; break;
case "ArrowLeft": this.input.left = false; break;
case "ArrowRight": this.input.right = false; break;
case " ": this.input.action = false; break;
}
});
}
getNearestTeammate(player) {
let teammates = this.players.filter(p => p.team === player.team && p !== player);
let nearest = null;
let bestDist = Infinity;
for (let mate of teammates) {
let d = player.pos.distance(mate.pos);
if(d < bestDist) { bestDist = d; nearest = mate; }
}
return nearest;
}
// When a goal is scored, reset positions
resetPositions(scoringTeam) {
this.ball.pos = new Vector(CONFIG.fieldWidth/2, CONFIG.fieldHeight/2);
this.ball.vel = new Vector(0,0);
this.ball.inPossession = null;
// Reset players to formation
for(let p of this.players){
p.pos = new Vector(p.formationPos.x, p.formationPos.y);
p.vel = new Vector(0,0);
p.hasBall = false;
}
// Brief celebration
this.celebrationTimer = CONFIG.celebrationTimeout;
this.addCommentary(scoringTeam === "home" ? "Home scores! Celebrations!" : "Away scores! What a strike!");
}
// Simple goal detection: when ball enters left/right goal area
checkGoal() {
// Left goal (home GK defends)
if(this.ball.pos.x - CONFIG.ballRadius <= 0 &&
Math.abs(this.ball.pos.y - CONFIG.fieldHeight/2) < CONFIG.goalWidth/2) {
// If away team scored:
this.score.away++;
this.resetPositions("away");
}
// Right goal
if(this.ball.pos.x + CONFIG.ballRadius >= CONFIG.fieldWidth &&
Math.abs(this.ball.pos.y - CONFIG.fieldHeight/2) < CONFIG.goalWidth/2) {
// Home team scored
this.score.home++;
this.resetPositions("home");
}
}
update() {
let now = Date.now(), dt = (now - this.lastUpdate)/1000;
this.lastUpdate = now;
// Simulate match clock (accelerated time: 1 real second = 1 game second)
this.matchTime -= dt;
if(this.matchTime <= 0) {
this.addCommentary("Full Time!");
// Stop updates after full time for now.
return;
}
// Update ball. If a player is in possession, the ball sticks.
this.ball.update();
// Update players. Also auto switch control to the player closest to the ball on the player’s team if the controlled player is too far.
let controlledPlayer = this.players.find(p => p.isControlled);
if(controlledPlayer && controlledPlayer.pos.distance(this.ball.pos) > 150 && !this.ball.inPossession) {
// Find nearest teammate
let teammates = this.players.filter(p => p.team === controlledPlayer.team);
let nearest = teammates.reduce((prev, curr) => (curr.pos.distance(this.ball.pos) < prev.pos.distance(this.ball.pos) ? curr : prev));
if(nearest !== controlledPlayer) {
controlledPlayer.isControlled = false;
nearest.isControlled = true;
this.addCommentary(`Switching control to player ${nearest.number}`);
}
}
// Update each player AI / input.
for(let p of this.players) {
// If a player is near the ball and no one owns it, take possession.
if(!this.ball.inPossession && p.pos.distance(this.ball.pos) < CONFIG.playerRadius+CONFIG.ballRadius+5) {
this.ball.inPossession = p;
p.hasBall = true;
this.addCommentary(`${p.team} player ${p.number} picks up the ball`);
}
p.update(this);
}
// Check collisions between ball and players for bouncing effects.
for(let p of this.players) {
let dist = p.pos.distance(this.ball.pos);
if(dist < CONFIG.playerRadius + CONFIG.ballRadius) {
// Simple repulsion force
let overlap = CONFIG.playerRadius + CONFIG.ballRadius - dist;
let push = this.ball.pos.subtract(p.pos).normalize().multiply(overlap*0.5);
this.ball.pos = this.ball.pos.add(push);
// Kick ball slightly away if not possessed
if(!p.hasBall && !this.ball.inPossession) {
this.ball.vel = this.ball.vel.add(push);
}
}
}
// Update camera to smoothly follow the ball.
let desiredCam = new Vector(
clamp(this.ball.pos.x - this.canvas.width/2, 0, CONFIG.fieldWidth - this.canvas.width),
clamp(this.ball.pos.y - this.canvas.height/2, 0, CONFIG.fieldHeight - this.canvas.height)
);
this.camera = new Vector(
this.camera.x + (desiredCam.x - this.camera.x) * CONFIG.cameraLerp,
this.camera.y + (desiredCam.y - this.camera.y) * CONFIG.cameraLerp
);
// Check goals.
this.checkGoal();
}
drawField() {
let ctx = this.ctx;
// Draw green field and boundaries.
ctx.fillStyle = "#0a0";
ctx.fillRect(-this.camera.x, -this.camera.y, CONFIG.fieldWidth, CONFIG.fieldHeight);
// Draw boundaries.
ctx.strokeStyle = "#fff";
ctx.lineWidth = 3;
ctx.strokeRect(-this.camera.x, -this.camera.y, CONFIG.fieldWidth, CONFIG.fieldHeight);
// Mid-line and circle
ctx.beginPath();
ctx.moveTo(-this.camera.x, CONFIG.fieldHeight/2 - this.camera.y);
ctx.lineTo(CONFIG.fieldWidth - this.camera.x, CONFIG.fieldHeight/2 - this.camera.y);
ctx.stroke();
ctx.beginPath();
ctx.arc(CONFIG.fieldWidth/2 - this.camera.x, CONFIG.fieldHeight/2 - this.camera.y, 60, 0, Math.PI*2);
ctx.stroke();
// Draw goals
// Left goal
ctx.fillStyle = "#666";
ctx.fillRect(-CONFIG.goalDepth - this.camera.x, CONFIG.fieldHeight/2 - CONFIG.goalWidth/2 - this.camera.y, CONFIG.goalDepth, CONFIG.goalWidth);
// Right goal
ctx.fillRect(CONFIG.fieldWidth - this.camera.x, CONFIG.fieldHeight/2 - CONFIG.goalWidth/2 - this.camera.y, CONFIG.goalDepth, CONFIG.goalWidth);
}
drawHUD() {
// Update timer and score display
let timerDiv = document.getElementById("timer");
let scoreDiv = document.getElementById("score");
let minutes = Math.floor(this.matchTime/60);
let seconds = Math.floor(this.matchTime % 60);
timerDiv.innerText = `${minutes.toString().padStart(2,"0")}:${seconds.toString().padStart(2,"0")}`;
scoreDiv.innerText = `${this.score.home} - ${this.score.away}`;
}
addCommentary(text) {
let commentary = document.getElementById("commentary");
commentary.innerText = text;
// Optionally: add sound effects or emoji celebrations here!
}
loop = () => {
// Only update if match time still remains.
if(this.matchTime > 0) {
this.update();
}
// Clear canvas
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// Draw field, players, ball.
this.drawField();
// Draw players
for(let p of this.players) {
p.draw(this.ctx, this.camera);
}
// Draw ball
this.ball.draw(this.ctx, this.camera);
// HUD updates
this.drawHUD();
// Celebration effect (just a colorful border flash)
if(this.celebrationTimer > 0) {
this.ctx.strokeStyle = "#ff0";
this.ctx.lineWidth = 10;
this.ctx.strokeRect(0, 0, this.canvas.width, this.canvas.height);
this.celebrationTimer--;
}
requestAnimationFrame(this.loop);
}
}
// ========== Start the Game ==========
window.onload = () => {
// Toggle rain randomly
CONFIG.rain = Math.random() > 0.7;
if(CONFIG.rain) {
document.getElementById("commentary").innerText = "It's raining! The pitch is slippery...";
}
const canvas = document.getElementById("gameCanvas");
new Game(canvas);
};
</script>
</body>
</html>