Snake Game JavaScript

Mastering the Classics: Building a Snake Game with JavaScript

When it comes to retro gaming, few titles are as iconic and nostalgic as the classic Snake game. This simple yet addictive game has captured the hearts of gamers across generations. Today, we're going to revisit this classic and build our own version of the Snake game using JavaScript.

Introduction to the Snake Game

The Snake game, also known as Nibbles, is a classic arcade game that was popularized by Nokia phones in the late 90s and early 2000s. In this game, players control a snake that grows longer as it eats apples or pellets scattered across the screen. The goal is to keep the snake alive by avoiding collisions with the walls or itself.

Getting Started with JavaScript

Before we dive into the code, let's set up our development environment. You'll need a text editor or IDE (Integrated Development Environment) to write your code. Popular choices include Visual Studio Code, Sublime Text, or Atom.

Once you have your editor set up, create a new HTML file called "index.html" and a JavaScript file called "snake.js". Link the JavaScript file to your HTML document using the <script> tag.

html复制代码
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<style>
/* Add your CSS styles here */
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>

Now we're ready to start coding our Snake game in JavaScript.

Setting Up the Game Board

The first step is to set up the game board. We'll use the HTML5 <canvas> element to render our game. In your JavaScript file, start by selecting the canvas element and getting its 2D rendering context.

javascript复制代码
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

Next, let's define some global variables for our game. We'll need variables for the snake's position, direction, and speed, as well as variables for the size of the game board and the size of each cell.

javascript复制代码
let snake = [{ x: 10, y: 10 }]; // Initial snake position
let dx = 1; // Horizontal movement
let dy = 0; // Vertical movement
let food = { x: null, y: null }; // Food position
let changingDirection = false; // Flag to prevent immediate direction changes
const cellSize = 20; // Size of each cell in pixels
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
const gridWidth = canvasWidth / cellSize;
const gridHeight = canvasHeight / cellSize;

Drawing the Game Board and Snake

Now that we have our variables set up, let's create a function to draw the game board and the snake. We'll use the fillStyle and fillRect methods of the canvas context to draw each cell.

javascript复制代码
function drawGame() {
// Clear the canvas
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// Draw the snake
ctx.fillStyle = 'green';
for (let cell of snake) {
ctx.fillRect(cell.x * cellSize, cell.y * cellSize, cellSize, cellSize);
}
// Draw the food
ctx.fillStyle = 'red';
ctx.fillRect(food.x * cellSize, food.y * cellSize, cellSize, cellSize);
}

Moving the Snake

To move the snake, we'll create a function called moveSnake that updates the snake's position based on its current direction. We'll also need to check if the snake has eaten the food and grow it accordingly.

javascript复制代码
function moveSnake() {
// Create a new head for the snake based on its current direction
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
snake.unshift(head); // Add the new head to the front of the snake array
// Check if the snake has eaten the food
if (snake[0].x === food.x && snake[0].y === food.y) {
// Generate new food position (omitted for brevity)
// ...
} else {
snake.pop(); // Remove the tail from the snake array
}
}

Controlling the Snake

To control the snake, we'll listen for keyboard events and update the snake's direction accordingly. We'll use the addEventListener method to listen for keydown events and update the dx and dy variables based on the pressed key.

javascript复制代码
document.addEventListener('keydown', function (event) {
switch (event.key) {
case 'ArrowUp':
if (dy === 0) { dy = -1; dx = 0; changingDirection = true; }
break;
case 'ArrowDown':
if (dy === 0) { dy = 1; dx = 0; changingDirection = true; }
break;
case 'ArrowLeft':
if (dx === 0) { dx = -1; dy = 0; changingDirection = true; }
break;
case 'ArrowRight':
if (dx === 0) { dx = 1; dy = 0; changingDirection = true; }
break;
}
});

Note that we added a changingDirection flag to prevent the snake from changing direction immediately after eating the food, which can cause it to crash into itself.

Game Loop and Collision Detection

Finally, we need to create a game loop that updates the game state and checks for collisions. We'll use setInterval to create a repeating timer that calls our update and draw functions.

Inside the game loop, we'll check if the snake has collided with the walls or itself. If a collision occurs, we'll stop the game loop and display a game over message.

javascript复制代码
function gameLoop() {
if (changingDirection) {
changingDirection = false;
} else {
moveSnake();
}
// Check for collisions (omitted for brevity)
// ...
drawGame();
}
let gameInterval = setInterval(gameLoop, 100); // Update the game every 100ms

Wrapping Up

That's it! You now have a basic Snake game implemented in JavaScript. Of course, there's still plenty of room for improvement and customization. You can add scoring, levels, different types of food, and more to enhance the gameplay experience.

Conclusion

Building a Snake game with JavaScript is a fun and educational exercise that teaches you about game development, programming logic, and interactive media. Whether you're a beginner or an experienced developer, revisiting classic games like Snake can provide valuable insights into game mechanics and player engagement.

So, grab your favorite text editor, fire up your browser, and start coding! Who knows, maybe your version of Snake will become the next retro gaming hit.

Resources and Further Learning

  • MDN Web Docs: An excellent resource for learning JavaScript and web development.
  • HTML5 Canvas Tutorial: Learn more about the HTML5 <canvas> element and how to draw graphics with JavaScript.
  • Game Development Tutorials: A collection of tutorials and resources for game development with JavaScript and other web technologies.

Remember, practice makes perfect! Keep coding, experimenting, and learning to become a master of JavaScript game development.

Back to blog

Contact Us