<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Falling Objects Game</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
canvas {
background-color: #f1f1f1;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const basketWidth = 100;
const basketHeight = 20;
let basketX = (canvas.width - basketWidth) / 2;
const basketY = canvas.height - basketHeight - 10;
let objects = [];
let score = 0;
const gravity = 10; // Adjust gravity value here for faster falling
function drawBasket() {
ctx.beginPath();
ctx.rect(basketX, basketY, basketWidth, basketHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawObjects() {
for(let i = 0; i < objects.length; i++) {
ctx.beginPath();
ctx.arc(objects[i].x, objects[i].y, 10, -50, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
}
function moveBasket(event) {
if(event.keyCode === 37) {
basketX -= 20;
} else if(event.keyCode === 39) {
basketX += 20;
}
}
function detectCollision() {
for(let i = 0; i < objects.length; i++) {
if(objects[i].y + 10 >= basketY && objects[i].y + 10 <= basketY + basketHeight && objects[i].x >= basketX && objects[i].x <= basketX + basketWidth) {
objects.splice(i, 1);
score++;
}
}
}
function updateGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBasket();
drawObjects();
detectCollision();
ctx.font = "20px Arial";
ctx.fillStyle = "#000";
ctx.fillText("Score: " + score, 10, 30);
for(let i = 0; i < objects.length; i++) {
objects[i].y += gravity;
}
}
function generateObject() {
const object = {
x: Math.random() * (canvas.width - 20) + 10,
y: 10
};
objects.push(object);
}
setInterval(generateObject, 1000);
setInterval(updateGame, 10);
document.addEventListener("keydown", moveBasket);
</script>
</body>
</html>
<head>: This section of the HTML document contains meta tags that provide information about the document, such as the character encoding and viewport settings. It also includes the <title> tag, which sets the title of the web page displayed in the browser's title bar.
<style>: This is where you define CSS rules and styles for your game. You can specify various styles for different HTML elements, classes, or IDs to control the appearance and layout of your game.
<body>: The <body> tag represents the main content of the HTML document. This is where you place your game canvas, HTML elements, and any other visual components.
<script>: This section is used to include JavaScript code. You can define functions, variables, event handlers, and logic required for your game within the <script> tags. JavaScript provides interactivity and dynamic behavior to your game.
Comments