Sure! Below is a complete implementation of the described basketball dunk game using HTML, CSS, and JavaScript with the HTML5 Canvas. The game resembles the "Flappy Bird" mechanic where each tap directs the basketball upwards ("flap"). Baskets appear from the top with slight rotations, and the player's goal is to dunk the basketball into these baskets. The score increases with each successful dunk, and the game ends if the basketball hits the ground.
1. HTML Structure
Create an index.html file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Basketball Dunk Game</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #87CEEB; /* Sky blue background */
font-family: Arial, sans-serif;
}
#gameCanvas {
display: block;
background-color: #87CEEB; /* Same sky blue for consistency */
}
#overlay {
position: absolute;
top: 0;
left: 0;
color: white;
padding: 20px;
font-size: 24px;
text-shadow: 2px 2px 4px #000;
}
#gameOver {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 36px;
text-align: center;
display: none;
text-shadow: 2px 2px 4px #000;
}
#restartBtn {
margin-top: 20px;
padding: 10px 20px;
font-size: 24px;
cursor: pointer;
background-color: #FF4500;
border: none;
border-radius: 5px;
color: white;
}
#restartBtn:hover {
background-color: #FF6347;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<div id="overlay">Score: 0</div>
<div id="gameOver">
<div>Game Over</div>
<button id="restartBtn">Restart</button>
</div>
<script>
// Game configuration
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions to full window
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Overlay elements
const overlay = document.getElementById('overlay');
const gameOverScreen = document.getElementById('gameOver');
const restartBtn = document.getElementById('restartBtn');
// Event listeners for window resize
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// Constants
const GRAVITY = 0.5;
const FLAP_STRENGTH = -10;
const BASKET_INTERVAL = 1500; // milliseconds
const BASKET_SPEED = 3;
const MAX_ROTATION = 15; // degrees
let score = 0;
let gameOver = false;
// Basketball object
const basketball = {
x: 100,
y: canvas.height / 2,
radius: 20,
color: 'orange',
velocity: 0,
flap: function() {
this.velocity = FLAP_STRENGTH;
},
update: function() {
this.velocity += GRAVITY;
this.y += this.velocity;
// Check collision with ground
if (this.y + this.radius >= canvas.height) {
gameOver = true;
}
},
draw: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.strokeStyle = 'darkorange';
ctx.stroke();
ctx.closePath();
// Draw basketball lines
ctx.beginPath();
ctx.moveTo(this.x - this.radius, this.y);
ctx.lineTo(this.x + this.radius, this.y);
ctx.moveTo(this.x, this.y - this.radius);
ctx.lineTo(this.x, this.y + this.radius);
ctx.strokeStyle = 'brown';
ctx.stroke();
ctx.closePath();
}
};
// Basket class
class Basket {
constructor() {
this.width = 100;
this.height = 20;
this.x = canvas.width;
this.y = 50 + Math.random() * (canvas.height / 2); // Random y position from top
this.speed = BASKET_SPEED;
this.rotation = (Math.random() * 2 - 1) * MAX_ROTATION * Math.PI / 180; // Radians
this.scored = false;
}
update() {
this.x -= this.speed;
}
draw() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation);
ctx.fillStyle = 'black';
ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);
ctx.restore();
}
isOffScreen() {
return this.x + this.width < 0;
}
checkScore(basketball) {
// Simple collision detection (circle vs rotated rectangle)
// Transform basketball position to basket's rotated coordinate system
const cos = Math.cos(-this.rotation);
const sin = Math.sin(-this.rotation);
const dx = basketball.x - this.x;
const dy = basketball.y - this.y;
const xRot = dx * cos - dy * sin;
const yRot = dx * sin + dy * cos;
// Check if within basket bounds
if (
xRot > -this.width / 2 &&
xRot < this.width / 2 &&
yRot > -this.height / 2 - basketball.radius &&
yRot < this.height / 2 + basketball.radius
) {
// Check if basketball is moving downwards (indicating a dunk)
if (basketball.velocity > 0 && !this.scored) {
score += 1;
this.scored = true;
}
}
}
}
let baskets = [];
let lastBasketTime = Date.now();
// Game loop
function gameLoop() {
if (gameOver) {
displayGameOver();
return;
}
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Update and draw basketball
basketball.update();
basketball.draw();
// Handle baskets
// Add new basket
if (Date.now() - lastBasketTime > BASKET_INTERVAL) {
baskets.push(new Basket());
lastBasketTime = Date.now();
}
// Update and draw existing baskets
for (let i = baskets.length - 1; i >= 0; i--) {
const basket = baskets[i];
basket.update();
basket.draw();
basket.checkScore(basketball);
// Remove off-screen baskets
if (basket.isOffScreen()) {
baskets.splice(i, 1);
}
}
// Update score display
overlay.textContent = `Score: ${score}`;
// Request next frame
requestAnimationFrame(gameLoop);
}
// Handle user input
function handleFlap() {
if (!gameOver) {
basketball.flap();
}
}
// Touch events for mobile
canvas.addEventListener('touchstart', (e) => {
e.preventDefault(); // Prevent scrolling
handleFlap();
});
// Mouse click for desktop
canvas.addEventListener('mousedown', handleFlap);
// Game Over display
function displayGameOver() {
gameOverScreen.style.display = 'block';
overlay.style.display = 'none';
}
// Restart game
restartBtn.addEventListener('click', () => {
// Reset game state
score = 0;
gameOver = false;
basketball.y = canvas.height / 2;
basketball.velocity = 0;
baskets = [];
lastBasketTime = Date.now();
overlay.style.display = 'block';
gameOverScreen.style.display = 'none';
gameLoop();
});
// Start the game loop
gameLoop();
</script>
</body>
</html>
2. Explanation of the Code
-
HTML Structure:
<canvas id="gameCanvas"></canvas>: The main canvas where the game is rendered.
<div id="overlay">Score: 0</div>: Displays the current score.
<div id="gameOver"> ... </div>: A game over screen with a restart button that's hidden initially.
-
Styling (<style> section):
- The canvas covers the full window with a sky-blue background.
- The overlay and game over screen are styled for visibility and user interaction.
-
JavaScript Logic (<script> section):
-
Canvas Initialization: The canvas is sized to fill the window, and it resizes dynamically when the window size changes.
-
Game Constants: Define gravity, flap strength, basket interval (time between baskets), basket speed, and maximum rotation.
-
Game State Variables: Track the score and whether the game is over.
-
Basketball Object:
- Contains properties like position
(x, y), radius, color, and vertical velocity.
flap(): Applies an upward velocity to the basketball.
update(): Updates the basketball's position based on velocity and gravity. Checks collision with the ground to trigger game over.
draw(): Renders the basketball as a circle with lines to resemble a real basketball.
-
Basket Class:
- Each basket has properties like size, position, speed, rotation, and a
scored flag to prevent multiple scores per basket.
update(): Moves the basket leftward across the screen.
draw(): Renders the basket as a rotated rectangle.
isOffScreen(): Determines if the basket has moved past the left edge of the screen.
checkScore(basketball): Detects if the basketball is within the basket's area and moving downwards to count as a dunk.
-
Baskets Management:
- Baskets are added at regular intervals (
BASKET_INTERVAL).
- Existing baskets are updated, drawn, and checked for scoring or if they have moved off-screen.
3. Running the Game
-
Save the Code: Create an index.html file and paste the above code into it.
-
Open in Browser: Open the index.html file in your preferred web browser.
-
Play: Click (on desktop) or tap (on mobile) anywhere on the canvas to make the basketball flap upwards. Dunk the basketball into the baskets to score points. If the basketball hits the ground, the game ends, and you can restart by clicking the "Restart" button.
4. Customizations and Enhancements
You can further enhance the game by adding features such as:
- Animations: Smooth transitions for the basketball and baskets.
- Sound Effects: Add sounds for flapping, scoring, and game over.
- Levels or Increasing Difficulty: Gradually increase the speed or spawn rate of baskets as the score increases.
- Visual Effects: Add backgrounds, particle effects for dunking, etc.
- Mobile Optimization: Ensure the game is fully responsive and touch-friendly on various devices.
Feel free to modify and expand upon this basic implementation to create a more engaging and feature-rich game!