Snake Game Javascript Code Github

Snake Game Javascript Code Github

6 min read Jun 20, 2024
Snake Game Javascript Code Github

Snake Game with Javascript: A Simple Guide and Code Example

This article will guide you through building a classic Snake game using Javascript. We'll cover the core concepts, provide a code example, and explain how to implement it.

Project Setup

  1. Create a New Project Folder: Start by creating a new folder for your game project.
  2. Create HTML, CSS, and JavaScript Files: Within the folder, create three files: index.html, style.css, and script.js.

HTML Structure (index.html)




    Snake Game
    


    
    


  • Canvas Element: We use the <canvas> element to draw the game.
  • CSS and Javascript Links: Link the style.css and script.js files.

CSS Styling (style.css)

body {
    background-color: #f0f0f0;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    margin: 0;
}

#gameCanvas {
    border: 2px solid black;
}
  • Basic Styling: This CSS provides a simple background for the game and centers the canvas on the screen.

Javascript Implementation (script.js)

const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

const gridSize = 20;
let snake = [{ x: 10, y: 10 }];
let food = {};
let direction = "right";
let score = 0;

function generateFood() {
    food = {
        x: Math.floor(Math.random() * (canvas.width / gridSize)),
        y: Math.floor(Math.random() * (canvas.height / gridSize))
    };
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (let i = 0; i < snake.length; i++) {
        ctx.fillStyle = i === 0 ? "green" : "lime";
        ctx.fillRect(snake[i].x * gridSize, snake[i].y * gridSize, gridSize, gridSize);
    }

    ctx.fillStyle = "red";
    ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
}

function update() {
    const head = { x: snake[0].x, y: snake[0].y };

    switch (direction) {
        case "up": head.y--; break;
        case "down": head.y++; break;
        case "left": head.x--; break;
        case "right": head.x++; break;
    }

    snake.unshift(head);

    if (head.x === food.x && head.y === food.y) {
        score++;
        generateFood();
    } else {
        snake.pop();
    }

    if (head.x < 0 || head.x >= canvas.width / gridSize || head.y < 0 || head.y >= canvas.height / gridSize || checkCollision()) {
        gameOver();
    }

    draw();
}

function checkCollision() {
    for (let i = 1; i < snake.length; i++) {
        if (snake[0].x === snake[i].x && snake[0].y === snake[i].y) {
            return true;
        }
    }
    return false;
}

function gameOver() {
    alert("Game Over! Score: " + score);
    clearInterval(gameLoop);
}

function handleKeyDown(event) {
    const keyPressed = event.key;

    if (keyPressed === "ArrowUp" && direction !== "down") {
        direction = "up";
    } else if (keyPressed === "ArrowDown" && direction !== "up") {
        direction = "down";
    } else if (keyPressed === "ArrowLeft" && direction !== "right") {
        direction = "left";
    } else if (keyPressed === "ArrowRight" && direction !== "left") {
        direction = "right";
    }
}

generateFood();
draw();

const gameLoop = setInterval(update, 100); // Adjust speed with interval value
document.addEventListener("keydown", handleKeyDown); 
  • Canvas and Context: Get the canvas element and its drawing context.
  • Grid Size: Define the grid size for the game.
  • Snake and Food: Initialize the snake and food objects.
  • Direction: Track the current direction of the snake.
  • Score: Store the player's score.
  • generateFood(): Creates a new food position randomly.
  • draw(): Clears the canvas and draws the snake and food.
  • update(): Updates the snake's position based on the direction, handles food consumption, checks for collisions, and calls draw().
  • checkCollision(): Checks if the snake collides with itself.
  • gameOver(): Stops the game loop and displays the score.
  • handleKeyDown(): Handles arrow key presses to change the snake's direction.
  • Game Loop: The setInterval() function repeatedly calls the update() function at a set interval.
  • Event Listener: The addEventListener() function listens for key presses and calls handleKeyDown().

This is a basic implementation of a snake game. You can expand on this code to add features like:

  • Score Display: Create an element to display the score on the screen.
  • Level System: Increase the game speed or add new challenges as the score increases.
  • Sound Effects: Add sound effects for eating food, hitting a wall, and game over.
  • Obstacles: Add obstacles to the game board that the snake cannot pass through.

Remember to test your code and have fun experimenting with different features!