Open In App

Snake Game using Angular

Last Updated : 05 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Snake game is one of the most popular software games ever made for computers as well as mobile devices. It is a simple game where player has to control the snake and eat food which are randomly spawned in order to score points.

In this article, we will be creating the snake game using the Angular framework. Note that this tutorial uses Angular version 17 instead of the outdated AngularJS framework.

Prerequisites

Approach

We will be using the HTML canvas element to display the game, and all the game mechanics and logic will be handled by our Angular component class. Functions for individual features of the game are implemented like:

  • Change the direction of the moving snake
  • Generate food at random places of the map
  • Check whether the snake is going out of boundaries or hitting itself
  • Increase the score if snake eats the food

Steps to Create Snake Game using Angular

Step 1: Install Angular CLI

Before creating the project, make sure that Node is installed in your computer. To install node in your computer you can follow this article. If installed, make sure that Angular is installed as a global dependency in your computer. If you do not have angular installed, install it using the command:

npm install -g @angular/cli

After installing Angular you can check the version. By default, the above command installs the latest Angular version which is available.

ng version

Step 2: Create a new Angular project named "snakegame" using the command:

ng new snakegame

It will ask for selecting stylesheet format. This article uses CSS. Also select No for enabling Server Side Rendering (SSR) if asked. It will take some time to download the project resources.

Folder Structure

projectstructure
Folder Structure

Dependencies

"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Example

HTML
//app.component.html
<div id="container">
    <h1>Snake Game</h1>
    <canvas #screen id="screen"></canvas>
    <h2>Score: {{ score }}</h2>
</div>
CSS
/*app.component.css */

#screen {
    width: 400px;
    height: 400px;
    outline: 1px solid black;
}

#container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

h1 {
    color: green;
}
JavaScript
//app.component.ts

import { Component, ViewChild, ElementRef } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
})
export class AppComponent {
    score: number = 0;

    @ViewChild("screen", { static: false })
    canvas!: ElementRef;

    ngAfterViewInit() {
        let ctx = this.canvas.nativeElement.getContext('2d');

        let gameOver: boolean = false;

        let snake = [
            { x: 20 * 4, y: 0 },
            { x: 20 * 3, y: 0 },
            { x: 20 * 2, y: 0 },
            { x: 20, y: 0 },
            { x: 0, y: 0 }
        ];

        let xVelocity: number = 20;
        let yVelocity: number = 0;

        let foodX: number;
        let foodY: number;

        function checkGameOver() {
            if (snake[0].x < 0) {
                gameOver = true;
            }
            else if (snake[0].x >= 280) {
                gameOver = true;
            }
            else if (snake[0].y < 0) {
                gameOver = true;
            }
            else if (snake[0].y >= 140) {
                gameOver = true;
            }
            for (let i = 1; i < snake.length; i += 1) {
                if (snake[i].x == snake[0].x && snake[i].y == snake[0].y) {
                    gameOver = true;
                }
            }
        };

        function createFood() {
            do {
                foodX = Math.floor((Math.random() * 13) + 1) * 20;
                foodY = Math.floor((Math.random() * 13) + 1) * 10;
            }
            while (snake.includes({ x: foodX, y: foodY }))
        };

        function drawFood() {
            ctx.fillStyle = 'red';
            ctx.fillRect(foodX, foodY, 20, 10);
        };

        function moveSnake() {
            const head = {
                x: snake[0].x + xVelocity,
                y: snake[0].y + yVelocity
            };
            snake.unshift(head);
        }

        function drawSnake() {
            ctx.fillStyle = 'black';
            snake.forEach(snakePart => {
                ctx.fillRect(snakePart.x, snakePart.y, 20, 10);
            })
        };

        function changeDirection(event: any) {
            const keyPressed = event.keyCode;

            const LEFT = 37;
            const UP = 38;
            const RIGHT = 39;
            const DOWN = 40;

            const goingUp = (yVelocity == -10);
            const goingDown = (yVelocity == 10);
            const goingRight = (xVelocity == 20);
            const goingLeft = (xVelocity == -20);

            if (keyPressed == LEFT && !goingRight) {
                xVelocity = -20;
                yVelocity = 0;
            }
            else if (keyPressed == UP && !goingDown) {
                xVelocity = 0;
                yVelocity = -10;
            }
            else if (keyPressed == RIGHT && !goingLeft) {
                xVelocity = 20;
                yVelocity = 0;
            }
            else if (keyPressed == DOWN && !goingUp) {
                xVelocity = 0;
                yVelocity = 10;
            }
        };
        createFood();
        let id = setInterval(() => {
            if (!gameOver) {
                window.addEventListener("keydown", changeDirection);
                checkGameOver();
                ctx.fillStyle = 'lightgray';
                ctx.fillRect(0, 0, 400, 400);
                drawFood();
                moveSnake();
                drawSnake();
                if (snake[0].x == foodX && snake[0].y == foodY) {
                    this.score++;
                    createFood();
                }
                else {
                    snake.pop();
                }
            }
            else {
                var answer = confirm("Game Over!")
                if (answer) location.reload();
                clearInterval(id)
            }
        }, 250);
    }
}

In order to run the application, use the following command in your terminal:

ng serve

Go to http://localhost:4200 using any browser and you can start playing the snake game.

Output



Next Article

Similar Reads