{}const=>[]async()letfn</>var
WebPracticeDevelopment

Tower Blocks — An exciting 3D game in JavaScript

Learn how to create Tower Blocks Game, a 3D game where you build a tower of blocks. Learn how to use Three.js and GSAP to create animations, score points, and control the game process.

К

Kodik

Author

7 min read

Tower Blocks Game is a fascinating arcade game in which the player must build a tower by placing blocks on top of each other. The goal is to place the blocks as accurately as possible so that the tower remains stable.

In this tutorial, we will create Tower Blocks Game using HTML, CSS, and JavaScript. We will use Three.js for 3D visualization and GSAP for smooth animations. The game includes:

  1. Animation of blocks that move and stop.

  2. Changing the size and position of blocks depending on the accuracy of placement.

  3. Scoring and game interface.


Game Description

Tower Blocks Game - is a game where you need to build a tower by placing moving blocks. The more accurately you place the blocks, the higher the tower will be. If the block goes beyond the previous one, part of the block is cut off. The game ends if the blocks completely miss the tower.

Features:

  • Easy to use (click or space).

  • Colorful 3D graphics.

  • Gradually more complex gameplay.


Stages of game development

1. Creating an HTML structure

  • Add the main elements: a container for the game, blocks for the interface (score, instructions, game end screen).

  • Connect styles and scripts: Three.js, GSAP, and the main JavaScript file.

2. Styling with CSS

  • Use styles to center the game container.

  • Create animations for the appearance of interface elements.

  • Configure the adaptability of the interface for different screens.

3. Game logic in JavaScript

  • Stage class: setting up the scene, camera, and lighting.

  • Block class: control of individual blocks (sizes, movement, placement).

  • Game class: game process management (adding blocks, scoring, game status).

4. Implementation of block mechanics

  • Block movement along the axis.

  • Determining the place of contact with the previous block.

  • Crop the block if it goes beyond the borders.

5. Control setup

  • Respond to keystrokes and mouse clicks to place blocks.

6. Scoring and game completion

  • Increase the score for each correctly placed block.

  • End the game if the block misses.

7. Testing and optimization

  • Make sure the game works on all devices and screens.

  • Check that the transitions between game states are smooth.

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Tower Blocks Game</title>
    <link rel="stylesheet" href="style.css"> <!-- Подключение стилей -->
</head>
<body>
    <div id="container">
        <!-- Основная область игры -->
        <div id="game"></div>
        
        <!-- Счет игры -->
        <div id="score">0</div>
        
        <!-- Инструкции -->
        <div id="instructions">Кликните, чтобы разместить блок</div>
        
        <!-- Экран окончания игры -->
        <div class="game-over">
            <h2>Игра окончена</h2>
            <p>Вы отлично справились, вы лучший.</p>
            <p>Кликните, чтобы начать заново</p>
        </div>
        
        <!-- Экран готовности к началу игры -->
        <div class="game-ready">
            <div id="start-button">Начать</div>
        </div>
    </div>

    <!-- Подключение скриптов -->
    <script src="https:// codepen.io/steveg3003/pen/zBVakw.js "> </ script> <!-- Library for auxiliary functions ->
    <script src="https:// cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.min.js "> </ script> <!-- Three.js for working with 3D ->
    <script src="https:// cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script> <! -- GSAP for animation -- >
    <script src="script.js"></script> <!-- Основная логика игры -->
</body>
</html>

What are we doing in this HTML?

  1. Adding the game structure:

    • Create a container with id="container", which will be the main area of the game.

    • Inside the container we place:

      • #game — area for rendering 3D graphics using Three.js.

      • #score — the game score, which is updated in real time.

      • #instructions — a hint for the player that is displayed at the beginning of the game.

      • .game-over — the screen that appears when the game is completed.

      • .game-ready — screen with a button to start the game.

  2. Connecting styles:

    • We use <link> to connect the style.css file, which sets the appearance of the game and styles the interface.

  3. Connecting libraries and scripts:

    • Three.js — a library for creating and working with 3D graphics.

    • GSAP — library for smooth animation of elements.

    • script.js — the main file with the game logic.

  4. Adding meta tags:

    • <meta charset="UTF-8"> — sets UTF-8 encoding to correctly display text in Russian.

    • <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> — provides adaptability of the game interface on mobile devices.

  5. Interaction scenarios:

    • The connected scripts implement the game mechanics:

      • #start-button starts the game.

      • Interaction with #instructions occurs at the start of the game.

      • The .game-over screen appears if the player makes a mistake.

Adding CSS styles

To style Tower Blocks Game, we use CSS to create a pleasant and user-friendly interface that supports adaptability and animations.


Basic elements and their styles

1. Basic settings

We disable standard indents and scrolling so that the game takes up the entire screen:

html, body {
  margin: 0;
  overflow: hidden;
  height: 100%;
  width: 100%;
  font-family: "Comfortaa", cursive;
}

2. Game container

The container occupies the entire screen and serves as the main area for the game:

#container {
  width: 100%;
  height: 100%;
}

3. Invoice

The game score is displayed at the top of the screen, has a large size and a smooth animation of appearance:

#container #score {
  position: absolute;
  top: 20px;
  width: 100%;
  text-align: center;
  font-size: 10vh;
  color: #333344;
  transition: transform 0.5s ease;
}

4. Game graphics

The #game area is designed to display 3D graphics using Three.js and occupies the entire screen:

#container #game {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

5. Game end and start screens

The .game-over and .game-ready screens appear in the center of the screen with animation:

#container .game-over, #container .game-ready {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

Where can I find the full code?

Full CSS code is available in the application Code or on GitHub project. This will allow you to study the entire styling and, if necessary, customize the appearance to your needs.

Description of the Tower Blocks Game logic (JavaScript)

JavaScript is the basis for the implementation of the entire game logic of Tower Blocks Game. It is responsible for managing the 3D scene, moving blocks, scoring, and interacting with the player.


Basic JavaScript elements and their functionality

1. Creating a 3D scene

To work with 3D graphics, we use the library Three.js. The Stage class creates a scene, camera, and lighting:

class Stage {
  constructor() {
    this.renderer = new THREE.WebGLRenderer({ antialias: true });
    this.scene = new THREE.Scene();
    this.camera = new THREE.OrthographicCamera(...);
    this.light = new THREE.DirectionalLight(0xffffff, 0.5);
    this.scene.add(this.light);
  }
}

What we do:

  • We set up the camera for orthographic projection (suitable for games with a "top view").

  • We add lighting to create visual volume.


2. Creating blocks

The Block class controls individual blocks, their size, movement, and placement:

class Block {
  constructor(previousBlock) {
    this.dimension = { width: 10, height: 2, depth: 10 };
    this.position = { x: 0, y: ..., z: 0 };
    this.mesh = new THREE.Mesh(new THREE.BoxGeometry(...), new THREE.MeshToonMaterial(...));
  }

  tick() {
    // Controls the movement of the unit
    this.position[this.workingPlane] += this.direction;
  }

  place() {
    // Block cropping logic when not matching the previous one
  }
}

What we do:

  • Set the size and initial positions of the blocks.

  • We implement the movement of blocks and their stop when pressed.


3. Game controls

The Game class combines game logic, state management, adding new blocks, and scoring:

class Game {
  constructor() {
    this.blocks = [];
    this.stage = new Stage();
    this.state = 'READY';
    this.score = 0;
  }

  addBlock() {
    // Adds a new block to the tower
  }

  placeBlock() {
    // Places the current block and checks for game completion
  }

  restartGame() {
    // Resets the game when finished
  }
}

What we do:

  • We process the game states: start, game, end, restart.

  • Manage adding new blocks and updating the scene.

  • We count points for successfully placed blocks.


4. Interaction with the player

The game reacts to user actions: pressing the space bar or clicking the mouse to place blocks:

document.addEventListener('click', () => game.onAction());
document.addEventListener('keydown', (e) => {
  if (e.keyCode === 32) game.onAction(); // Pressing the space bar
});

5. Animations

Using the library GSAP we implement smooth camera movement and block animations:

TweenLite.to(this.camera.position, 0.3, { y: newY });
TweenLite.to(block.position, 1, { x: ... });

What we do:

  • The camera smoothly rises up, following the blocks.

  • Blocks that do not match fly away and disappear.


Where can I find the full code?

Full JavaScript code is available in the application Code or on GitHub project. You will be able to study it in more detail and, if necessary, adapt it to your needs.

Conclusion

Creating a game Tower Blocks Game is a fascinating process that combines work with 3D graphics, animations, and game mechanics. We reviewed the key points of development: scene setup, block management, implementation of interactions, and interface styling.


Where can I play and learn how to create a game?

Play Tower Blocks Game and you can study the code in detail in the application Code. This is a great opportunity not only to enjoy the game, but also to learn how to develop your own projects by studying the example in practice. Also, the full source code is available at GitHub project, where you can download and adapt it to your needs.

Try to create a game yourself, experiment with the settings and improve it — this is the magic of programming! 🚀

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card