Building a Tetris Game with HTML, CSS, and JavaScript

Published on Apr 04, 2024

Hello everyone, welcome back to our channel! Today, we have an exciting tutorial for you where we’ll be creating a simple Tetris game using HTML, CSS, and JavaScript. Tetris is a classic game loved by many, and we’re going to walk you through the process of building your very own version of it from scratch.

Let’s start by setting up the HTML structure for our game. As you can see here, we have the basic structure of an HTML document. We’ve defined the language as English, included the necessary meta tags for character encoding and viewport settings.

In the head section, we’ve set the title of our webpage as “Tetris Game”. We’ve linked an external CSS file named “style.css” using the <link> tag. This CSS file will help us style our game elements and make it visually appealing.

Moving on to the body section, we have a div element with the class “canvas_wrap”. Inside this div, we have a canvas element with the id “tetris”. This canvas will serve as the playing area for our Tetris game, where all the action will happen. Additionally, we have a button with the id “start_game”, which users will click to start the game.

Now, let’s take a look at the JavaScript part of our code. We’ve included an external JavaScript Now, let’s take a look at the JavaScript part of our code. We’ve included an external JavaScript” using the <script> tag. This is where we’ll write the logic for our Tetris game, handling things like moving the tetrominoes, checking for collisions, and updating the game state.

CSS

Alright, let’s dive into the CSS part to design our Tetris game! In this segment, we’ll be styling the elements to make our game visually appealing and user-friendly.

Starting with the CSS reset, we’re targeting all elements with the asterisk wildcard * and setting their margin and padding to zero. This ensures a consistent spacing throughout our game.

Moving on to the body styling, we’ve set the background colour of the entire webpage to a light gray shade #ccc. This will provide a neutral backdrop for our game.

Now, let’s focus on the styling of our game container .canvas_wrap. We’ve centered it horizontally on the page by setting the left and right margins to auto. The container has a light background colour #f1f1f1 and some padding to give it some breathing space. Additionally, we’ve applied a border radius of 10px to give it rounded corners, adding a touch of elegance to our design.

Inside our .canvas_wrap, we’re targeting all direct children elements and centering them horizontally using margin: 0 auto;. This ensures that any elements placed inside our game container will be nicely centered.

Lastly, let’s talk about the styling of our start button. We’ve set its width to 100% of its parent container, ensuring it spans the entire width. It has some margin at the top and bottom to provide spacing, and padding to make it visually appealing. The button has a border radius of 10px for rounded corners, and we’ve chosen the Courier font family with a bold weight to make it stand out. The button itself has a background colour of #ffb000 and a contrasting text colour of #000000 for better readability. Lastly, we’ve added a cursor pointer to indicate to users that it’s clickable.

JavaScript

Alright, let’s move on to the JavaScript part to give our Tetris game some functionality! In this segment, we’ll be diving into the code that controls the game mechanics, such as moving the tetrominoes, detecting collisions, updating the score, and managing game over conditions.

Starting with the initialisation, we’re using a self-invoking anonymous function to encapsulate our code and keep the variables and functions private. We’ve set the strict mode to ensure cleaner and safer JavaScript code.

We’re obtaining references to the canvas element and its 2D rendering context, where we’ll be drawing our game. Additionally, we’re scaling the context by a factor of 20 to make the game elements larger and easier to interact with.

Next, we define a function makeMatrix that generates a 2D array representing the game area with specified width and height. This function initialises the matrix with zeros and returns it.

We have another function makePiece which creates tetromino pieces based on their type. Each tetromino is represented by a 2D array of numbers, where each number corresponds to a specific color.

The points function checks for completed rows in the game area and awards points accordingly. It updates the player’s score based on the number of rows cleared.

The collide function checks for collisions between the current tetromino and the game area. It returns true if there’s a collision, indicating that the tetromino cannot be moved further.

The drawMatrix function draws a given matrix onto the canvas, applying offsets for positioning. It utilises an array of colour values to render different tetromino shapes.

The merge function merges the current tetromino into the game area when it cannot move further, updating the game state.

We define a rotate function to rotate tetromino pieces clockwise or counterclockwise based on the specified direction.

The playerReset function resets the player’s position and selects a new random tetromino piece when a new game starts. It also handles game over conditions.

These functions control the movement of the current tetromino piece – dropping it down, moving it left or right, and rotating it respectively. They also handle collision detection .

The draw function clears the canvas, draws the game area and current tetromino, and updates the score display. The update function manages the game loop, controlling the timing of drops and updates.

Finally, we have the gameOver function, which is triggered when the game ends. It clears the game loop, displays a “Game Over” message, and enables the start button for a new game.

And there you have it! Our JavaScript code is ready to breathe life into our Tetris game. That wraps up this video. Stay tuned for more tutorials, and don’t forget to subscribe to our channel for updates. Happy coding!

Our Latest Blog

Java Programming

Introduction to Java Programming Getting Started with the Basics

Welcome to the innovative world of Java programming. Java is an important and powerful programming...
Read More
Reinforcement Learning

Future Trends in Reinforcement Learning Innovations and Opportunities

Reinforcement Learning (RL) is an important branch of artificial intelligence (AI) in which agents learn...
Read More
LSET's New Course

How LSET’s New Course Structure Enhances Your Learning Experience

LSET stands out for its commitment to nonstop enhancement in the ever-evolving geography of education....
Read More