Sensible Soccer HTML5 Game
I'll create a fully-featured Sensible Soccer-style football game in a single HTML file with all the requested features. The game will include physics-based ball movement, player AI, match mechanics, and visual effects - all without external graphics.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sensible Soccer HTML5</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Arial Rounded MT Bold', 'Segoe UI', sans-serif;
}
body {
background: linear-gradient(135deg, #1a2a6c, #b21f1f, #1a2a6c);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
overflow: hidden;
}
.game-container {
position: relative;
width: 100%;
max-width: 900px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
border-radius: 12px;
overflow: hidden;
}
header {
background: linear-gradient(to bottom, #2c3e50, #1a2a6c);
color: white;
padding: 15px 20px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 3px solid #f1c40f;
}
.score-display {
display: flex;
gap: 30px;
font-size: 2.2rem;
font-weight: bold;
}
.team {
display: flex;
flex-direction: column;
align-items: center;
}
.team-name {
font-size: 1.2rem;
margin-bottom: 5px;
text-transform: uppercase;
letter-spacing: 1px;
}
.match-info {
display: flex;
flex-direction: column;
align-items: center;
gap: 5px;
}
.timer {
font-size: 1.8rem;
font-weight: bold;
background: rgba(0, 0, 0, 0.3);
padding: 5px 15px;
border-radius: 20px;
}
.half {
font-size: 0.9rem;
color: #f1c40f;
}
.canvas-container {
position: relative;
background: #27ae60;
width: 100%;
height: 500px;
overflow: hidden;
}
canvas {
position: absolute;
top: 0;
left: 0;
}
.commentary-box {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 10px 20px;
border-radius: 30px;
font-size: 1.1rem;
max-width: 80%;
text-align: center;
z-index: 10;
backdrop-filter: blur(3px);
animation: slideUp 0.3s ease-out;
}
@keyframes slideUp {
from { transform: translate(-50%, 20px); opacity: 0; }
to { transform: translate(-50%, 0); opacity: 1; }
}
.controls {
background: rgba(30, 30, 50, 0.9);
padding: 15px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
color: white;
border-top: 2px solid #f1c40f;
}
.control-group {
background: rgba(0, 0, 0, 0.3);
padding: 10px;
border-radius: 8px;
}
.control-group h3 {
color: #f1c40f;
margin-bottom: 8px;
font-size: 1.1rem;
}
.control-row {
display: flex;
justify-content: space-between;
padding: 5px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.control-row:last-child {
border-bottom: none;
}
.key {
display: inline-block;
background: rgba(255, 255, 255, 0.2);
padding: 2px 8px;
border-radius: 4px;
min-width: 30px;
text-align: center;
font-family: monospace;
}
.game-status {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 30px 50px;
border-radius: 15px;
text-align: center;
z-index: 20;
display: none;
backdrop-filter: blur(5px);
border: 2px solid #f1c40f;
}
.game-status h2 {
font-size: 2.5rem;
margin-bottom: 20px;
color: #f1c40f;
}
.game-status p {
font-size: 1.3rem;
margin-bottom: 25px;
}
.btn {
background: linear-gradient(to bottom, #f1c40f, #f39c12);
color: #2c3e50;
border: none;
padding: 12px 30px;
font-size: 1.2rem;
font-weight: bold;
border-radius: 50px;
cursor: pointer;
transition: all 0.2s;
}
.btn:hover {
transform: translateY(-3px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
.celebration {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 15;
display: none;
}
.confetti {
position: absolute;
width: 10px;
height: 10px;
background: #f1c40f;
animation: fall 2s linear forwards;
}
@keyframes fall {
0% { transform: translateY(-20px) rotate(0deg); opacity: 1; }
100% { transform: translateY(500px) rotate(360deg); opacity: 0; }
}
.weather-effect {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 5;
}
.rain-drop {
position: absolute;
width: 2px;
height: 15px;
background: rgba(255, 255, 255, 0.6);
animation: rainFall 1s linear infinite;
}
@keyframes rainFall {
0% { transform: translateY(-20px); }
100% { transform: translateY(500px); }
}
.player-stats {
position: absolute;
top: 20px;
right: 20px;
background: rgba(0, 0, 0, 0.6);
color: white;
padding: 10px;
border-radius: 8px;
font-size: 0.9rem;
z-index: 10;
display: none;
}
</style>
</head>
<body>
<div class="game-container">
<header>
<div class="team">
<div class="team-name">Red Devils</div>
<div class="score" id="team1-score">0</div>
</div>
<div class="match-info">
<div class="timer" id="timer">45:00</div>
<div class="half" id="half">1st Half</div>
</div>
<div class="team">
<div class="team-name">Blue Eagles</div>
<div class="score" id="team2-score">0</div>
</div>
</header>
<div class="canvas-container">
<canvas id="gameCanvas" width="900" height="500"></canvas>
<div class="commentary-box" id="commentary">Kick off! The match begins!</div>
<div class="game-status" id="gameStatus">
<h2>Match Ended</h2>
<p id="matchResult">Red Devils 0 - 0 Blue Eagles</p>
<button class="btn" id="restartBtn">Play Again</button>
</div>
<div class="celebration" id="celebration"></div>
<div class="weather-effect" id="weather"></div>
<div class="player-stats" id="playerStats">
<div>Player: #10</div>
<div>Speed: 85</div>
<div>Stamina: 78%</div>
<div>Position: Midfield</div>
</div>
</div>
<div class="controls">
<div class="control-group">
<h3>Movement</h3>
<div class="control-row">
<span>Move Player</span>
<span><span class="key">W</span> <span class="key">A</span> <span class="key">S</span> <span class="key">D</span></span>
</div>
<div class="control-row">
<span>Sprint</span>
<span><span class="key">SHIFT</span></span>
</div>
</div>
<div class="control-group">
<h3>Actions</h3>
<div class="control-row">
<span>Pass / Tackle</span>
<span><span class="key">SPACE</span></span>
</div>
<div class="control-row">
<span>Shoot</span>
<span><span class="key">F</span></span>
</div>
<div class="control-row">
<span>Long Pass</span>
<span><span class="key">E</span></span>
</div>
<div class="control-row">
<span>Switch Player</span>
<span><span class="key">Q</span></span>
</div>
</div>
</div>
</div>
<script>
// Game constants and variables
const CANVAS_WIDTH = 900;
const CANVAS_HEIGHT = 500;
const FIELD_COLOR = '#27ae60';
const FIELD_LINE_COLOR = '#ffffff';
const PLAYER_RADIUS = 15;
const BALL_RADIUS = 8;
const GOAL_WIDTH = 120;
const GOAL_HEIGHT = 40;
let canvas, ctx;
let gameRunning = true;
let matchTime = 45 * 60; // 45 minutes in seconds
let timerInterval;
let half = 1;
let scores = [0, 0];
let playerTeam = 0; // 0 = home, 1 = away
let selectedPlayerIndex = 0;
let commentaryTimeout;
let weatherType = 'sunny'; // 'sunny', 'rainy'
// Teams and players
const teams = [
{
name: "Red Devils",
color: "#e74c3c",
players: []
},
{
name: "Blue Eagles",
color: "#3498db",
players: []
}
];
// Player class
class Player {
constructor(team, x, y, number, position, attributes) {
this.team = team;
this.x = x;
this.y = y;
this.number = number;
this.position = position;
this.speed = attributes.speed;
this.strength = attributes.strength;
this.accuracy = attributes.accuracy;
this.stamina = 100;
this.hasBall = false;
this.targetX = x;
this.targetY = y;
this.state = "idle"; // idle, moving, tackling, shooting
this.tackleCooldown = 0;
}
move(dx, dy) {
if (this.state === "tackling" || this.state === "shooting") return;
// Apply stamina effect
const effectiveSpeed = this.speed * (this.stamina / 100);
this.x += dx * effectiveSpeed * 0.05;
this.y += dy * effectiveSpeed * 0.05;
// Update stamina
if (dx !== 0 || dy !== 0) {
this.stamina = Math.max(50, this.stamina - 0.05);
}
this.state = "moving";
}
tackle() {
if (this.tackleCooldown > 0) return;
this.state = "tackling";
this.tackleCooldown = 30; // Cooldown frames
}
shoot() {
if (!this.hasBall) return;
this.state = "shooting";
// Calculate direction towards opponent goal
const goalY = CANVAS_HEIGHT / 2;
const goalX = this.team === 0 ? CANVAS_WIDTH : 0;
// Calculate vector to goal
const dx = goalX - this.x;
const dy = goalY - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
// Normalize and add some randomness
const power = 10 + Math.random() * 5;
ball.vx = (dx / distance) * power;
ball.vy = (dy / distance) * power * (0.8 + Math.random() * 0.4);
this.hasBall = false;
ball.player = null;
// Add commentary
showCommentary(`Shot on goal by #${this.number}!`);
}
pass(targetX, targetY) {
if (!this.hasBall) return;
// Calculate direction to target
const dx = targetX - this.x;
const dy = targetY - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
// Normalize and set ball velocity
const power = 5 + Math.random() * 3;
ball.vx = (dx / distance) * power;
ball.vy = (dy / distance) * power;
this.hasBall = false;
ball.player = null;
// Add commentary
showCommentary(`Pass by #${this.number}`);
}
update() {
// Update tackle cooldown
if (this.tackleCooldown > 0) {
this.tackleCooldown--;
}
// Reset state if not moving
if (this.state === "moving" && Math.abs(this.x - this.targetX) < 2 && Math.abs(this.y - this.targetY) < 2) {
this.state = "idle";
}
// AI movement towards target position
if (!this.hasBall && this.state !== "tackling" && this.state !== "shooting") {
const dx = this.targetX - this.x;
const dy = this.targetY - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance > 5) {
const speed = this.speed * 0.03 * (this.stamina / 100);
this.x += (dx / distance) * speed;
this.y += (dy / distance) * speed;
}
}
// Regain stamina when idle
if (this.state === "idle") {
this.stamina = Math.min(100, this.stamina + 0.02);
}
// Check if player has the ball
if (!ball.player && distanceToBall(this) < PLAYER_RADIUS + BALL_RADIUS) {
ball.player = this;
this.hasBall = true;
ball.vx = 0;
ball.vy = 0;
}
}
draw() {
// Draw player
ctx.beginPath();
ctx.arc(this.x, this.y, PLAYER_RADIUS, 0, Math.PI * 2);
ctx.fillStyle = teams[this.team].color;
ctx.fill();
ctx.strokeStyle = this.hasBall ? "#f1c40f" : "#ffffff";
ctx.lineWidth = 2;
ctx.stroke();
// Draw player number
ctx.fillStyle = "#ffffff";
ctx.font = "12px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(this.number, this.x, this.y);
// Draw state indicator
if (this.state === "tackling") {
ctx.beginPath();
ctx.arc(this.x, this.y, PLAYER_RADIUS + 5, 0, Math.PI * 2);
ctx.strokeStyle = "#e74c3c";
ctx.lineWidth = 2;
ctx.stroke();
}
}
}
// Ball class
class Ball {
constructor() {
this.x = CANVAS_WIDTH / 2;
this.y = CANVAS_HEIGHT / 2;
this.vx = 0;
this.vy = 0;
this.player = null;
this.spin = 0;
this.lastTouch = null;
}
update() {
// Apply friction
this.vx *= 0.98;
this.vy *= 0.98;
// Apply gravity
this.vy += 0.1;
// Apply spin effect
this.vx += this.spin * 0.01;
// Update position
this.x += this.vx;
this.y += this.vy;
// Boundary collision
if (this.x < BALL_RADIUS) {
this.x = BALL_RADIUS;
this.vx = -this.vx * 0.8;
} else if (this.x > CANVAS_WIDTH - BALL_RADIUS) {
this.x = CANVAS_WIDTH - BALL_RADIUS;
this.vx = -this.vx * 0.8;
}
if (this.y < BALL_RADIUS) {
this.y = BALL_RADIUS;
this.vy = -this.vy * 0.8;
} else if (this.y > CANVAS_HEIGHT - BALL_RADIUS) {
this.y = CANVAS_HEIGHT - BALL_RADIUS;
this.vy = -this.vy * 0.8;
}
// Check for goals
if (this.x < 0 && Math.abs(this.y - CANVAS_HEIGHT / 2) < GOAL_HEIGHT / 2) {
scoreGoal(1); // Team 1 scores
} else if (this.x > CANVAS_WIDTH && Math.abs(this.y - CANVAS_HEIGHT / 2) < GOAL_HEIGHT / 2) {
scoreGoal(0); // Team 0 scores
}
// Check if ball is moving slowly enough to be picked up
if (!this.player && Math.abs(this.vx) < 0.1 && Math.abs(this.vy) < 0.1) {
this.vx = 0;
this.vy = 0;
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, BALL_RADIUS, 0, Math.PI * 2);
// Create gradient for ball
const gradient = ctx.createRadialGradient(
this.x - 3, this.y - 3, 1,
this.x, this.y, BALL_RADIUS
);
gradient.addColorStop(0, "#ffffff");
gradient.addColorStop(1, "#cccccc");
ctx.fillStyle = gradient;
ctx.fill();
// Draw ball pattern
ctx.beginPath();
ctx.arc(this.x, this.y, BALL_RADIUS, 0, Math.PI * 2);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 1;
ctx.stroke();
// Draw pentagons (simplified)
ctx.beginPath();
ctx.arc(this.x, this.y, BALL_RADIUS * 0.7, 0, Math.PI * 2);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 1;
ctx.stroke();
}
}
// Create ball instance
const ball = new Ball();
// Initialize game
function init() {
canvas = document.getElementById('gameCanvas');
ctx = canvas.getContext('2d');
// Create players with random attributes
createPlayers();
// Set up initial player positions
resetPlayers();
// Start game loop
gameLoop();
// Start match timer
startTimer();
// Set up weather
setWeather('rainy');
// Set up controls
setupControls();
}
// Create players for both teams
function createPlayers() {
// Team 1 (Home - Red Devils)
teams[0].players = [];
teams[1].players = [];
// Player positions: 1 goalkeeper, 4 defenders, 4 midfielders, 2 attackers
const positions = [
{ type: "GK", x: 80, y: CANVAS_HEIGHT / 2 },
{ type: "DF", x: 180, y: CANVAS_HEIGHT / 4 },
{ type: "DF", x: 180, y: CANVAS_HEIGHT * 3 / 4 },
{ type: "DF", x: 220, y: CANVAS_HEIGHT / 2 - 40 },
{ type: "DF", x: 220, y: CANVAS_HEIGHT / 2 + 40 },
{ type: "MF", x: 320, y: CANVAS_HEIGHT / 2 - 60 },
{ type: "MF", x: 320, y: CANVAS_HEIGHT / 2 + 60 },
{ type: "MF", x: 360, y: CANVAS_HEIGHT / 2 - 30 },
{ type: "MF", x: 360, y: CANVAS_HEIGHT / 2 + 30 },
{ type: "FW", x: 460, y: CANVAS_HEIGHT / 2 - 40 },
{ type: "FW", x: 460, y: CANVAS_HEIGHT / 2 + 40 }
];
// Create players for team 0
for (let i = 0; i < positions.length; i++) {
const attributes = {
speed: 70 + Math.random() * 30,
strength: 60 + Math.random() * 40,
accuracy: 60 + Math.random() * 40
};
teams[0].players.push(new Player(
0,
positions[i].x,
positions[i].y,
i + 1,
positions[i].type,
attributes
));
}
// Create players for team 1 (mirrored positions)
for (let i = 0; i < positions.length; i++) {
const attributes = {
speed: 70 + Math.random() * 30,
strength: 60 + Math.random() * 40,
accuracy: 60 + Math.random() * 40
};
teams[1].players.push(new Player(
1,
CANVAS_WIDTH - positions[i].x,
positions[i].y,
i + 1,
positions[i].type,
attributes
));
}
// Set goalkeeper attributes
teams[0].players[0].speed = 50;
teams[0].players[0].strength = 90;
teams[1].players[0].speed = 50;
teams[1].players[0].strength = 90;
// Give ball to one of the forwards
teams[0].players[9].hasBall = true;
ball.player = teams[0].players[9];
ball.x = teams[0].players[9].x + PLAYER_RADIUS + 5;
ball.y = teams[0].players[9].y;
}
// Reset player positions for kickoff
function resetPlayers() {
// Team 0 positions
teams[0].players[0].x = 80;
teams[0].players[0].y = CANVAS_HEIGHT / 2;
for (let i = 1; i < teams[0].players.length; i++) {
teams[0].players[i].x = 180 + (i-1)*20;
teams[0].players[i].y = CANVAS_HEIGHT / 2 + (i % 2 === 0 ? -1 : 1) * 40 * Math.ceil(i/2);
}
// Team 1 positions
teams[1].players[0].x = CANVAS_WIDTH - 80;
teams[1].players[0].y = CANVAS_HEIGHT / 2;
for (let i = 1; i < teams[1].players.length; i++) {
teams[1].players[i].x = CANVAS_WIDTH - 180 - (i-1)*20;
teams[1].players[i].y = CANVAS_HEIGHT / 2 + (i % 2 === 0 ? -1 : 1) * 40 * Math.ceil(i/2);
}
}
// Game loop
function gameLoop() {
if (!gameRunning) return;
update();
draw();
requestAnimationFrame(gameLoop);
}
// Update game state
function update() {
// Update ball
ball.update();
// Update players
for (let t = 0; t < teams.length; t++) {
for (let p = 0; p < teams[t].players.length; p++) {
teams[t].players[p].update();
}
}
// Simple AI for computer team
updateAI();
// Update player selection
updatePlayerSelection();
}
// Update AI for computer-controlled players
function updateAI() {
const aiTeam = 1; // Team 1 is AI-controlled
// Find closest player to ball
let closestPlayer = null;
let minDistance = Infinity;
for (let p = 0; p < teams[aiTeam].players.length; p++) {
const player = teams[aiTeam].players[p];
const dist = distanceToBall(player);
if (dist < minDistance) {
minDistance = dist;
closestPlayer = player;
}
}
// Move closest player toward ball
if (closestPlayer && !ball.player) {
closestPlayer.targetX = ball.x;
closestPlayer.targetY = ball.y;
// Attempt tackle if close enough
if (minDistance < PLAYER_RADIUS + BALL_RADIUS + 20) {
closestPlayer.tackle();
}
}
// If AI player has the ball
const aiWithBall = teams[aiTeam].players.find(p => p.hasBall);
if (aiWithBall) {
// Move toward opponent goal
aiWithBall.targetX = 0;
aiWithBall.targetY = CANVAS_HEIGHT / 2;
// Sometimes pass or shoot
if (Math.random() < 0.01) {
// Shoot if close to goal
if (aiWithBall.x < CANVAS_WIDTH / 3) {
aiWithBall.shoot();
} else {
// Pass to a teammate
const teammates = teams[aiTeam].players.filter(p => p !== aiWithBall);
if (teammates.length > 0) {
const targetPlayer = teammates[Math.floor(Math.random() * teammates.length)];
aiWithBall.pass(targetPlayer.x, targetPlayer.y);
}
}
}
}
}
// Update player selection logic
function updatePlayerSelection() {
if (ball.player && ball.player.team === playerTeam) {
// If current player has the ball, keep control
selectedPlayerIndex = teams[playerTeam].players.indexOf(ball.player);
return;
}
// Find closest player to ball on player's team
let closestPlayer = null;
let minDistance = Infinity;
for (let p = 0; p < teams[playerTeam].players.length; p++) {
const player = teams[playerTeam].players[p];
const dist = distanceToBall(player);
if (dist < minDistance) {
minDistance = dist;
closestPlayer = player;
}
}
if (closestPlayer) {
selectedPlayerIndex = teams[playerTeam].players.indexOf(closestPlayer);
}
}
// Draw game
function draw() {
// Clear canvas
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
// Draw field
drawField();
// Draw goals
drawGoals();
// Draw players
for (let t = 0; t < teams.length; t++) {
for (let p = 0; p < teams[t].players.length; p++) {
teams[t].players[p].draw();
}
}
// Draw ball
ball.draw();
// Highlight selected player
const selectedPlayer = teams[playerTeam].players[selectedPlayerIndex];
if (selectedPlayer) {
ctx.beginPath();
ctx.arc(selectedPlayer.x, selectedPlayer.y, PLAYER_RADIUS + 8, 0, Math.PI * 2);
ctx.strokeStyle = "#f1c40f";
ctx.lineWidth = 2;
ctx.stroke();
}
}
// Draw soccer field
function drawField() {
// Draw grass
ctx.fillStyle = FIELD_COLOR;
ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
// Draw lines
ctx.strokeStyle = FIELD_LINE_COLOR;
ctx.lineWidth = 3;
// Outer boundary
ctx.strokeRect(10, 10, CANVAS_WIDTH - 20, CANVAS_HEIGHT - 20);
// Center line
ctx.beginPath();
ctx.moveTo(CANVAS_WIDTH / 2, 10);
ctx.lineTo(CANVAS_WIDTH / 2, CANVAS_HEIGHT - 10);
ctx.stroke();
// Center circle
ctx.beginPath();
ctx.arc(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2, 70, 0, Math.PI * 2);
ctx.stroke();
// Left penalty area
ctx.strokeRect(10, (CANVAS_HEIGHT - 160) / 2, 100, 160);
// Right penalty area
ctx.strokeRect(CANVAS_WIDTH - 110, (CANVAS_HEIGHT - 160) / 2, 100, 160);
// Left goal area
ctx.strokeRect(10, (CANVAS_HEIGHT - 80) / 2, 40, 80);
// Right goal area
ctx.strokeRect(CANVAS_WIDTH - 50, (CANVAS_HEIGHT - 80) / 2, 40, 80);
// Draw center spot
ctx.beginPath();
ctx.arc(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2, 5, 0, Math.PI * 2);
ctx.fillStyle = FIELD_LINE_COLOR;
ctx.fill();
}
// Draw goals
function drawGoals() {
// Left goal
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, (CANVAS_HEIGHT - GOAL_HEIGHT) / 2, 10, GOAL_HEIGHT);
// Right goal
ctx.fillRect(CANVAS_WIDTH - 10, (CANVAS_HEIGHT - GOAL_HEIGHT) / 2, 10, GOAL_HEIGHT);
// Goal nets
ctx.strokeStyle = "rgba(255, 255, 255, 0.3)";
ctx.lineWidth = 1;
// Left goal net
ctx.beginPath();
ctx.moveTo(10, (CANVAS_HEIGHT - GOAL_HEIGHT) / 2);
ctx.lineTo(30, (CANVAS_HEIGHT - GOAL_HEIGHT) / 2 - 10);
ctx.lineTo(30, (CANVAS_HEIGHT + GOAL_HEIGHT) / 2 + 10);
ctx.lineTo(10, (CANVAS_HEIGHT + GOAL_HEIGHT) / 2);
ctx.closePath();
ctx.stroke();
// Right goal net
ctx.beginPath();
ctx.moveTo(CANVAS_WIDTH - 10, (CANVAS_HEIGHT - GOAL_HEIGHT) / 2);
ctx.lineTo(CANVAS_WIDTH - 30, (CANVAS_HEIGHT - GOAL_HEIGHT) / 2 - 10);
ctx.lineTo(CANVAS_WIDTH - 30, (CANVAS_HEIGHT + GOAL_HEIGHT) / 2 + 10);
ctx.lineTo(CANVAS_WIDTH - 10, (CANVAS_HEIGHT + GOAL_HEIGHT) / 2);
ctx.closePath();
ctx.stroke();
}
// Start match timer
function startTimer() {
timerInterval = setInterval(() => {
if (gameRunning) {
matchTime--;
// Update timer display
const minutes = Math.floor(matchTime / 60);
const seconds = matchTime % 60;
document.getElementById('timer').textContent =
`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
// Switch halves
if (matchTime <= 0 && half === 1) {
half = 2;
matchTime = 45 * 60; // Reset for second half
document.getElementById('half').textContent = "2nd Half";
resetPlayers();
showCommentary("Second half begins!");
} else if (matchTime <= 0 && half === 2) {
endMatch();
}
}
}, 1000);
}
// Set weather effects
function setWeather(type) {
weatherType = type;
const weatherEl = document.getElementById('weather');
weatherEl.innerHTML = '';
if (type === 'rainy') {
// Create rain drops
for (let i = 0; i < 100; i++) {
const drop = document.createElement('div');
drop.className = 'rain-drop';
drop.style.left = `${Math.random() * 100}%`;
drop.style.animationDelay = `${Math.random() * 2}s`;
weatherEl.appendChild(drop);
}
// Apply physics effect
ball.spin = 0.5;
} else {
ball.spin = 0;
}
}
// Show commentary message
function showCommentary(message) {
const commentaryEl = document.getElementById('commentary');
commentaryEl.textContent = message;
commentaryEl.style.display = 'block';
// Clear previous timeout
if (commentaryTimeout) clearTimeout(commentaryTimeout);
// Hide after delay
commentaryTimeout = setTimeout(() => {
commentaryEl.style.display = 'none';
}, 3000);
}
// Handle goal scoring
function scoreGoal(team) {
scores[team]++;
document.getElementById(`team${team+1}-score`).textContent = scores[team];
// Goal celebration
celebrateGoal(team);
// Show commentary
const scorer = ball.lastTouch ? `#${ball.lastTouch.number}` : "a player";
showCommentary(`GOAL! ${teams[team].name} score! Scored by ${scorer}!`);
// Reset for kickoff
setTimeout(() => {
resetPlayers();
ball.x = CANVAS_WIDTH / 2;
ball.y = CANVAS_HEIGHT / 2;
ball.vx = 0;
ball.vy = 0;
ball.player = null;
// Give ball to the team that conceded
const kickoffTeam = team === 0 ? 1 : 0;
teams[kickoffTeam].players[5].hasBall = true;
ball.player = teams[kickoffTeam].players[5];
showCommentary(`Kick off by ${teams[kickoffTeam].name}`);
}, 2000);
}
// Goal celebration animation
function celebrateGoal(team) {
const celebrationEl = document.getElementById('celebration');
celebrationEl.style.display = 'block';
celebrationEl.innerHTML = '';
// Create confetti
for (let i = 0; i < 150; i++) {
const confetti = document.createElement('div');
confetti.className = 'confetti';
confetti.style.left = `${Math.random() * 100}%`;
confetti.style.backgroundColor = team === 0 ?
["#e74c3c", "#f1c40f", "#ffffff"][Math.floor(Math.random() * 3)] :
["#3498db", "#f1c40f", "#ffffff"][Math.floor(Math.random() * 3)];
confetti.style.animationDelay = `${Math.random() * 0.5}s`;
celebrationEl.appendChild(confetti);
}
// Hide after animation
setTimeout(() => {
celebrationEl.style.display = 'none';
}, 2500);
}
// End the match
function endMatch() {
gameRunning = false;
clearInterval(timerInterval);
const gameStatusEl = document.getElementById('gameStatus');
const matchResultEl = document.getElementById('matchResult');
// Determine result
if (scores[0] > scores[1]) {
matchResultEl.textContent = `${teams[0].name} win ${scores[0]} - ${scores[1]}!`;
matchResultEl.style.color = "#f1c40f";
} else if (scores[1] > scores[0]) {
matchResultEl.textContent = `${teams[1].name} win ${scores[1]} - ${scores[0]}!`;
matchResultEl.style.color = "#f1c40f";
} else {
matchResultEl.textContent = `It's a draw! ${scores[0]} - ${scores[1]}`;
matchResultEl.style.color = "#ffffff";
}
gameStatusEl.style.display = 'block';
}
// Set up keyboard controls
function setupControls() {
const keys = {};
document.addEventListener('keydown', (e) => {
keys[e.key.toLowerCase()] = true;
// Handle actions
if (e.key === ' ') {
// Tackle
const player = teams[playerTeam].players[selectedPlayerIndex];
if (player) player.tackle();
} else if (e.key === 'f') {
// Shoot
const player = teams[playerTeam].players[selectedPlayerIndex];
if (player && player.hasBall) player.shoot();
} else if (e.key === 'e') {
// Long pass
const player = teams[playerTeam].players[selectedPlayerIndex];
if (player && player.hasBall) {
// Pass to a teammate
const teammates = teams[playerTeam].players.filter(p => p !== player);
if (teammates.length > 0) {
const targetPlayer = teammates[Math.floor(Math.random() * teammates.length)];
player.pass(targetPlayer.x, targetPlayer.y);
}
}
} else if (e.key === 'q') {
// Switch player (cycle through)
selectedPlayerIndex = (selectedPlayerIndex + 1) % teams[playerTeam].players.length;
}
});
document.addEventListener('keyup', (e) => {
keys[e.key.toLowerCase()] = false;
});
// Movement handling in game loop
function handleMovement() {
if (!gameRunning) return;
const player = teams[playerTeam].players[selectedPlayerIndex];
if (!player) return;
let dx = 0, dy = 0;
if (keys['w'] || keys['arrowup']) dy -= 1;
if (keys['s'] || keys['arrowdown']) dy += 1;
if (keys['a'] || keys['arrowleft']) dx -= 1;
if (keys['d'] || keys['arrowright']) dx += 1;
player.move(dx, dy);
requestAnimationFrame(handleMovement);
}
handleMovement();
// Restart button
document.getElementById('restartBtn').addEventListener('click', () => {
// Reset game state
scores = [0, 0];
document.getElementById('team1-score').textContent = '0';
document.getElementById('team2-score').textContent = '0';
matchTime = 45 * 60;
half = 1;
document.getElementById('half').textContent = "1st Half";
document.getElementById('gameStatus').style.display = 'none';
// Reset players and ball
createPlayers();
// Restart game
gameRunning = true;
startTimer();
gameLoop();
});
}
// Helper function to calculate distance to ball
function distanceToBall(player) {
const dx = player.x - ball.x;
const dy = player.y - ball.y;
return Math.sqrt(dx * dx + dy * dy);
}
// Initialize game when page loads
window.onload = init;
</script>
</body>
</html>