Skip to main content

Car Parking Game with Gemini Flash 2.5

Updated 12 min readMarkdown
Car Parking Game with Gemini Flash 2.5

Repo: https://github.com/canerdemirci/car-parking-game-with-ai/tree/main

The Car Parking Game is a browser-based, interactive experience built with HTML, CSS, and JavaScript. The objective is to navigate your car through a parking lot and successfully park it in the designated spot. The game progresses through different chapters, each with unique parking challenges.

How to Play

Controls: Use the arrow keys on your keyboard (or the on-screen buttons on a touch device) to control the car.

Movement: The car has a realistic driving feel with momentum, so it won't stop instantly when you release the keys. It will coast to a stop, so you need to be precise.

Steering: The front wheels of the car turn when you press the left and right arrows, which then guides the car's movement. You can turn the wheels even when the car is stationary.

Winning: To win a level, you must not only drive the car into the designated parking spot but also align it correctly with the spot's angle.

Losing: You will lose if you hit any of the obstacles (other cars, walls) or drive off-road.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Car Parking Game</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');

        body {
            font-family: 'Inter', sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: #2c3e50;
            margin: 0;
            overflow: hidden;
            flex-direction: column;
            color: #ecf0f1;
        }

        #game-container {
            position: relative;
            width: 95vw;
            display: flex;
            flex-direction: column;
            align-items: center;
            background: #34495e;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4);
            border: 2px solid #2980b9;
        }

        canvas {
            background-color: #7f8c8d;
            border-radius: 8px;
            border: 2px solid #95a5a6;
            touch-action: none; /* Disable touch gestures on canvas */
        }

        #message-box {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(44, 62, 80, 0.9);
            border: 2px solid #2980b9;
            padding: 25px;
            border-radius: 10px;
            text-align: center;
            color: #ecf0f1;
            font-size: 1.5rem;
            display: none;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
            z-index: 10;
        }

        #message-box h2 {
            margin: 0 0 10px 0;
            font-weight: 700;
        }

        #message-box button {
            background: #27ae60;
            border: none;
            padding: 10px 20px;
            margin-top: 15px;
            border-radius: 5px;
            color: white;
            font-size: 1rem;
            cursor: pointer;
            transition: transform 0.2s, background 0.2s;
        }

        #message-box button:hover {
            background: #2ecc71;
            transform: translateY(-2px);
        }

        #level-info {
            font-size: 1.2rem;
            margin-top: 10px;
            text-align: center;
        }

        #controls {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 20px;
        }

        .control-row {
            display: flex;
            justify-content: center;
            gap: 10px;
        }

        .control-btn {
            background: #3498db;
            color: white;
            border: none;
            width: 60px;
            height: 60px;
            border-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1.5rem;
            cursor: pointer;
            transition: background 0.2s, transform 0.1s;
            box-shadow: 0 3px 6px rgba(0,0,0,0.3);
            user-select: none;
        }

        .control-btn:active {
            transform: scale(0.95);
            box-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .control-btn:hover {
            background: #2980b9;
        }

        /* Mobile styles */
        @media (max-width: 900px) {
            #game-container {
                width: 95vw;
                padding: 10px;
            }

            canvas {
                width: 90vw;
                height: calc(90vw / 1.77777); /* Maintain 16:9 ratio */
            }

            #message-box {
                padding: 20px;
                font-size: 1.2rem;
            }

            #message-box h2 {
                font-size: 1.5rem;
            }

            #message-box button {
                font-size: 0.9rem;
            }
        }

    </style>
</head>
<body>

    <div id="game-container">
        <div id="level-info">Level: 1</div>
        <canvas id="gameCanvas"></canvas>

        <!-- Message Box for win/lose -->
        <div id="message-box">
            <h2 id="message-title"></h2>
            <p id="message-text"></p>
            <button id="message-button">Next Level</button>
        </div>

        <!-- On-screen controls for mobile -->
        <div id="controls">
            <div class="control-row">
                <button class="control-btn" id="up-btn">&#x25B2;</button>
            </div>
            <div class="control-row">
                <button class="control-btn" id="left-btn">&#x25C0;</button>
                <button class="control-btn" id="down-btn">&#x25BC;</button>
                <button class="control-btn" id="right-btn">&#x25B6;</button>
            </div>
        </div>
    </div>


    <script>
        window.onload = function() {
            // Get canvas and context
            const canvas = document.getElementById('gameCanvas');
            const ctx = canvas.getContext('2d');
            const levelInfo = document.getElementById('level-info');
            const messageBox = document.getElementById('message-box');
            const messageTitle = document.getElementById('message-title');
            const messageText = document.getElementById('message-text');
            const messageButton = document.getElementById('message-button');

            // Set canvas size dynamically to 16:9 aspect ratio
            const aspectRatio = 16 / 9;
            function resizeCanvas() {
                const containerWidth = document.getElementById('game-container').offsetWidth - 40;
                canvas.width = Math.min(containerWidth, 800);
                canvas.height = canvas.width / aspectRatio;
            }
            window.addEventListener('resize', resizeCanvas);
            resizeCanvas();

            // Game variables
            let currentLevel = 0;
            let gameRunning = true;
            let frameCount = 0; // New variable to track frames for staggered movement

            // Car object
            const car = {
                x: 0,
                y: 0,
                width: 30,
                height: 50,
                color: '#e74c3c',

                // Physics properties
                acceleration: 0.1, 
                maxSpeed: 5,      
                velocity: 0,         
                drag: 0.95,          

                // New steering properties
                angle: 0,         
                steerAngle: 0,    
                steerSpeed: 0.04, 
                maxSteer: Math.PI / 4, 

                // Method to draw the car
                draw: function() {
                    ctx.save();
                    ctx.translate(this.x, this.y);
                    ctx.rotate(this.angle);

                    // Draw the main car body
                    ctx.fillStyle = this.color;
                    ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);

                    // Draw a visual indicator for the front of the car
                    ctx.fillStyle = '#c0392b';
                    ctx.fillRect(-this.width / 4, -this.height / 2, this.width / 2, 5);

                    // Draw back wheels (fixed)
                    const wheelWidth = 5;
                    const wheelHeight = 10;
                    const backWheelY = this.height / 2 - 5;
                    ctx.fillStyle = '#2c3e50';
                    ctx.fillRect(-this.width / 2, backWheelY - wheelHeight / 2, wheelWidth, wheelHeight); // Back left
                    ctx.fillRect(this.width / 2 - wheelWidth, backWheelY - wheelHeight / 2, wheelWidth, wheelHeight); // Back right

                    // Draw front wheels (turning)
                    const frontWheelY = -this.height / 2 + 5;
                    ctx.save();
                    ctx.translate(-this.width / 2 + wheelWidth / 2, frontWheelY + wheelHeight / 2);
                    ctx.rotate(this.steerAngle);
                    ctx.fillRect(-wheelWidth / 2, -wheelHeight / 2, wheelWidth, wheelHeight); // Front left
                    ctx.restore();

                    ctx.save();
                    ctx.translate(this.width / 2 - wheelWidth / 2, frontWheelY + wheelHeight / 2);
                    ctx.rotate(this.steerAngle);
                    ctx.fillRect(-wheelWidth / 2, -wheelHeight / 2, wheelWidth, wheelHeight); // Front right
                    ctx.restore();

                    ctx.restore();
                },

                // Method to update car's state based on input
                update: function(keys) {
                    // Update steering angle based on left/right keys
                    if (keys['ArrowLeft'] || keys['KeyA']) {
                        this.steerAngle -= this.steerSpeed;
                    }
                    if (keys['ArrowRight'] || keys['KeyD']) {
                        this.steerAngle += this.steerSpeed;
                    }

                    // Clamp the steer angle to prevent infinite turning
                    this.steerAngle = Math.max(-this.maxSteer, Math.min(this.maxSteer, this.steerAngle));

                    // Update velocity based on up/down keys
                    if (keys['ArrowUp'] || keys['KeyW']) {
                        this.velocity += this.acceleration;
                    }
                    if (keys['ArrowDown'] || keys['KeyS']) {
                        this.velocity -= this.acceleration;
                    }

                    // Clamp velocity to max speed
                    this.velocity = Math.max(-this.maxSpeed, Math.min(this.maxSpeed, this.velocity));

                    // Apply drag to the velocity
                    this.velocity *= this.drag;

                    // Update car's body angle based on velocity and steer angle
                    this.angle += this.velocity * Math.tan(this.steerAngle) / this.height;

                    // Update car's position based on its body's angle and current velocity
                    this.x += this.velocity * Math.sin(this.angle);
                    this.y -= this.velocity * Math.cos(this.angle);
                },

                // Check collision with a rectangle (obstacle)
                checkCollision: function(rect) {
                    const carCorners = [
                        {x: this.x + (this.width/2) * Math.sin(this.angle) - (this.height/2) * Math.cos(this.angle), y: this.y - (this.width/2) * Math.cos(this.angle) - (this.height/2) * Math.sin(this.angle)},
                        {x: this.x - (this.width/2) * Math.sin(this.angle) - (this.height/2) * Math.cos(this.angle), y: this.y + (this.width/2) * Math.cos(this.angle) - (this.height/2) * Math.sin(this.angle)},
                        {x: this.x - (this.width/2) * Math.sin(this.angle) + (this.height/2) * Math.cos(this.angle), y: this.y + (this.width/2) * Math.cos(this.angle) + (this.height/2) * Math.sin(this.angle)},
                        {x: this.x + (this.width/2) * Math.sin(this.angle) + (this.height/2) * Math.cos(this.angle), y: this.y - (this.width/2) * Math.cos(this.angle) + (this.height/2) * Math.sin(this.angle)},
                    ];

                    for (const corner of carCorners) {
                        if (corner.x > rect.x && corner.x < rect.x + rect.width &&
                            corner.y > rect.y && corner.y < rect.y + rect.height) {
                            return true;
                        }
                    }
                    return false;
                },

                // Check if the car is within the parking spot and at the right angle
                isParked: function(spot) {
                    // Check if the car is within the parking spot bounds
                    // This function now handles rotated rectangles correctly.
                    function isPointInRotatedRect(px, py, rx, ry, rw, rh, ra) {
                        // Translate point to rect's local coordinates
                        const cos = Math.cos(-ra);
                        const sin = Math.sin(-ra);
                        const dx = px - rx;
                        const dy = py - ry;
                        const localX = dx * cos - dy * sin;
                        const localY = dx * sin + dy * cos;

                        // Check if the local point is inside the rect's un-rotated bounding box
                        return localX > -rw / 2 && localX < rw / 2 &&
                               localY > -rh / 2 && localY < rh / 2;
                    }

                    // Get the car's rotated corners
                    const halfWidth = this.width / 2;
                    const halfHeight = this.height / 2;
                    const carCorners = [
                        // Top-left
                        {x: this.x - halfHeight * Math.sin(this.angle) - halfWidth * Math.cos(this.angle), y: this.y + halfHeight * Math.cos(this.angle) - halfWidth * Math.sin(this.angle)},
                        // Top-right
                        {x: this.x + halfHeight * Math.sin(this.angle) - halfWidth * Math.cos(this.angle), y: this.y - halfHeight * Math.cos(this.angle) - halfWidth * Math.sin(this.angle)},
                        // Bottom-left
                        {x: this.x - halfHeight * Math.sin(this.angle) + halfWidth * Math.cos(this.angle), y: this.y + halfHeight * Math.cos(this.angle) + halfWidth * Math.sin(this.angle)},
                        // Bottom-right
                        {x: this.x + halfHeight * Math.sin(this.angle) + halfWidth * Math.cos(this.angle), y: this.y - halfHeight * Math.cos(this.angle) + halfWidth * Math.sin(this.angle)},
                    ];

                    let allCornersInside = true;
                    // Fix: The spot's center is its x and y coordinates, not x + width/2 etc.
                    const spotCenterX = spot.x;
                    const spotCenterY = spot.y;

                    for (const corner of carCorners) {
                        if (!isPointInRotatedRect(corner.x, corner.y, spotCenterX, spotCenterY, spot.width, spot.height, spot.angle)) {
                            allCornersInside = false;
                            break;
                        }
                    }

                    // Check angle relative to the spot's angle
                    const angleTolerance = 0.1; 
                    const angleDiff = Math.abs(this.angle - spot.angle);
                    // Check for both the correct angle and the opposite angle (e.g., facing forward or backward)
                    const angleCorrect = (angleDiff < angleTolerance) || (Math.abs(angleDiff - Math.PI) < angleTolerance);

                    return allCornersInside && angleCorrect;
                }
            };

            // Draws a parking spot with a dashed white line
            function drawParkingSpot(spot) {
                ctx.save();
                ctx.translate(spot.x, spot.y);
                ctx.rotate(spot.angle);

                ctx.strokeStyle = '#ecf0f1';
                ctx.lineWidth = 2;
                ctx.setLineDash([5, 5]); // Dashed line pattern
                ctx.strokeRect(-spot.width / 2, -spot.height / 2, spot.width, spot.height);

                ctx.restore();
            }

            // Levels data with new layouts
            const levels = [
                { // Level 1: Perpendicular Parking
                    car: {x: 50, y: 50, angle: 0},
                    parkingSpot: {x: 400, y: 350, width: 40, height: 60, angle: 0},
                    obstacles: [
                        {x: 0, y: 0, width: 800, height: 10, color: '#34495e'},
                        {x: 0, y: 440, width: 800, height: 10, color: '#34495e'},
                        {x: 0, y: 0, width: 10, height: 450, color: '#34495e'},
                        {x: 790, y: 0, width: 10, height: 450, color: '#34495e'},
                        {x: 100, y: 350, width: 30, height: 50, color: '#2980b9'},
                        {x: 200, y: 350, width: 30, height: 50, color: '#16a085'},
                        {x: 300, y: 350, width: 30, height: 50, color: '#f39c12'},
                        {x: 500, y: 350, width: 30, height: 50, color: '#c0392b'},
                    ]
                },
                { // Level 2: Diagonal Parking
                    car: {x: 50, y: 200, angle: 0},
                    parkingSpot: {x: 500, y: 300, width: 40, height: 60, angle: Math.PI / 4},
                    obstacles: [
                        {x: 0, y: 0, width: 800, height: 10, color: '#34495e'},
                        {x: 0, y: 440, width: 800, height: 10, color: '#34495e'},
                        {x: 0, y: 0, width: 10, height: 450, color: '#34495e'},
                        {x: 790, y: 0, width: 10, height: 450, color: '#34495e'},
                        {x: 350, y: 150, width: 30, height: 50, color: '#2c3e50'},
                        {x: 400, y: 150, width: 30, height: 50, color: '#3498db'},
                        {x: 450, y: 150, width: 30, height: 50, color: '#e67e22'},
                        {x: 550, y: 350, width: 30, height: 50, color: '#f1c40f'},
                        {x: 600, y: 350, width: 30, height: 50, color: '#1abc9c'},
                    ]
                },
                { // Level 3: Parallel Parking (Fixed Dimensions)
                    car: {x: 100, y: 50, angle: Math.PI / 2},
                    parkingSpot: {x: 350, y: 250, width: 40, height: 60, angle: Math.PI / 2}, // Fixed dimensions
                    obstacles: [
                        {x: 0, y: 0, width: 800, height: 10, color: '#34495e'},
                        {x: 0, y: 440, width: 800, height: 10, color: '#34495e'},
                        {x: 0, y: 0, width: 10, height: 450, color: '#34495e'},
                        {x: 790, y: 0, width: 10, height: 450, color: '#34495e'},
                        {x: 350, y: 100, width: 60, height: 30, color: '#e67e22', angle: Math.PI / 2},
                        {x: 350, y: 400, width: 60, height: 30, color: '#e67e22', angle: Math.PI / 2},
                        {x: 200, y: 250, width: 30, height: 50, color: '#1abc9c', angle: Math.PI / 2}
                    ]
                }
            ];

            // Load a level
            function loadLevel(levelIndex) {
                if (levelIndex >= levels.length) {
                    showWinMessage("You've completed all chapters! Great job!", "Game Over");
                    return;
                }
                currentLevel = levelIndex;
                const levelData = levels[currentLevel];
                car.x = levelData.car.x;
                car.y = levelData.car.y;
                car.angle = levelData.car.angle;
                car.velocity = 0;
                car.steerAngle = 0;
                levelInfo.textContent = `Level: ${currentLevel + 1}`;
                hideMessageBox();
            }

            // Keyboard input handling
            const keys = {};
            window.addEventListener('keydown', (e) => {
                keys[e.key] = true;
            });
            window.addEventListener('keyup', (e) => {
                keys[e.key] = false;
            });

            // Touch/button input handling
            const controlButtons = document.querySelectorAll('.control-btn');
            controlButtons.forEach(button => {
                button.addEventListener('mousedown', (e) => {
                    e.preventDefault();
                    if (e.target.id === 'up-btn') keys['ArrowUp'] = true;
                    if (e.target.id === 'down-btn') keys['ArrowDown'] = true;
                    if (e.target.id === 'left-btn') keys['ArrowLeft'] = true;
                    if (e.target.id === 'right-btn') keys['ArrowRight'] = true;
                });
                button.addEventListener('mouseup', (e) => {
                    e.preventDefault();
                    if (e.target.id === 'up-btn') keys['ArrowUp'] = false;
                    if (e.target.id === 'down-btn') keys['ArrowDown'] = false;
                    if (e.target.id === 'left-btn') keys['ArrowLeft'] = false;
                    if (e.target.id === 'right-btn') keys['ArrowRight'] = false;
                });
                button.addEventListener('touchstart', (e) => {
                    e.preventDefault();
                    if (e.target.id === 'up-btn') keys['ArrowUp'] = true;
                    if (e.target.id === 'down-btn') keys['ArrowDown'] = true;
                    if (e.target.id === 'left-btn') keys['ArrowLeft'] = true;
                    if (e.target.id === 'right-btn') keys['ArrowRight'] = true;
                });
                button.addEventListener('touchend', (e) => {
                    e.preventDefault();
                    if (e.target.id === 'up-btn') keys['ArrowUp'] = false;
                    if (e.target.id === 'down-btn') keys['ArrowDown'] = false;
                    if (e.target.id === 'left-btn') keys['ArrowLeft'] = false;
                    if (e.target.id === 'right-btn') keys['ArrowRight'] = false;
                });
            });

            // Draws a parking spot with a dashed white line
            function drawParkingSpot(spot) {
                ctx.save();
                ctx.translate(spot.x, spot.y);
                ctx.rotate(spot.angle);

                ctx.strokeStyle = '#ecf0f1';
                ctx.lineWidth = 2;
                ctx.setLineDash([5, 5]); // Dashed line pattern
                ctx.strokeRect(-spot.width / 2, -spot.height / 2, spot.width, spot.height);

                ctx.restore();
            }

            // Main game loop
            function gameLoop() {
                if (!gameRunning) return;

                frameCount++;

                ctx.clearRect(0, 0, canvas.width, canvas.height);

                const levelData = levels[currentLevel];

                if (frameCount % 2 === 0) {
                    car.update(keys);
                }

                const carBounds = {
                    x1: car.x - car.width / 2,
                    y1: car.y - car.height / 2,
                    x2: car.x + car.width / 2,
                    y2: car.y + car.height / 2
                };

                if (carBounds.x1 < 0 || carBounds.x2 > canvas.width || carBounds.y1 < 0 || carBounds.y2 > canvas.height) {
                    showLoseMessage("You went off-road! Try again.");
                    return;
                }

                for (const obstacle of levelData.obstacles) {
                    if (car.checkCollision(obstacle)) {
                        showLoseMessage("You hit an obstacle! Try again.");
                        return;
                    }
                }

                if (car.isParked(levelData.parkingSpot)) {
                    showWinMessage("Success! You parked the car.");
                    return;
                }

                drawParkingSpot(levelData.parkingSpot);

                levelData.obstacles.forEach(obs => {
                    ctx.fillStyle = obs.color;
                    ctx.fillRect(obs.x, obs.y, obs.width, obs.height);
                });

                car.draw();

                requestAnimationFrame(gameLoop);
            }

            // Show win message
            function showWinMessage(message, title = "Level Complete!") {
                gameRunning = false;
                messageTitle.textContent = title;
                messageText.textContent = message;
                messageButton.textContent = "Next Level";
                messageButton.onclick = () => loadLevel(currentLevel + 1);
                messageBox.style.display = 'block';
            }

            // Show lose message
            function showLoseMessage(message) {
                gameRunning = false;
                messageTitle.textContent = "Game Over";
                messageText.textContent = message;
                messageButton.textContent = "Restart Level";
                messageButton.onclick = () => loadLevel(currentLevel);
                messageBox.style.display = 'block';
            }

            // Hide message box
            function hideMessageBox() {
                messageBox.style.display = 'none';
                gameRunning = true;
                requestAnimationFrame(gameLoop);
            }

            // Start the game
            loadLevel(0);
        };
    </script>
</body>
</html>

Code Explanation

The game's code is a single HTML file containing all the necessary logic and styling.

HTML Structure: The HTML sets up the canvas for the game, a container for the controls, and a message box for displaying win/loss messages.

CSS Styling: The CSS provides the overall look and feel of the game, including the background, container styles, and the appearance of the buttons and message box.

JavaScript Logic: This is the core of the game. It handles:

Car Object: Defines the car's properties such as its position (x, y), dimensions (width, height), and physics (velocity, drag).

Level Data: An array of objects, where each object represents a different level with its own car starting position, parking spot, and obstacles.

Input Handling: Listens for keyboard and touch events to control the car's movement and steering.

Game Loop: The gameLoop function is the heart of the game, continuously redrawing the scene, updating the car's state, and checking for collisions and win conditions.

Collision Detection: The isParked and checkCollision functions use geometric calculations to determine if the car is in a valid spot or has hit an obstacle. The isParked function was a key part of our chat history, as we had to update it to properly detect when the car was parked in rotated spots.

Gemini Flash 2.5 Chat History

This documentation is a result of our collaborative work in developing the game. We started with a basic car and progressively added features based on your feedback:

We made the game scene bigger and added a full parking lot with other cars.

We introduced a more realistic driving model with momentum and gradual acceleration.

We gave the car wheels and allowed them to turn independently of movement for more realistic steering.

We refined the parking logic to correctly handle perpendicular, parallel, and diagonal parking spots.

We adjusted the car's speed and steering sensitivity several times to find the perfect balance for an enjoyable experience.

About the author

  • Programming is fun. It is nice to spend time with it and not realize how time passes, learning new things... I hope one day I will make awesome things with it.

No comments yet. Be the first to comment.