Certamente! Ho preparato per te un simulatore di partita di calcio completo, racchiuso in un unico file HTML. Puoi semplicemente copiare e incollare il codice in un file .html e aprirlo con il tuo browser.
Ho commentato il codice (in italiano) per spiegarti come funziona ogni parte, specialmente la logica del movimento e la gestione delle animazioni.
Caratteristiche Incluse:
- Campo da Calcio: Realizzato con CSS, completo di linee di metà campo, aree di rigore e cerchio centrale.
- Giocatori e Palla: 22 giocatori e una palla che si muovono in modo "intelligente" (i giocatori inseguono la palla, e quando la toccano, la calciano in una direzione casuale).
- Personalizzazione:
- Puoi cambiare i nomi delle squadre in tempo reale.
- Puoi cambiare il colore della maglia di entrambe le squadre usando un selettore di colore.
- Puoi cambiare il colore della palla.
- Evento Goal:
- Quando la palla entra in una delle porte, il gioco si ferma temporaneamente.
- Appare una scritta gigante "GOAL!".
- Sullo schermo vengono lanciati fuochi d'artificio e scintille (realizzati con CSS).
- Il punteggio viene aggiornato automaticamente.
- Logica di Gioco: Il risultato non è modificabile, ma viene generato dinamicamente dalla simulazione.
Codice del Simulatore
Copia tutto il codice seguente e salvalo in un file chiamato simulatore_calcio.html.
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simulatore Partita di Calcio</title>
<style>
/* Variabili CSS per una facile personalizzazione tramite JavaScript */
:root {
--team-a-color: #007bff; /* Blu */
--team-b-color: #dc3545; /* Rosso */
--ball-color: #ffffff; /* Bianco */
}
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f0f0f0;
margin: 0;
padding: 20px;
overflow: hidden; /* Nasconde lo scroll per i fuochi d'artificio */
}
h1 {
color: #333;
}
/* ---- SEZIONE CONTROLLI ---- */
#controls {
display: flex;
justify-content: space-around;
width: 100%;
max-width: 800px;
background: #fff;
padding: 15px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
margin-bottom: 20px;
flex-wrap: wrap;
}
.control-group {
display: flex;
flex-direction: column;
align-items: center;
margin: 10px;
}
.control-group label {
font-weight: bold;
margin-bottom: 5px;
color: #555;
}
.control-group input[type="text"],
.control-group input[type="color"] {
border: 2px solid #ddd;
border-radius: 5px;
padding: 5px;
}
.control-group input[type="color"] {
width: 50px;
height: 30px;
cursor: pointer;
}
/* ---- TABELLONE ---- */
#scoreboard {
font-size: 2em;
font-weight: bold;
background-color: #222;
color: white;
padding: 10px 20px;
border-radius: 10px;
margin-bottom: 20px;
width: 100%;
max-width: 800px;
text-align: center;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
#team-a-name-display { color: var(--team-a-color); transition: color 0.3s; }
#team-b-name-display { color: var(--team-b-color); transition: color 0.3s; }
/* ---- CAMPO DA GIOCO ---- */
#field-container {
position: relative;
width: 90vw;
height: 60vw;
max-width: 1000px;
max-height: 600px;
}
#field {
position: relative;
width: 100%;
height: 100%;
background-color: #4CAF50; /* Verde campo */
border: 3px solid white;
box-sizing: border-box;
overflow: hidden; /* I giocatori non escono dal campo */
}
/* Linee del campo create con pseudo-elementi */
#field::before { /* Linea di metà campo */
content: '';
position: absolute;
width: 3px;
height: 100%;
background-color: white;
left: 50%;
transform: translateX(-50%);
}
#field::after { /* Cerchio di metà campo */
content: '';
position: absolute;
width: 18%; /* In percentuale per essere responsive */
padding-bottom: 18%; /* Trucco per mantenere le proporzioni */
border: 3px solid white;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.goal-area { /* Le porte */
position: absolute;
top: 35%;
width: 8%;
height: 30%;
border: 3px solid white;
box-sizing: border-box;
}
#goal-a { left: 0; border-left: none; }
#goal-b { right: 0; border-right: none; }
/* ---- GIOCATORI E PALLA ---- */
.player, #ball {
position: absolute;
border-radius: 50%;
transition: top 0.1s linear, left 0.1s linear;
}
.player {
width: 20px;
height: 20px;
display: flex;
justify-content: center;
align-items: center;
color: white;
font-size: 10px;
font-weight: bold;
box-shadow: 0 0 5px rgba(0,0,0,0.5);
border: 1px solid #fff;
}
.team-a { background-color: var(--team-a-color); }
.team-b { background-color: var(--team-b-color); }
#ball {
width: 15px;
height: 15px;
background-color: var(--ball-color);
z-index: 10;
border: 1px solid black;
box-shadow: 0 0 8px rgba(0,0,0,0.7);
}
/* ---- CELEBRAZIONE GOAL ---- */
#goal-celebration {
position: fixed; /* A tutto schermo */
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1000;
opacity: 0;
pointer-events: none; /* Non intercettare click */
transition: opacity 0.5s;
}
#goal-celebration.visible {
opacity: 1;
pointer-events: all;
}
#goal-text {
font-size: 15vw;
color: #ffdd00;
font-weight: bold;
text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #ffc107, 0 0 40px #ffc107;
animation: goal-pop 0.5s ease-out forwards;
transform: scale(0);
}
@keyframes goal-pop {
from { transform: scale(0); }
to { transform: scale(1); }
}
/* ---- FUOCHI D'ARTIFICIO E SCINTILLE ---- */
.sparkle {
position: absolute;
background: gold;
width: 5px;
height: 5px;
border-radius: 50%;
box-shadow: 0 0 10px gold;
animation: sparkle-burst 1s ease-out forwards;
}
@keyframes sparkle-burst {
0% {
transform: scale(1);
opacity: 1;
}
100% {
transform: scale(0);
opacity: 0;
}
}
.firework {
position: absolute;
width: 4px;
height: 4px;
background: #fff;
border-radius: 50%;
animation: firework-fly 1s ease-out forwards;
}
@keyframes firework-fly {
0% {
transform: translateY(0);
opacity: 1;
}
100% {
transform: translateY(-200px);
opacity: 0;
}
}
</style>
</head>
<body>
<h1>Simulatore di Calcio</h1>
<div id="controls">
<div class="control-group">
<label for="team-a-name">Nome Squadra Casa</label>
<input type="text" id="team-a-name" value="Squadra A">
<label for="team-a-color">Colore Maglia</label>
<input type="color" id="team-a-color" value="#007bff">
</div>
<div class="control-group">
<label for="ball-color">Colore Palla</label>
<input type="color" id="ball-color" value="#ffffff">
</div>
<div class="control-group">
<label for="team-b-name">Nome Squadra Ospite</label>
<input type="text" id="team-b-name" value="Squadra B">
<label for="team-b-color">Colore Maglia</label>
<input type="color" id="team-b-color" value="#dc3545">
</div>
</div>
<div id="scoreboard">
<span id="team-a-name-display">Squadra A</span>
<span id="score">0 - 0</span>
<span id="team-b-name-display">Squadra B</span>
</div>
<div id="field-container">
<div id="field">
<div class="goal-area" id="goal-a"></div>
<div class="goal-area" id="goal-b"></div>
<div id="ball"></div>
<!-- I giocatori verranno aggiunti qui da JavaScript -->
</div>
<div id="goal-celebration">
<div id="goal-text">GOAL!</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// ----- ELEMENTI DEL DOM -----
const field = document.getElementById('field');
const ball = document.getElementById('ball');
const scoreboard = document.getElementById('score');
const goalCelebration = document.getElementById('goal-celebration');
const goalText = document.getElementById('goal-text');
// ----- CONTROLLI PERSONALIZZAZIONE -----
const teamANameInput = document.getElementById('team-a-name');
const teamAColorInput = document.getElementById('team-a-color');
const teamBNameInput = document.getElementById('team-b-name');
const teamBColorInput = document.getElementById('team-b-color');
const ballColorInput = document.getElementById('ball-color');
const teamANameDisplay = document.getElementById('team-a-name-display');
const teamBNameDisplay = document.getElementById('team-b-name-display');
// Event listener per aggiornare i nomi e i colori
teamANameInput.addEventListener('input', e => teamANameDisplay.textContent = e.target.value);
teamBNameInput.addEventListener('input', e => teamBNameDisplay.textContent = e.target.value);
teamAColorInput.addEventListener('input', e => {
document.documentElement.style.setProperty('--team-a-color', e.target.value);
teamANameDisplay.style.color = e.target.value;
});
teamBColorInput.addEventListener('input', e => {
document.documentElement.style.setProperty('--team-b-color', e.target.value);
teamBNameDisplay.style.color = e.target.value;
});
ballColorInput.addEventListener('input', e => document.documentElement.style.setProperty('--ball-color', e.target.value));
// ----- IMPOSTAZIONI DI GIOCO -----
const fieldRect = field.getBoundingClientRect();
const playerSize = 20;
const ballSize = 15;
let players = [];
let scoreA = 0;
let scoreB = 0;
let gamePaused = false;
// Proprietà fisiche della palla
const ballPhysics = {
x: fieldRect.width / 2,
y: fieldRect.height / 2,
vx: 0, // velocità x
vy: 0, // velocità y
friction: 0.98 // Attrito per rallentare
};
// ----- FUNZIONI DI GIOCO -----
// Crea i giocatori e li posiziona sul campo
function createPlayers() {
for (let i = 0; i < 22; i++) {
const player = document.createElement('div');
player.classList.add('player');
const team = i < 11 ? 'a' : 'b';
player.classList.add(`team-${team}`);
player.textContent = (i % 11) + 1; // Numero maglia
field.appendChild(player);
players.push({
element: player,
team: team,
x: 0, // posizione x
y: 0, // posizione y
speed: 1.5 + Math.random() * 0.5 // Velocità leggermente diversa per ogni giocatore
});
}
}
// Resetta le posizioni di giocatori e palla (es. dopo un goal)
function resetPositions() {
// Palla al centro
ballPhysics.x = fieldRect.width / 2 - ballSize / 2;
ballPhysics.y = fieldRect.height / 2 - ballSize / 2;
ballPhysics.vx = (Math.random() - 0.5) * 5; // Calcio d'inizio casuale
ballPhysics.vy = (Math.random() - 0.5) * 5;
// Giocatori nelle loro metà campo
players.forEach(p => {
if (p.team === 'a') {
p.x = Math.random() * (fieldRect.width / 2 - playerSize);
} else {
p.x = fieldRect.width / 2 + Math.random() * (fieldRect.width / 2 - playerSize);
}
p.y = Math.random() * (fieldRect.height - playerSize);
});
}
// Funzione per gestire l'evento del goal
function handleGoal(scoringTeam) {
gamePaused = true;
if (scoringTeam === 'a') {
scoreA++;
} else {
scoreB++;
}
scoreboard.textContent = `${scoreA} - ${scoreB}`;
// Mostra la celebrazione
goalText.style.animation = 'none'; // reset animazione
goalText.offsetHeight; // trigger reflow
goalText.style.animation = null;
goalCelebration.classList.add('visible');
// Crea scintille e fuochi d'artificio
createSparkles(goalText.getBoundingClientRect());
createFireworks(20);
setTimeout(() => {
goalCelebration.classList.remove('visible');
resetPositions();
gamePaused = false;
}, 4000); // Pausa di 4 secondi
}
// ----- FUNZIONI DI ANIMAZIONE (Scintille e Fuochi) -----
function createSparkles(sourceRect) {
for (let i = 0; i < 50; i++) {
const sparkle = document.createElement('div');
sparkle.className = 'sparkle';
goalCelebration.appendChild(sparkle);
const angle = Math.random() * 2 * Math.PI;
const distance = Math.random() * 100 + 50;
sparkle.style.left = `${sourceRect.left + sourceRect.width / 2}px`;
sparkle.style.top = `${sourceRect.top + sourceRect.height / 2}px`;
// Applica la trasformazione per l'esplosione
sparkle.style.transform = `translate(${Math.cos(angle) * distance}px, ${Math.sin(angle) * distance}px) scale(1)`;
setTimeout(() => sparkle.remove(), 1000);
}
}
function createFireworks(count) {
for (let i = 0; i < count; i++) {
const firework = document.createElement('div');
firework.className = 'firework';
goalCelebration.appendChild(firework);
firework.style.left = `${Math.random() * 100}%`;
firework.style.top = `${Math.random() * 50 + 50}%`; // Partono dalla metà inferiore dello schermo
firework.style.animationDelay = `${Math.random() * 1.5}s`;
setTimeout(() => firework.remove(), 2500);
}
}
// ----- LOOP PRINCIPALE DI GIOCO -----
function gameLoop() {
if (!gamePaused) {
// 1. Muovi la palla
ballPhysics.x += ballPhysics.vx;
ballPhysics.y += ballPhysics.vy;
ballPhysics.vx *= ballPhysics.friction;
ballPhysics.vy *= ballPhysics.friction;
// 2. Controlla collisioni della palla con i bordi
if (ballPhysics.x < 0 || ballPhysics.x > fieldRect.width - ballSize) {
// GOAL CHECK
const goalPostY = fieldRect.height * 0.35;
const goalPostHeight = fieldRect.height * 0.30;
if (ballPhysics.y > goalPostY && ballPhysics.y < goalPostY + goalPostHeight) {
if (ballPhysics.x < 0) handleGoal('b'); // Goal per la squadra B
else handleGoal('a'); // Goal per la squadra A
} else {
ballPhysics.vx *= -1; // Rimbalza
ballPhysics.x = Math.max(0, Math.min(ballPhysics.x, fieldRect.width - ballSize));
}
}
if (ballPhysics.y < 0 || ballPhysics.y > fieldRect.height - ballSize) {
ballPhysics.vy *= -1; // Rimbalza
ballPhysics.y = Math.max(0, Math.min(ballPhysics.y, fieldRect.height - ballSize));
}
// 3. Muovi i giocatori verso la palla
players.forEach(p => {
const dx = ballPhysics.x - p.x;
const dy = ballPhysics.y - p.y;
const distance = Math.sqrt(dx * dx + dy * dy);
// Se il giocatore è vicino alla palla, la calcia
if (distance < playerSize) {
const kickStrength = 5 + Math.random() * 5;
// Calcia verso la porta avversaria (con un po' di imprecisione)
const targetX = (p.team === 'a') ? fieldRect.width : 0;
const angleToGoal = Math.atan2((fieldRect.height / 2) - p.y, targetX - p.x);
const randomAngle = angleToGoal + (Math.random() - 0.5) * 0.8; // Aggiunge imprecisione
ballPhysics.vx = Math.cos(randomAngle) * kickStrength;
ballPhysics.vy = Math.sin(randomAngle) * kickStrength;
} else { // Altrimenti, la insegue
p.x += (dx / distance) * p.speed;
p.y += (dy / distance) * p.speed;
}
// Mantieni i giocatori dentro il campo
p.x = Math.max(0, Math.min(p.x, fieldRect.width - playerSize));
p.y = Math.max(0, Math.min(p.y, fieldRect.height - playerSize));
});
// 4. Aggiorna la posizione degli elementi nel DOM
ball.style.left = `${ballPhysics.x}px`;
ball.style.top = `${ballPhysics.y}px`;
players.forEach(p => {
p.element.style.left = `${p.x}px`;
p.element.style.top = `${p.y}px`;
});
}
// Richiama il prossimo frame
requestAnimationFrame(gameLoop);
}
// ----- INIZIO -----
createPlayers();
resetPositions();
gameLoop();
});
</script>
</body>
</html>