Snake Game with JavaScript. Part 1

This is part of the course “Snake Game with JavaScript”.

Image for post
Image for post
GitHub Repository and Deployed Game

In this course, we will build a Snake Game with JavaScript without using any libraries. We will utilize functional and immutable programming, learn canvas rendering, applications of vectors, and basics of game development. You can find the source code in this GitHub repository, and check out the game here.

In the first part of this series, we will write all HTML and CSS and implement a few utility functions that we will often use in the game.

HTML

In the HTML file, we will have a header with text that shows current and best score of the player, and container to which will be attached canvas.

Besides HTML file, we will also have one file with code for the game and one file with styles that we are loading via link and script attributes.

CSS

We have nothing fancy in styles. To make content take the full height of the page — we are making the height of html and body equal to100%. Our goal is to make the game look cool on any screen size, to do so we will make text size in percents.

Most boring stuff is done and we won’t come back to the index.html and styles.css later in this series.

JavaScript

Since we don’t use any libraries in this project, we won’t have a tool that will bandle our .js files in one. Also, we have not a big game so it will be alright if we will put everything in one place. To not lost in the JavaScript we will use VSCode feature that allows folding parts of the code via comments that start with #region and ends with #endregion.

At the end of the series, we will fill each region and make an exciting snake game.

General Utils

We start by creating a few utils that we will use in different parts of the game.

Below you can see examples of what they do.

Image for post
getRange(5)
Image for post
Image for post
getRandomFrom([1, 2, 3, 4])
Image for post
Image for post
getWithoutLastElement([1, 2, 3, 4])
Image for post
Image for post
getLastElement([1, 2, 3, 4])

The last function is checking if two float numbers are equal, by checking if their absolute difference is smaller than some super small number.

In this part, we’ve finished with HTML, CSS, and general utils. The commit with these changes you can find here. In the next part, we will implement Segment and Vector classes. Stay tuned!

Reach the next level of focus and productivity with increaser.org.

Image for post
Image for post
Increaser

Written by

Software engineer, creator of increaser.org. More at geekrodion.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store