Untitled

 avatar
unknown
plain_text
9 months ago
2.4 kB
24
Indexable
// Get the game 'screen' from the HTML
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// Define our 'car' as an object
const car = {
        x: 375,       // Starting X position
            y: 500,       // Starting Y position
                width: 30,    // Car width
                    height: 50,   // Car height
                        color: 'red',
                            speed: 10       // How fast the car moves
};

// This function draws everything
function drawGame() {
        // 1. Clear the entire screen
            ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                    // 2. Draw the car
                        ctx.fillStyle = car.color;
                            ctx.fillRect(car.x, car.y, car.width, car.height);
}

// This function listens for key presses
function moveCar(event) {
        switch(event.key) {
                    case 'ArrowUp':
                                car.y -= car.speed;
                                            break;
                                                    case 'ArrowDown':
                                                                car.y += car.speed;
                                                                            break;
                                                                                    case 'ArrowLeft':
                                                                                                car.x -= car.speed;
                                                                                                            break;
                                                                                                                    case 'ArrowRight':
                                                                                                                                car.x += car.speed;
                                                                                                                                            break;
        }
            
                // After moving, re-draw the game
                    drawGame();
}

// --- Start the Game ---

// 1. Draw the car in its starting position
drawGame();

// 2. Tell the browser to listen for key presses and call our 'moveCar' function
window.addEventListener('keydown', moveCar);

        }
}
}
}
Editor is loading...
Leave a Comment