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
Folder StructureDependencies
"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
Similar Reads
How to Create Todo List in Angular 7 ?
The ToDo app is used to help us to remember some important task. We just add the task and when accomplished, delete them. This to-do list uses various Bootstrap classes that make our web application not only attractive but also responsive. Approach: Create a new angular app using following command:
2 min read
Build a Simple Web App with Express & Angular
Building a simple web app using Express and Angular is a great way to understand the fundamentals of full-stack development. Express, a minimalist web framework for Node.js, handles the backend, while Angular, a powerful front-end framework, provides the structure for the client-side application. In
5 min read
How to build progressive web app(PWA) in Angular 9 ?
In this article, we will develop a PWA (Progressive Web App) using Angular. What is PWA ? Progressive Web Apps (PWAs) are web applications that have been designed so that they are capable, reliable, and installable. PWA are built and enhanced with modern APIs to deliver enhanced capabilities, reliab
7 min read
Routing in Angular 9/10
Routing in Angular allows the users to create a single-page application with multiple views and allows navigation between them. Users can switch between these views without losing the application state and properties. Approach: Create an Angular app that to be used.Create the navigation links inside
3 min read
How to create a To-Do list using Drag and Drop in Angular 7 ?
We can easily create a To-Do list using Drag-Drop module provided by angular Component Development Kit (CDK). First of all, create an angular component by using the following command- ng g c To-Do Now import CdkDragDrop, moveItemInArray, transferArrayItem from @angular/cdk/drag-drop to our to-Do com
2 min read
How to make a multi-select dropdown using Angular 11/10 ?
In this article, we will learn to build the multiple selection drop-down menu in Angular. To accomplish this task, we require Angular 10 or the Angular 11 version. Sometimes we need to display dynamically fetched multi-selected data in a drop-down menu, for this, we will use the npm @ng-select/ng-se
3 min read
How to set focus on input field automatically on page load in AngularJS ?
We can focus on any input field automatically using the angular directives. Here we create a custom directive that can auto-focus on any field in the form. Creating a custom directive is just like creating an Angular component. To create a custom directive we have to replace @Component decorator wit
3 min read
How to Scroll to an Element on click in Angular ?
In this article, we will see how to scroll to an element on click in Angular. Here, we will create a component that enables scrolling to specific targets when a button is pressed within the document from one target to another. Steps for Installing & Configuring the Angular ApplicationStep 1: Cre
4 min read
AngularJS $locationProvider
The $locationProvider facilitates the configuration of the application by implementing the deep linking paths that are stored. Here are some of the things that can be made with the $locationProvider service: Set the html5Mode property to true to enable HTML5 mode, which uses the history.pushState AP
4 min read
AngularJS $location Service
The $location in AngularJS basically uses a window.location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS. There are various methods in the $location s
4 min read