Untitled

Anonymous
Plain Text
10/02/2025 3:24 PM
29.0 KB
20
Indexable
Never
I'll enhance the game with real football rules! Here's the updated version:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Realistic Football Game</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #2d5a2d;
            font-family: Arial, sans-serif;
            color: white;
        }
        
        #gameCanvas {
            border: 3px solid white;
            background: linear-gradient(90deg, #4a7c4a 0%, #3d6b3d 50%, #4a7c4a 100%);
            display: block;
            margin: 0 auto;
        }
        
        #controls {
            max-width: 1000px;
            margin: 20px auto;
            text-align: center;
        }
        
        .control-section {
            display: inline-block;
            margin: 10px 15px;
            padding: 15px;
            background-color: rgba(0,0,0,0.3);
            border-radius: 10px;
            vertical-align: top;
        }
        
        #gameInfo {
            text-align: center;
            font-size: 18px;
            margin-bottom: 10px;
            background-color: rgba(0,0,0,0.5);
            padding: 15px;
            border-radius: 10px;
            max-width: 800px;
            margin: 0 auto 20px auto;
        }
        
        .key {
            background-color: #333;
            color: white;
            padding: 3px 8px;
            border-radius: 3px;
            font-weight: bold;
        }
        
        .score-section {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        
        .team-score {
            font-size: 24px;
            font-weight: bold;
        }
        
        .game-clock {
            font-size: 20px;
            color: #FFD700;
        }
        
        #playResult {
            min-height: 20px;
            font-weight: bold;
            color: #FFD700;
        }
    </style>
</head>
<body>
    <div id="gameInfo">
        <div class="score-section">
            <div class="team-score">HOME: <span id="homeScore">0</span></div>
            <div class="game-clock">Q<span id="quarter">1</span> - <span id="timeLeft">15:00</span></div>
            <div class="team-score">AWAY: <span id="awayScore">0</span></div>
        </div>
        <div>
            <strong>Down:</strong> <span id="down">1</span> | 
            <strong>Distance:</strong> <span id="yardsToGo">10</span> | 
            <strong>Field Position:</strong> <span id="fieldPosition">Own 25</span> | 
            <strong>Timeouts:</strong> <span id="timeouts">3</span>
        </div>
        <div id="gameStatus">Press SPACE to start play</div>
        <div id="playResult"></div>
    </div>
    
    <canvas id="gameCanvas" width="1000" height="400"></canvas>
    
    <div id="controls">
        <div class="control-section">
            <h3>Plays</h3>
            <div><span class="key">SPACE</span> - Snap Ball</div>
            <div><span class="key">R</span> - Run Play</div>
            <div><span class="key">P</span> - Pass Play</div>
            <div><span class="key">F</span> - Field Goal</div>
            <div><span class="key">U</span> - Punt</div>
        </div>
        
        <div class="control-section">
            <h3>Passing</h3>
            <div><span class="key">1</span> - Throw to WR1 (Red)</div>
            <div><span class="key">2</span> - Throw to WR2 (Blue)</div>
            <div><span class="key">3</span> - Throw to TE (Green)</div>
            <div><span class="key">4</span> - Throw to RB (Orange)</div>
            <div><span class="key">S</span> - Spike Ball</div>
        </div>
        
        <div class="control-section">
            <h3>Special</h3>
            <div><span class="key">T</span> - Call Timeout</div>
            <div><span class="key">H</span> - Hurry Up</div>
            <div><span class="key">A</span> - Audible</div>
        </div>
        
        <div class="control-section">
            <h3>Movement</h3>
            <div><span class="key">↑↓←→</span> - Move QB</div>
            <div><span class="key">SHIFT</span> - Sprint</div>
        </div>
    </div>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
        // Game state with real football rules
        let gameState = {
            // Game flow
            quarter: 1,
            timeLeft: 900, // 15 minutes in seconds
            gameRunning: false,
            
            // Team stats
            homeScore: 0,
            awayScore: 0,
            possession: 'home', // 'home' or 'away'
            
            // Down and distance
            down: 1,
            yardsToGo: 10,
            yardLine: 25, // Distance from own goal line (0-100)
            
            // Play state
            playActive: false,
            playType: null,
            ballThrown: false,
            playResult: null,
            playStartTime: 0,
            
            // Team resources
            timeouts: 3,
            
            // Special situations
            redZone: false,
            twoMinuteWarning: false,
            overtime: false,
            
            // Play clock
            playClock: 40,
            playClockRunning: false
        };
        
        // Player positions
        let players = {
            qb: { x: 200, y: 200, color: '#FFD700', speed: 2 },
            wr1: { x: 400, y: 150, color: '#FF4444', route: 'go', speed: 3 },
            wr2: { x: 450, y: 250, color: '#4444FF', route: 'slant', speed: 3 },
            te: { x: 300, y: 180, color: '#44FF44', route: 'out', speed: 2.5 },
            rb: { x: 180, y: 200, color: '#FF8844', speed: 2.5 }
        };
        
        // Ball object
        let ball = {
            x: 200,
            y: 200,
            targetX: 200,
            targetY: 200,
            flying: false,
            speed: 8,
            carrier: 'qb'
        };
        
        // Defenders with realistic AI
        let defenders = [
            { x: 500, y: 160, color: '#800080', target: 'wr1', type: 'cb', speed: 3 },
            { x: 550, y: 240, color: '#800080', target: 'wr2', type: 'cb', speed: 3 },
            { x: 400, y: 190, color: '#800080', target: 'te', type: 'lb', speed: 2.5 },
            { x: 350, y: 200, color: '#800080', target: 'qb', type: 'de', speed: 2 },
            { x: 300, y: 200, color: '#800080', target: 'qb', type: 'dt', speed: 1.5 }
        ];
        
        // Input handling
        let keys = {};
        
        document.addEventListener('keydown', (e) => {
            keys[e.key.toLowerCase()] = true;
            handleKeyPress(e.key.toLowerCase());
        });
        
        document.addEventListener('keyup', (e) => {
            keys[e.key.toLowerCase()] = false;
        });
        
        function handleKeyPress(key) {
            if (key === ' ') {
                if (!gameState.playActive && gameState.playType) {
                    snapBall();
                }
            } else if (!gameState.playActive) {
                switch(key) {
                    case 'r':
                        selectPlay('run');
                        break;
                    case 'p':
                        selectPlay('pass');
                        break;
                    case 'f':
                        if (isFieldGoalRange()) {
                            selectPlay('fieldgoal');
                        } else {
                            updateStatus('Too far for field goal attempt!');
                        }
                        break;
                    case 'u':
                        selectPlay('punt');
                        break;
                    case 't':
                        callTimeout();
                        break;
                }
            } else if (gameState.playActive) {
                switch(key) {
                    case '1':
                        if (gameState.playType === 'pass' && !gameState.ballThrown) {
                            throwBall('wr1');
                        }
                        break;
                    case '2':
                        if (gameState.playType === 'pass' && !gameState.ballThrown) {
                            throwBall('wr2');
                        }
                        break;
                    case '3':
                        if (gameState.playType === 'pass' && !gameState.ballThrown) {
                            throwBall('te');
                        }
                        break;
                    case '4':
                        if (gameState.playType === 'pass' && !gameState.ballThrown) {
                            throwBall('rb');
                        }
                        break;
                    case 's':
                        if (gameState.playType === 'pass' && !gameState.ballThrown) {
                            spikeBall();
                        }
                        break;
                }
            }
        }
        
        function selectPlay(playType) {
            gameState.playType = playType;
            gameState.playClock = 40;
            gameState.playClockRunning = true;
            
            const playNames = {
                'run': 'Run Play',
                'pass': 'Pass Play', 
                'fieldgoal': 'Field Goal Attempt',
                'punt': 'Punt'
            };
            
            updateStatus(`${playNames[playType]} selected - Press SPACE to snap`);
        }
        
        function snapBall() {
            gameState.playActive = true;
            gameState.ballThrown = false;
            gameState.playResult = null;
            gameState.playStartTime = Date.now();
            gameState.playClockRunning = false;
            
            resetPositions();
            
            switch(gameState.playType) {
                case 'pass':
                    updateStatus('Pass play! Use 1,2,3,4 to throw or S to spike');
                    break;
                case 'run':
                    updateStatus('Handoff to RB!');
                    ball.carrier = 'rb';
                    setTimeout(() => executeRunPlay(), 1500);
                    break;
                case 'fieldgoal':
                    updateStatus('Field goal attempt!');
                    setTimeout(() => executeFieldGoal(), 2000);
                    break;
                case 'punt':
                    updateStatus('Punting the ball!');
                    setTimeout(() => executePunt(), 2000);
                    break;
            }
        }
        
        function resetPositions() {
            const lineOfScrimmage = (gameState.yardLine / 100) * canvas.width;
            
            players.qb.x = lineOfScrimmage - 50;
            players.qb.y = 200;
            players.wr1.x = lineOfScrimmage + 100;
            players.wr1.y = 150;
            players.wr2.x = lineOfScrimmage + 150;
            players.wr2.y = 250;
            players.te.x = lineOfScrimmage + 50;
            players.te.y = 180;
            players.rb.x = lineOfScrimmage - 70;
            players.rb.y = 200;
            
            ball.x = players[ball.carrier].x;
            ball.y = players[ball.carrier].y;
            ball.flying = false;
            
            // Position defenders
            defenders.forEach((defender, i) => {
                defender.x = lineOfScrimmage + 200 + (i * 30);
                defender.y = 120 + (i * 40);
            });
        }
        
        function throwBall(receiver) {
            if (gameState.ballThrown) return;
            
            gameState.ballThrown = true;
            ball.flying = true;
            ball.carrier = receiver;
            ball.targetX = players[receiver].x;
            ball.targetY = players[receiver].y;
            
            updateStatus(`Ball thrown to ${receiver.toUpperCase()}!`);
            
            setTimeout(() => {
                resolvePass(receiver);
            }, 1200);
        }
        
        function spikeBall() {
            gameState.ballThrown = true;
            updateStatus('Ball spiked to stop the clock!');
            
            setTimeout(() => {
                gameState.playResult = 'Incomplete - Clock stopped';
                gameState.down++;
                endPlay();
            }, 1000);
        }
        
        function resolvePass(receiver) {
            const distance = Math.sqrt(
                Math.pow(players[receiver].x - ball.x, 2) + 
                Math.pow(players[receiver].y - ball.y, 2)
            );
            
            // Calculate completion probability based on pressure, distance, receiver
            let completionChance = 0.65;
            
            // Adjust for receiver type
            if (receiver === 'te') completionChance += 0.1; // TEs more reliable
            if (receiver === 'rb') completionChance += 0.15; // RBs very reliable
            
            // Adjust for distance
            if (distance > 200) completionChance -= 0.2; // Long passes harder
            
            // Adjust for pressure (defender proximity to QB)
            const qbPressure = defenders.some(d => 
                Math.sqrt(Math.pow(d.x - players.qb.x, 2) + Math.pow(d.y - players.qb.y, 2)) < 50
            );
            if (qbPressure) completionChance -= 0.15;
            
            const isComplete = Math.random() < completionChance;
            
            if (isComplete) {
                const baseYards = Math.floor(Math.random() * 12) + 3;
                let yards = baseYards;
                
                // Bonus yards for different receivers
                if (receiver === 'wr1') yards += Math.floor(Math.random() * 8); // Deep threat
                if (receiver === 'wr2') yards += Math.floor(Math.random() * 5); // Possession receiver
                
                // Check for touchdown
                const yardsToEndzone = 100 - gameState.yardLine;
                if (yards >= yardsToEndzone) {
                    yards = yardsToEndzone;
                    scoreTouchdown();
                    return;
                }
                
                advanceField(yards);
                gameState.playResult = `COMPLETE! +${yards} yards to ${receiver.toUpperCase()}`;
                
            } else {
                // Check for interception (5% chance)
                if (Math.random() < 0.05) {
                    gameState.playResult = 'INTERCEPTION! Turnover!';
                    changePossession();
                } else {
                    gameState.playResult = 'Incomplete pass';
                    gameState.down++;
                }
            }
            
            endPlay();
        }
        
        function executeRunPlay() {
            const baseYards = Math.floor(Math.random() * 6) + 1;
            let yards = baseYards;
            
            // Chance for big run (10%)
            if (Math.random() < 0.1) {
                yards += Math.floor(Math.random() * 15) + 10;
            }
            
            // Chance for loss (15%)
            if (Math.random() < 0.15) {
                yards = -Math.floor(Math.random() * 3) - 1;
            }
            
            // Check for touchdown
            const yardsToEndzone = 100 - gameState.yardLine;
            if (yards >= yardsToEndzone) {
                yards = yardsToEndzone;
                scoreTouchdown();
                return;
            }
            
            // Check for safety
            if (gameState.yardLine + yards < 0) {
                scoreSafety();
                return;
            }
            
            advanceField(yards);
            gameState.playResult = `Run for ${yards} yards`;
            gameState.down++;
            
            endPlay();
        }
        
        function executeFieldGoal() {
            const distance = (100 - gameState.yardLine) + 17; // Add 17 for endzone + holder
            let successChance = 0.9;
            
            // Adjust success rate by distance
            if (distance > 50) successChance -= 0.3;
            if (distance > 40) successChance -= 0.2;
            if (distance > 30) successChance -= 0.1;
            
            const isGood = Math.random() < successChance;
            
            if (isGood) {
                gameState.homeScore += 3;
                gameState.playResult = `FIELD GOAL GOOD! ${distance} yards`;
                changePossession();
                gameState.yardLine = 25; // Kickoff return position
            } else {
                gameState.playResult = `Field goal MISSED from ${distance} yards`;
                changePossession();
                gameState.yardLine = Math.min(80, gameState.yardLine + 7); // Opponent gets ball at spot or 20
            }
            
            endPlay();
        }
        
        function executePunt() {
            const puntDistance = Math.floor(Math.random() * 20) + 35;
            const netYards = Math.min(puntDistance, 100 - gameState.yardLine - 5); // Account for touchback
            
            changePossession();
            gameState.yardLine = 100 - (gameState.yardLine + netYards);
            gameState.playResult = `Punt for ${puntDistance} yards`;
            
            endPlay();
        }
        
        function scoreTouchdown() {
            gameState.homeScore += 6;
            gameState.playResult = 'TOUCHDOWN! +6 points';
            
            // Extra point attempt (automatic for now)
            setTimeout(() => {
                if (Math.random() > 0.05) { // 95% success rate
                    gameState.homeScore += 1;
                    gameState.playResult += ' - Extra point GOOD!';
                } else {
                    gameState.playResult += ' - Extra point MISSED!';
                }
                
                changePossession();
                gameState.yardLine = 25; // Kickoff
                endPlay();
            }, 2000);
        }
        
        function scoreSafety() {
            gameState.awayScore += 2;
            gameState.playResult = 'SAFETY! +2 points for defense';
            changePossession();
            gameState.yardLine = 20; // Free kick from 20
            endPlay();
        }
        
        function advanceField(yards) {
            gameState.yardLine += yards;
            gameState.yardLine = Math.max(0, Math.min(100, gameState.yardLine));
            
            // Check for first down
            if (yards >= gameState.yardsToGo) {
                gameState.down = 1;
                gameState.yardsToGo = Math.min(10, 100 - gameState.yardLine);
                gameState.playResult += ' - FIRST DOWN!';
            } else {
                gameState.yardsToGo -= yards;
            }
        }
        
        function changePossession() {
            gameState.possession = gameState.possession === 'home' ? 'away' : 'home';
            gameState.down = 1;
            gameState.yardsToGo = 10;
            gameState.timeouts = 3;
        }
        
        function endPlay() {
            gameState.playActive = false;
            gameState.playType = null;
            
            // Check for turnover on downs
            if (gameState.down > 4) {
                gameState.playResult += ' - TURNOVER ON DOWNS!';
                changePossession();
                gameState.yardLine = 100 - gameState.yardLine; // Flip field position
            }
            
            // Update red zone status
            gameState.redZone = gameState.yardLine >= 80;
            
            // Run game clock (approximate)
            const playTime = Math.floor(Math.random() * 15) + 5;
            gameState.timeLeft = Math.max(0, gameState.timeLeft - playTime);
            
            // Check for end of quarter
            if (gameState.timeLeft <= 0) {
                advanceQuarter();
            }
            
            updateUI();
            updateStatus(gameState.playResult + ' - Select next play');
        }
        
        function advanceQuarter() {
            gameState.quarter++;
            gameState.timeLeft = 900; // Reset to 15:00
            
            if (gameState.quarter === 3) {
                // Halftime - switch possession
                changePossession();
            }
            
            if (gameState.quarter > 4) {
                endGame();
            }
        }
        
        function endGame() {
            if (gameState.homeScore === gameState.awayScore) {
                gameState.overtime = true;
                gameState.quarter = 5;
                gameState.timeLeft = 600; // 10 minute OT
                updateStatus('OVERTIME! First to score wins!');
            } else {
                const winner = gameState.homeScore > gameState.awayScore ? 'HOME' : 'AWAY';
                updateStatus(`GAME OVER! ${winner} WINS!`);
            }
        }
        
        function callTimeout() {
            if (gameState.timeouts > 0 && !gameState.playActive) {
                gameState.timeouts--;
                updateStatus(`Timeout called! ${gameState.timeouts} remaining`);
            }
        }
        
        function isFieldGoalRange() {
            const distance = (100 - gameState.yardLine) + 17;
            return distance <= 55; // Reasonable FG range
        }
        
        function getFieldPositionText() {
            if (gameState.yardLine <= 50) {
                return `Own ${gameState.yardLine}`;
            } else {
                return `Opp ${100 - gameState.yardLine}`;
            }
        }
        
        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const secs = seconds % 60;
            return `${minutes}:${secs.toString().padStart(2, '0')}`;
        }
        
        function updateStatus(message) {
            document.getElementById('gameStatus').textContent = message;
        }
        
        function updateUI() {
            document.getElementById('down').textContent = gameState.down;
            document.getElementById('yardsToGo').textContent = gameState.yardsToGo;
            document.getElementById('fieldPosition').textContent = getFieldPositionText();
            document.getElementById('homeScore').textContent = gameState.homeScore;
            document.getElementById('awayScore').textContent = gameState.awayScore;
            document.getElementById('quarter').textContent = gameState.quarter;
            document.getElementById('timeLeft').textContent = formatTime(gameState.timeLeft);
            document.getElementById('timeouts').textContent = gameState.timeouts;
            document.getElementById('playResult').textContent = gameState.playResult || '';
        }
        
        function update() {
            // Move QB with arrow keys during pass plays
            if (gameState.playActive && gameState.playType === 'pass' && !gameState.ballThrown) {
                const speed = keys['shift'] ? 4 : 2; // Sprint with shift
                
                if (keys['arrowup'] && players.qb.y > 50) players.qb.y -= speed;
                if (keys['arrowdown'] && players.qb.y < 350) players.qb.y += speed;
                if (keys['arrowleft'] && players.qb.x > 20) players.qb.x -= speed;
                if (keys['arrowright'] && players.qb.x < canvas.width - 100) players.qb.x += speed;
                
                // Update ball position with QB
                ball.x = players.qb.x;
                ball.y = players.qb.y;
            }
            
            // Animate receivers running routes
            if (gameState.playActive && gameState.playType === 'pass') {
                players.wr1.x += players.wr1.speed; // Go route
                
                players.wr2.x += players.wr2.speed * 0.7; // Slant route
                players.wr2.y -= 1.5;
                
                players.te.x += players.te.speed * 0.8; // Out route
                players.te.y += Math.sin(Date.now() * 0.01) * 0.5;
                
                players.rb.x += players.rb.speed * 0.5; // Checkdown route
            }
            
            // Animate ball flight
            if (ball.flying) {
                const dx = ball.targetX - ball.x;
                const dy = ball.targetY - ball.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance > ball.speed) {
                    ball.x += (dx / distance) * ball.speed;
                    ball.y += (dy / distance) * ball.speed;
                } else {
                    ball.x = ball.targetX;
                    ball.y = ball.targetY;
                    ball.flying = false;
                }
            }
            
            // Move defenders with realistic AI
            defenders.forEach(defender => {
                let target;
                if (gameState.playType === 'pass') {
                    target = players[defender.target];
                } else {
                    target = players[ball.carrier];
                }
                
                const dx = target.x - defender.x;
                const dy = target.y - defender.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance > 5) {
                    defender.x += (dx / distance) * defender.speed;
                    defender.y += (dy / distance) * defender.speed;
                }
            });
            
            // Update play clock
            if (gameState.playClockRunning) {
                gameState.playClock -= 0.1;
                if (gameState.playClock <= 0) {
                    // Delay of game penalty
                    gameState.yardLine = Math.max(0, gameState.yardLine - 5);
                    updateStatus('DELAY OF GAME! -5 yards');
                    gameState.playClockRunning = false;
                    gameState.playType = null;
                }
            }
        }
        
        function draw() {
            // Clear canvas
            ctx.fillStyle = '#4a7c4a';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // Draw field with proper proportions
            ctx.strokeStyle = 'white';
            ctx.lineWidth = 2;
            
            // Yard lines every 10 yards
            for (let i = 0; i <= 10; i++) {
                const x = (i / 10) * canvas.width;
                ctx.beginPath();
                ctx.moveTo(x, 0);
                ctx.lineTo(x, canvas.height);
                ctx.stroke();
                
                // Yard markers
                ctx.fillStyle = 'white';
                ctx.font = '16px Arial';
                ctx.textAlign = 'center';
                const yardNum = i === 0 ? 'G' : i === 10 ? 'G' : Math.abs(50 - (i * 10));
                ctx.fillText(yardNum, x, 30);
                ctx.fillText(yardNum, x, canvas.height - 10);
            }
            
            // Draw line of scrimmage
            const losX = (gameState.yardLine / 100) * canvas.width;
            ctx.strokeStyle = '#FFD700';
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.moveTo(losX, 0);
            ctx.lineTo(losX, canvas.height);
            ctx.stroke();
            
            // Draw first down marker
            const firstDownX = ((gameState.yardLine + gameState.yardsToGo) / 100) * canvas.width;
            ctx.strokeStyle = '#FF4444';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(firstDownX, 0);
            ctx.lineTo(firstDownX, canvas.height);
            ctx.stroke();
            
            // Draw players
            Object.entries(players).forEach(([name, player]) => {
                ctx.fillStyle = player.color;
                ctx.beginPath();
                ctx.arc(player.x, player.y, 10, 0, Math.PI * 2);
                ctx.fill();
                
                // Draw player labels
                ctx.fillStyle = 'white';
                ctx.font = '12px Arial';
                ctx.textAlign = 'center';
                ctx.fillText(name.toUpperCase(), player.x, player.y - 18);
                
                // Highlight ball carrier
                if (name === ball.carrier) {
                    ctx.strokeStyle = '#FFD700';
                    ctx.lineWidth = 3;
                    ctx.beginPath();
                    ctx.arc(player.x, player.y, 12, 0, Math.PI * 2);
                    ctx.stroke();
                }
            });
            
            // Draw defenders
            defenders.forEach((defender, i) => {
                ctx.fillStyle = defender.color;
                ctx.beginPath();
                ctx.arc(defender.x, defender.y, 10, 0, Math.PI * 2);
                ctx.fill();
                
                ctx.fillStyle = 'white';
                ctx.font = '10px Arial';
                ctx.textAlign = 'center';
                ctx.fillText(defender.type.toUpperCase(), defender.x, defender.y - 15);
            });
            
            // Draw ball
            ctx.fillStyle = '#8B4513';
            ctx.strokeStyle = 'white';
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.ellipse(ball.x, ball.y, 8, 5, 0, 0, Math.PI * 2);
            ctx.fill();
            ctx.stroke();
            
            // Draw play clock
            if (gameState.playClock
Editor is loading...
Leave a Comment