Sure! Below is a complete implementation of a Snake game combined with falling Tetris-like blocks. The game is built using HTML5 Canvas and JavaScript. In this game, you control the snake to eat food while dodging randomly falling blocks from the top.
You can control the snake using the arrow keys or WASD keys.
HTML Code
First, set up the basic HTML structure with a canvas element where the game will be rendered.
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game with Falling Blocks</title>
<style>
body {
background-color: #232323;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
canvas {
border: 1px solid #fff;
background-color: #000;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="game.js"></script>
</body>
</html>
JavaScript Code (game.js)
Create a game.js file and include the following code.
javascript Copy code
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Game settings
const gridSize = 20;
const tileCount = canvas.width / gridSize;
// Snake properties
let snake = [];
let snakeLength = 5;
let snakeDir = { x: 0, y: 0 };
let snakeSpeed = 100; // milliseconds
// Food properties
let food = { x: 0, y: 0 };
// Falling blocks properties
let blocks = [];
let blockSpawnRate = 2000; // milliseconds
let blockFallSpeed = 2;
// Game state
let gameOver = false;
let score = 0;
// Initialize the game
function init() {
snake = [];
snakeLength = 5;
snakeDir = { x: 1, y: 0 };
snakeSpeed = 100;
blocks = [];
gameOver = false;
score = 0;
// Initialize snake in the center
for (let i = snakeLength - 1; i >= 0; i--) {
snake.push({ x: Math.floor(tileCount / 2) - i, y: Math.floor(tileCount / 2) });
}
placeFood();
document.addEventListener('keydown', keyDownEvent);
setInterval(gameLoop, snakeSpeed);
setInterval(spawnBlock, blockSpawnRate);
}
// Game loop
function gameLoop() {
if (gameOver) {
drawGameOver();
return;
}
update();
draw();
}
// Update game state
function update() {
// Move snake
const head = { x: snake[0].x + snakeDir.x, y: snake[0].y + snakeDir.y };
// Check wall collision
if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
gameOver = true;
return;
}
// Check self collision
for (let s of snake) {
if (s.x === head.x && s.y === head.y) {
gameOver = true;
return;
}
}
snake.unshift(head);
// Check food collision
if (head.x === food.x && head.y === food.y) {
score += 10;
snakeLength++;
placeFood();
}
while (snake.length > snakeLength) {
snake.pop();
}
// Update blocks
for (let block of blocks) {
block.y += blockFallSpeed / gridSize;
}
// Remove off-screen blocks
blocks = blocks.filter(block => block.y < tileCount);
// Check collision with blocks
for (let block of blocks) {
if (Math.floor(block.x) === head.x && Math.floor(block.y) === head.y) {
gameOver = true;
return;
}
}
}
// Draw game elements
function draw() {
// Clear canvas
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw snake
ctx.fillStyle = '#0f0';
for (let s of snake) {
ctx.fillRect(s.x * gridSize, s.y * gridSize, gridSize - 2, gridSize - 2);
}
// Draw food
ctx.fillStyle = '#f00';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize - 2, gridSize - 2);
// Draw blocks
ctx.fillStyle = '#00f';
for (let block of blocks) {
ctx.fillRect(Math.floor(block.x) * gridSize, Math.floor(block.y) * gridSize, gridSize, gridSize);
}
// Draw score
ctx.fillStyle = '#fff';
ctx.font = '16px Arial';
ctx.fillText('Score: ' + score, 10, 20);
}
// Place food at random position
function placeFood() {
food.x = Math.floor(Math.random() * tileCount);
food.y = Math.floor(Math.random() * tileCount);
// Ensure food does not appear on the snake or blocks
for (let s of snake) {
if (s.x === food.x && s.y === food.y) {
placeFood();
return;
}
}
for (let block of blocks) {
if (Math.floor(block.x) === food.x && Math.floor(block.y) === food.y) {
placeFood();
return;
}
}
}
// Spawn a new falling block
function spawnBlock() {
const blockX = Math.floor(Math.random() * tileCount);
blocks.push({ x: blockX, y: -1 });
}
// Handle keyboard input
function keyDownEvent(e) {
switch (e.keyCode) {
case 37: // Left arrow
case 65: // A key
if (snakeDir.x === 0) {
snakeDir = { x: -1, y: 0 };
}
break;
case 38: // Up arrow
case 87: // W key
if (snakeDir.y === 0) {
snakeDir = { x: 0, y: -1 };
}
break;
case 39: // Right arrow
case 68: // D key
if (snakeDir.x === 0) {
snakeDir = { x: 1, y: 0 };
}
break;
case 40: // Down arrow
case 83: // S key
if (snakeDir.y === 0) {
snakeDir = { x: 0, y: 1 };
}
break;
}
}
// Draw game over screen
function drawGameOver() {
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#fff';
ctx.font = '40px Arial';
ctx.textAlign = 'center';
ctx.fillText('Game Over', canvas.width / 2, canvas.height / 2);
ctx.font = '20px Arial';
ctx.fillText('Score: ' + score, canvas.width / 2, canvas.height / 2 + 40);
}
// Start the game
init();
Explanation
1. Game Initialization (init function):
Initializes the snake starting position and direction.
Sets initial game variables like score and game over state.
Places the first food item on the board.
Sets up keyboard event listeners.
Starts the gameLoop and spawnBlock intervals.
2. Game Loop (gameLoop function):
Checks if the game is over; if so, displays the game over screen.
Updates the game state by moving the snake, handling collisions, and updating falling blocks.
Draws the game elements on the canvas.
3. Update Function (update):
Moves the snake in the current direction.
Checks for collision with walls, self, food, and blocks.
Increases the snake's length if it eats food.
Moves the falling blocks down.
Removes blocks that have fallen off-screen.
4. Drawing Function (draw):
Clears the canvas.
Draws the snake, food, and falling blocks.
Displays the current score.
5. Keyboard Input Handling (keyDownEvent):
Changes the snake's direction based on arrow keys or WASD keys.
Prevents reversing direction directly to avoid immediate self-collision.
6. Falling Blocks (blocks array and spawnBlock function):
blocks array holds the positions of the falling blocks.
spawnBlock function adds a new block at a random x-position at the top of the canvas.
Blocks move down each frame and are removed if they move off-screen or collide with the snake.
7. Collision Detection:
Wall Collision: Checks if the snake's head is outside the boundaries.
Self Collision: Checks if the snake's head collides with any part of its body.
Food Collision: Checks if the snake's head is on the same tile as the food.
Block Collision: Checks if the snake's head is on the same tile as any falling block.
8. Game Over Screen (drawGameOver function):
Displays "Game Over" text and the player's final score.
How to Run the Game
Create Project Files:
Create an index.html file and paste the HTML code.
Create a game.js file and paste the JavaScript code.
Ensure both files are in the same directory.
Open in Browser:
Open index.html in a modern web browser (e.g., Chrome, Firefox).
Control the Snake:
Use arrow keys or WASD keys to control the snake.
Avoid falling blocks and the walls.
Eat the red food squares to grow and increase your score.
Customization and Enhancements
Adjust Difficulty:
Modify snakeSpeed to change how fast the snake moves.
Modify blockSpawnRate and blockFallSpeed to adjust the frequency and speed of falling blocks.
Graphics Enhancements:
Add images or sprites for the snake, food, and blocks.
Implement smoother animations.
Feature Additions:
Add sound effects and background music.
Introduce different types of blocks with varying behaviors.
Implement levels or increasing difficulty over time.
Enjoy playing the Snake game with an exciting twist of falling Tetris blocks! Let me know if you have any questions or need further assistance.