Write the snake game in HTML canvas combined with tetris, there are gonna be blocked falling from the top (you can't control them) and you have to dodge them with the snake (WASD or arrows) and eat the fruit etc.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating a game that combines the classic Snake mechanics with falling Tetris-like blocks involves integrating several elements: rendering the game on an HTML Canvas, handling user input for controlling the snake, managing the falling blocks, spawning fruits for the snake to eat, and implementing collision detection.
Below is a complete implementation of such a game using HTML, CSS, and JavaScript. You can copy the code into an .html file and open it in your browser to play.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake-Tetris Hybrid Game</title>
<style>
body {
background-color: #222;
color: #fff;
text-align: center;
margin: 0;
padding: 0;
overflow: hidden;
font-family: Arial, sans-serif;
}
#gameCanvas {
background-color: #333;
display: block;
margin: 20px auto;
border: 2px solid #555;
}
#score {
font-size: 24px;
}
#startButton {
padding: 10px 20px;
font-size: 18px;
cursor: pointer;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Snake-Tetris Hybrid Game</h1>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<div id="score">Score: 0</div>
<button id="startButton">Start Game</button>
<script>
// Game Constants
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20; // Size of each grid square
const canvasSize = canvas.width; // Assuming square canvas
const numRows = canvasSize / gridSize;
const numCols = canvasSize / gridSize;
const snakeColor = '#0f0';
const blockColor = '#f00';
const fruitColor = '#ff0';
const initialSnakeLength = 5;
const snakeSpeed = 100; // milliseconds per move
const blockFallInterval = 2000; // milliseconds between new blocks
// Direction vectors
const directions = {
'ArrowUp': {x: 0, y: -1},
'ArrowDown': {x: 0, y: 1},
'ArrowLeft': {x: -1, y: 0},
'ArrowRight': {x: 1, y: 0},
'w': {x: 0, y: -1},
's': {x: 0, y: 1},
'a': {x: -1, y: 0},
'd': {x: 1, y: 0},
};
// Game Variables
let snake;
let direction;
let nextDirection;
let fruits = [];
let blocks = [];
let score = 0;
let gameInterval;
let blockInterval;
let isGameOver = false;
// Event Listener for Keyboard
document.addEventListener('keydown', (e) => {
if (directions[e.key]) {
const newDir = directions[e.key];
// Prevent the snake from reversing
if (snake.length > 1 && (newDir.x === -direction.x && newDir.y === -direction.y)) {
return;
}
nextDirection = newDir;
}
});
// Start Button Listener
document.getElementById('startButton').addEventListener('click', startGame);
// Initialize the game state
function startGame() {
clearInterval(gameInterval);
clearInterval(blockInterval);
snake = [];
for (let i = initialSnakeLength - 1; i >= 0; i--) {
snake.push({x: i, y: Math.floor(numRows / 2)});
}
direction = {x: 1, y: 0};
nextDirection = direction;
fruits = [];
blocks = [];
score = 0;
isGameOver = false;
document.getElementById('score').innerText = `Score: ${score}`;
gameInterval = setInterval(gameLoop, snakeSpeed);
blockInterval = setInterval(generateBlock, blockFallInterval);
}
// Game Loop
function gameLoop() {
if (isGameOver) {
clearInterval(gameInterval);
clearInterval(blockInterval);
alert('Game Over! Your score: ' + score);
return;
}
// Update direction
direction = nextDirection;
// Calculate next head position
const head = {x: snake[snake.length - 1].x + direction.x, y: snake[snake.length - 1].y + direction.y};
// Wrap around the edges
if (head.x < 0) head.x = numCols - 1;
if (head.x >= numCols) head.x = 0;
if (head.y < 0) head.y = numRows - 1;
if (head.y >= numRows) head.y = 0;
// Check collision with blocks
for (let block of blocks) {
if (block.x === head.x && block.y === head.y) {
isGameOver = true;
return;
}
}
// Check collision with itself
for (let segment of snake) {
if (segment.x === head.x && segment.y === head.y) {
isGameOver = true;
return;
}
}
// Add new head to the snake
snake.push(head);
// Check if fruit is eaten
let ateFruit = false;
for (let i = 0; i < fruits.length; i++) {
if (fruits[i].x === head.x && fruits[i].y === head.y) {
ateFruit = true;
fruits.splice(i, 1);
score += 10;
document.getElementById('score').innerText = `Score: ${score}`;
break;
}
}
if (!ateFruit) {
// Remove the tail
snake.shift();
}
// Move blocks
moveBlocks();
// Generate random fruit
if (fruits.length < 3 && Math.random() < 0.02) {
generateFruit();
}
// Draw everything
draw();
}
// Generate a new fruit at a random position
function generateFruit() {
let position;
let conflict;
do {
conflict = false;
position = {
x: Math.floor(Math.random() * numCols),
y: Math.floor(Math.random() * numRows)
};
// Ensure fruit doesn't spawn on the snake or on blocks
for (let segment of snake) {
if (segment.x === position.x && segment.y === position.y) {
conflict = true;
break;
}
}
if (!conflict) {
for (let block of blocks) {
if (block.x === position.x && block.y === position.y) {
conflict = true;
break;
}
}
}
} while (conflict);
fruits.push(position);
}
// Generate a new falling block
function generateBlock() {
// Generate a block at a random x position at the top
const x = Math.floor(Math.random() * numCols);
const y = 0;
// Ensure it doesn't spawn on the snake or fruit
for (let segment of snake) {
if (segment.x === x && segment.y === y) {
return; // Skip generating this block
}
}
for (let fruit of fruits) {
if (fruit.x === x && fruit.y === y) {
return;
}
}
blocks.push({x, y});
}
// Move all blocks down by one
function moveBlocks() {
for (let block of blocks) {
block.y += 1;
}
// Remove blocks that have moved off the screen
blocks = blocks.filter(block => block.y < numRows);
}
// Draw the game state
function draw() {
// Clear the canvas
ctx.fillStyle = '#333';
ctx.fillRect(0, 0, canvasSize, canvasSize);
// Draw the snake
ctx.fillStyle = snakeColor;
for (let segment of snake) {
ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 2, gridSize -2);
}
// Draw the blocks
ctx.fillStyle = blockColor;
for (let block of blocks) {
ctx.fillRect(block.x * gridSize, block.y * gridSize, gridSize - 2, gridSize -2);
}
// Draw the fruits
ctx.fillStyle = fruitColor;
for (let fruit of fruits) {
ctx.beginPath();
ctx.arc(fruit.x * gridSize + gridSize / 2, fruit.y * gridSize + gridSize / 2, gridSize / 2 - 2, 0, 2 * Math.PI);
ctx.fill();
}
}
// Initial draw
draw();
</script>
</body>
</html>
Explanation of the Code
HTML Structure:
Canvas: The <canvas> element is where the game is rendered. It has a specified width and height (400x400 pixels) and an id of gameCanvas.
Score Display: A <div> with id="score" displays the current score.
Start Button: A <button> with id="startButton" allows the player to start or restart the game.
CSS Styling:
The body is styled with a dark background and centered text.
The canvas has a darker background and a border to distinguish the game area.
The score and button are styled for better visibility.
JavaScript Logic:
Constants and Variables:
gridSize: Defines the size of each grid square. The game grid is based on dividing the canvas into a grid of numCols x numRows.
Colors are defined for the snake, blocks, and fruits.
snakeSpeed: Determines how fast the snake moves (in milliseconds).
blockFallInterval: Determines how often new blocks are generated.
Direction Handling:
The directions object maps key presses (W, A, S, D or arrow keys) to direction vectors.
An event listener captures key presses to update the snake's direction, ensuring the snake cannot reverse directly.
Game Initialization (startGame):
Resets all game variables, including the snake's initial position, direction, empty arrays for fruits and blocks, and the score.
Starts two intervals:
gameInterval: Runs the gameLoop function at intervals defined by snakeSpeed.
blockInterval: Generates new blocks at intervals defined by blockFallInterval.
Game Loop (gameLoop):
Game Over Check: If the game is over, it stops the intervals and alerts the player.
This implementation provides a solid foundation for the Snake-Tetris hybrid game. You can further enhance and customize it based on your preferences and desired complexity.
Direction Update: Updates the current direction based on user input.
Head Movement: Calculates the new head position of the snake based on the current direction.
Edge Wrapping: The snake wraps around to the opposite side if it moves beyond the canvas boundaries.
Collision Detection:
With Blocks: If the snake's head collides with any falling block, the game is over.
With Itself: If the snake's head collides with its body, the game is over.
Fruit Consumption:
If the snake eats a fruit, it grows (by not removing the tail) and the score increases.
If not, the tail segment is removed to keep the snake's length constant.
Block Movement: Moves all blocks down by one row and removes those that have moved off-screen.
Fruit Generation: Randomly spawns new fruits ensuring they do not overlap with the snake or blocks.
Rendering: Calls the draw function to update the game visuals.
Block Management (generateBlock, moveBlocks):
generateBlock: Spawns a new block at a random horizontal position at the top of the canvas, ensuring it doesn't overlap with the snake or existing fruits.
moveBlocks: Moves all existing blocks down by one row and removes those that go beyond the canvas.
Fruit Management (generateFruit):
Randomly places a fruit on the grid, ensuring it doesn't overlap with the snake or blocks.
Rendering (draw):
Clears the canvas.
Draws the snake, blocks, and fruits with their respective colors.
The snake is drawn as filled rectangles.
Blocks are also drawn as filled rectangles.
Fruits are drawn as circles for visual distinction.
Gameplay Instructions:
Controls: Use W, A, S, D or the arrow keys to move the snake up, left, down, and right respectively.
Objective: Eat fruits to grow the snake and increase your score while dodging the falling blocks. Avoid collisions with the blocks and the snake's own body.
Enhancements & Considerations:
Difficulty Scaling: You can increase the game's difficulty by decreasing the snakeSpeed or blockFallInterval as the score increases.
Block Shapes: Currently, blocks are single squares. For a more Tetris-like experience, you can implement different shapes (like L, T, etc.) that fall together.
Score Display: The score updates dynamically as the player eats fruits.
Responsive Design: Adjust the canvasSize and gridSize for different screen sizes or make the canvas responsive.
Running the Game:
Save the provided code in a file named, for example, snake_tetris_game.html.
Open the file in any modern web browser.
Click the "Start Game" button to begin playing.
Possible Extensions:
Levels: Introduce levels that change the falling speed or the number of blocks.
High Scores: Implement a high score tracker using localStorage.
Pause Functionality: Allow the player to pause and resume the game.
Sound Effects: Add audio feedback for actions like eating fruits or game over.