Creating a Tetris Game with HTML, CSS and JavaScript

codinglabsolution

 Discover how to develop your very own Tetris game using HTML, CSS, and JavaScript. Dive into game development with our comprehensive tutorial, complete with step-by-step instructions and provided source code.


Creating a Tetris Game with HTML, CSS and JavaScript










Tetris, a timeless classic in the realm of gaming, continues to captivate players worldwide with its simple yet addictive gameplay. In this tutorial, we embark on an exciting journey to recreate this iconic game using the power of web technologies. With HTML for structure, CSS for styling, and JavaScript for interactivity, we'll unravel the secrets behind Tetris and bring it to life in our browser. Join us as we delve into the realms of blocks, lines, and strategic maneuvering to craft our very own version of Tetris. Let's embark on this adventure and shape our digital world one tetromino at a time.


Source Code

Step 1 (HTML Code):



This HTML code sets up the structure for a Tetris game webpage. Let's break it down:


1. `<!DOCTYPE html>`: This declaration specifies the document type and version of HTML being used, which is HTML5 in this case.


2. `<html>`: This element represents the root of an HTML document and contains all other HTML elements.


3. `<head>`: This section contains meta-information about the HTML document, such as the title and links to external resources like CSS files or JavaScript files.


   - `<title>`: This element specifies the title of the document, which appears in the browser's title bar or tab.

   

   - `<link rel="stylesheet" type="text/css" href="styles.css" />`: This line links an external CSS file named "styles.css" to the HTML document. This CSS file is used to style the elements of the Tetris game.


4. `<body>`: This section contains the visible content of the HTML document, including the Tetris game interface.


   - `<div id="tetris">`: This div serves as the main container for the Tetris game. It contains all the game elements.

   

     - `<div id="info">`: This div contains information about the game, such as the next shape, level, lines cleared, score, and time.

     

       - `<div id="next_shape"></div>`: This empty div will display the next shape that will appear in the game.

       

       - `<p id="level">Level: <span></span></p>`: This paragraph element displays the current level of the game.

       

       - `<p id="lines">Lines: <span></span></p>`: This paragraph element displays the number of lines cleared in the game.

       

       - `<p id="score">Score: <span></span></p>`: This paragraph element displays the player's score.

       

       - `<p id="time">Time: <span></span></p>`: This paragraph element displays the elapsed time during the game.

       

       - `<button id="start">Start</button>`: This button allows the player to start the game.

       

       - `<p class="red">Press the Esc button to pause<span></span></p>`: This paragraph element provides instructions to the player, indicating that they can pause the game by pressing the Esc button.

       

     - `<div id="canvas"></div>`: This empty div will serve as the canvas where the Tetris game will be displayed.


   - `<script type="text/javascript" src="script.js"></script>`: This line links an external JavaScript file named "script.js" to the HTML document. This JavaScript file contains the logic and functionality for the Tetris game.


This HTML code provides the basic structure for setting up a Tetris game interface and linking it to external CSS and JavaScript files for styling and functionality.

<!DOCTYPE html> <html lang="en" dir="ltr"><!DOCTYPE html> <html> <head> <title>TETRIS GAMES WITH JAVASCRIPT</title> <link rel="stylesheet" type="text/css" href="styles.css" /> </head> <body> <div id="tetris"> <div id="info"> <div id="next_shape"></div> <p id="level">Level: <span></span></p> <p id="lines">Lines: <span></span></p> <p id="score">Score: <span></span></p> <p id="time">Time: <span></span></p> <button id="start">Start</button> <p class="red">Press the Esc button to pause<span></span></p> </div> <div id="canvas"></div> </div> <script type="text/javascript" src="script.js"></script> </body> </html>

Read Also :Create a Maze Game with JavaScript 


Step 2 (CSS Code):


This CSS code provides styling for the Tetris game interface. Let's break it down:


1. `body`: Styles applied to the entire body of the HTML document.


   - `overflow: hidden;`: Hides any content that exceeds the dimensions of the body element.

   

   - `background: #d7d7d7;`: Sets the background color of the body to a light gray color.


2. `#tetris`: Styles applied to the main container for the Tetris game.


   - `width: 360px;`: Sets the width of the Tetris container to 360 pixels.

   

   - `border: 1px solid black;`: Adds a 1-pixel solid black border around the Tetris container.

   

   - `padding: 20px;`: Adds 20 pixels of padding inside the Tetris container.


3. `#canvas`: Styles applied to the canvas where the Tetris game will be displayed.


   - `width: 200px;`: Sets the width of the canvas to 200 pixels.

   

   - `height: 440px;`: Sets the height of the canvas to 440 pixels.

   

   - `background-color: #000;`: Sets the background color of the canvas to black.

   

   - `position: relative;`: Specifies that the canvas is positioned relative to its normal position.

   

   - `color: #fff;`: Sets the text color inside the canvas to white.


4. `.piece`: Styles applied to the Tetris pieces.


   - `border: 1px solid white;`: Adds a 1-pixel solid white border around each Tetris piece.

   

   - `position: absolute;`: Specifies that the Tetris pieces are positioned relative to the nearest positioned ancestor.


5. `#start`: Styles applied to the start button.


   - `animation: blink .7s steps(2, start) infinite;`: Adds a blinking animation to the start button.

   

   - `background: #E1FF5F;`: Sets the background color of the start button to a light green color.

   

   - `border-radius: 2px;`: Adds a slight border radius to the start button.

   

   - `color: #202020;`: Sets the text color of the start button to a dark gray color.

   

   - `cursor: pointer;`: Changes the cursor to a pointer when hovering over the start button.

   

   - `font-size: 28px;`: Sets the font size of the text inside the start button to 28 pixels.


6. `@keyframes blink`: Defines a blinking animation for the start button.


   - `to`: Specifies the end state of the animation, which adds a solid outline to the start button.


7. `.red`: Styles applied to text with the "red" class.


   - `color: #f00000;`: Sets the text color to red.


8. `.square`: Styles applied to individual squares in the Tetris game grid.


   - `position: absolute;`: Specifies that the squares are positioned relative to the canvas.


   - `width: 19px; height: 19px;`: Sets the width and height of each square to 19 pixels.


   - `border: 1px solid white;`: Adds a 1-pixel solid white border around each square.


9. `.type0`, `.type1`, `.type2`, `.type3`, `.type4`, `.type5`, `.type6`: Styles applied to each type of Tetris piece.


   - `background-color`: Sets the background color of each Tetris piece type.


10. `#next_shape`: Styles applied to the container for displaying the next Tetris shape.


    - `width: 110px; height: 110px;`: Sets the width and height of the container to 110 pixels.


11. `#info`: Styles applied to the information panel displaying game details.


    - `width: 110px; height: 420px;`: Sets the width and height of the information panel.


This CSS code provides the necessary styling to create a visually appealing Tetris game interface.

body { overflow: hidden; background: #d7d7d7; } #tetris { width: 360px; border: 1px solid black; padding: 20px; } #canvas { width: 200px; height: 440px; background-color: #000; position: relative; color: #fff; } #canvas h1 { margin: 0; padding: 0; text-align: center; font-size: 30px; padding-top: 200px; } .piece { border: 1px solid white; position: absolute; } #start{ animation: blink .7s steps(2, start) infinite; background: #E1FF5F; border-radius: 2px; color: #202020; cursor: pointer; font-size: 28px; } @keyframes blink { to { outline: #E1FF5F solid 1px; } } .red{ color: #f00000; } .square { position: absolute; width: 19px; height: 19px; border: 1px solid white; } .type0 { background-color: #a000f0; } .type1 { background-color: #00f0f0; } .type2 { background-color: #f0a000; } .type3 { background-color: #0000f0; } .type4 { background-color: #00f000; } .type5 { background-color: #f00000; } .type6 { background-color: #f0f000; } #next_shape { position: relative; background-color: #000; border: 1px solid white; width: 110px; height: 110px; } #info { background-color: #000; color: #fff; float: right; width: 110px; height: 420px; padding: 10px; }

Step 3 (JavaScript Code):


This JavaScript code initializes a Tetris game using HTML elements and CSS for styling. Let's break it down:


1. **Initialization and Setup**:

   - The code wraps the entire game logic inside an immediately-invoked function expression (IIFE), ensuring that variables and functions defined within it don't pollute the global scope.

   - It initializes various variables and properties needed for the game, including the game board, canvas dimensions, Tetris shapes, current and next shapes, score, level, time, and game speed.

   - Event listeners are set up to handle keypresses and the start button click.


2. **Game Logic**:

   - The `init()` function initializes the game by setting up the game board, info display, level scores, and shapes. It then binds key events and starts the game loop.

   - Functions like `initBoard()`, `initInfo()`, `initShapes()`, and `initNextShape()` set up the initial game state and display.

   - The `play()` function controls the game loop, moving the current Tetris piece downwards automatically at regular intervals.

   - Key event handling functions like `handleKey()` and `whichKey()` manage player input for moving and rotating Tetris pieces.

   - Functions like `move()`, `rotate()`, and `checkMove()` handle the movement, rotation, and collision detection of Tetris pieces.

   - The game tracks and updates the score, level, and lines cleared.

   - Functions like `checkRows()` and `removeRow()` handle clearing filled rows.


3. **Helper Functions**:

   - Helper functions like `createSquare()`, `drawNextShape()`, and `removeBlock()` assist in creating and manipulating Tetris shapes and game elements.

   - Array prototype extension functions like `eachdo()` and `remDup()` are defined to iterate over arrays and remove duplicates.


4. **Event Handling**:

   - Event listeners are set up to handle keypresses and the start button click.

   - The start button click event triggers the game initialization if the game is not already started.


5. **Compatibility Checks**:

   - The code includes checks for browser compatibility using functions like `isIE()`, `isFirefox()`, and `isSafari()`.


Overall, this code sets up the foundation for a Tetris game with basic functionalities like piece movement, rotation, collision detection, scoring, and level progression.


(function () {
  var isStart = false;
  var tetris = {
    board: [],
    boardDiv: null,
    canvas: null,
    pSize: 20,
    canvasHeight: 440,
    canvasWidth: 200,
    boardHeight: 0,
    boardWidth: 0,
    spawnX: 4,
    spawnY: 1,
    shapes: [
      [
        [-1, 1],
        [0, 1],
        [1, 1],
        [0, 0], //TEE
      ],
      [
        [-1, 0],
        [0, 0],
        [1, 0],
        [2, 0], //line
      ],
      [
        [-1, -1],
        [-1, 0],
        [0, 0],
        [1, 0], //L EL
      ],
      [
        [1, -1],
        [-1, 0],
        [0, 0],
        [1, 0], //R EL
      ],
      [
        [0, -1],
        [1, -1],
        [-1, 0],
        [0, 0], // R ess
      ],
      [
        [-1, -1],
        [0, -1],
        [0, 0],
        [1, 0], //L ess
      ],
      [
        [0, -1],
        [1, -1],
        [0, 0],
        [1, 0], //square
      ],
    ],
    tempShapes: null,
    curShape: null,
    curShapeIndex: null,
    curX: 0,
    curY: 0,
    curSqs: [],
    nextShape: null,
    nextShapeDisplay: null,
    nextShapeIndex: null,
    sqs: [],
    score: 0,
    scoreDisplay: null,
    level: 1,
    levelDisplay: null,
    numLevels: 10,
    time: 0,
    maxTime: 1000,
    timeDisplay: null,
    isActive: 0,
    curComplete: false,
    timer: null,
    sTimer: null,
    speed: 700,
    lines: 0,

    init: function () {
      isStart = true;
      this.canvas = document.getElementById('canvas');
      this.initBoard();
      this.initInfo();
      this.initLevelScores();
      this.initShapes();
      this.bindKeyEvents();
      this.play();
    },
    initBoard: function () {
      this.boardHeight = this.canvasHeight / this.pSize;
      this.boardWidth = this.canvasWidth / this.pSize;
      var s = this.boardHeight * this.boardWidth;
      for (var i = 0; i < s; i++) {
        this.board.push(0);
      }
      //this.boardDiv = document.getElementById('board); //for debugging
    },
    initInfo: function () {
      this.nextShapeDisplay = document.getElementById('next_shape');
      this.levelDisplay = document
        .getElementById('level')
        .getElementsByTagName('span')[0];
      this.timeDisplay = document
        .getElementById('time')
        .getElementsByTagName('span')[0];
      this.scoreDisplay = document
        .getElementById('score')
        .getElementsByTagName('span')[0];
      this.linesDisplay = document
        .getElementById('lines')
        .getElementsByTagName('span')[0];
      this.setInfo('time');
      this.setInfo('score');
      this.setInfo('level');
      this.setInfo('lines');
    },
    initShapes: function () {
      this.curSqs = [];
      this.curComplete = false;
      this.shiftTempShapes();
      this.curShapeIndex = this.tempShapes[0];
      this.curShape = this.shapes[this.curShapeIndex];
      this.initNextShape();
      this.setCurCoords(this.spawnX, this.spawnY);
      this.drawShape(this.curX, this.curY, this.curShape);
    },
    initNextShape: function () {
      if (typeof this.tempShapes[1] === 'undefined') {
        this.initTempShapes();
      }
      try {
        this.nextShapeIndex = this.tempShapes[1];
        this.nextShape = this.shapes[this.nextShapeIndex];
        this.drawNextShape();
      } catch (e) {
        throw new Error('Could not create next shape. ' + e);
      }
    },
    initTempShapes: function () {
      this.tempShapes = [];
      for (var i = 0; i < this.shapes.length; i++) {
        this.tempShapes.push(i);
      }
      var k = this.tempShapes.length;
      while (--k) {
        //Fisher Yates Shuffle
        var j = Math.floor(Math.random() * (k + 1));
        var tempk = this.tempShapes[k];
        var tempj = this.tempShapes[j];
        this.tempShapes[k] = tempj;
        this.tempShapes[j] = tempk;
      }
    },
    shiftTempShapes: function () {
      try {
        if (
          typeof this.tempShapes === 'undefined' ||
          this.tempShapes === null
        ) {
          this.initTempShapes();
        } else {
          this.tempShapes.shift();
        }
      } catch (e) {
        throw new Error('Could not shift or init tempShapes: ' + e);
      }
    },
    initTimer: function () {
      var me = this;
      var tLoop = function () {
        me.incTime();
        me.timer = setTimeout(tLoop, 2000);
      };
      this.timer = setTimeout(tLoop, 2000);
    },
    initLevelScores: function () {
      var c = 1;
      for (var i = 1; i <= this.numLevels; i++) {
        this['level' + i] = [c * 1000, 40 * i, 5 * i]; //for nxt level, row score, p sore,
        c = c + c;
      }
    },
    setInfo: function (el) {
      this[el + 'Display'].innerHTML = this[el];
    },
    drawNextShape: function () {
      var ns = [];
      for (var i = 0; i < this.nextShape.length; i++) {
        ns[i] = this.createSquare(
          this.nextShape[i][0] + 2,
          this.nextShape[i][1] + 2,
          this.nextShapeIndex
        );
      }
      this.nextShapeDisplay.innerHTML = '';
      for (var k = 0; k < ns.length; k++) {
        this.nextShapeDisplay.appendChild(ns[k]);
      }
    },
    drawShape: function (x, y, p) {
      for (var i = 0; i < p.length; i++) {
        var newX = p[i][0] + x;
        var newY = p[i][1] + y;
        this.curSqs[i] = this.createSquare(newX, newY, this.curShapeIndex);
      }
      for (var k = 0; k < this.curSqs.length; k++) {
        this.canvas.appendChild(this.curSqs[k]);
      }
    },
    createSquare: function (x, y, type) {
      var el = document.createElement('div');
      el.className = 'square type' + type;
      el.style.left = x * this.pSize + 'px';
      el.style.top = y * this.pSize + 'px';
      return el;
    },
    removeCur: function () {
      var me = this;
      this.curSqs.eachdo(function () {
        me.canvas.removeChild(this);
      });
      this.curSqs = [];
    },
    setCurCoords: function (x, y) {
      this.curX = x;
      this.curY = y;
    },
    bindKeyEvents: function () {
      var me = this;
      var event = 'keypress';
      if (this.isSafari() || this.isIE()) {
        event = 'keydown';
      }
      var cb = function (e) {
        me.handleKey(e);
      };
      if (window.addEventListener) {
        document.addEventListener(event, cb, false);
      } else {
        document.attachEvent('on' + event, cb);
      }
    },
    handleKey: function (e) {
      var c = this.whichKey(e);
      var dir = '';
      switch (c) {
        case 37:
          this.move('L');
          break;
        case 38:
          this.move('RT');
          break;
        case 39:
          this.move('R');
          break;
        case 40:
          this.move('D');
          break;
        case 27: //esc: pause
          this.togglePause();
          break;
        default:
          break;
      }
    },
    whichKey: function (e) {
      var c;
      if (window.event) {
        c = window.event.keyCode;
      } else if (e) {
        c = e.keyCode;
      }
      return c;
    },
    incTime: function () {
      this.time++;
      this.setInfo('time');
    },
    incScore: function (amount) {
      this.score = this.score + amount;
      this.setInfo('score');
    },
    incLevel: function () {
      this.level++;
      this.speed = this.speed - 75;
      this.setInfo('level');
    },
    incLines: function (num) {
      this.lines += num;
      this.setInfo('lines');
    },
    calcScore: function (args) {
      var lines = args.lines || 0;
      var shape = args.shape || false;
      var speed = args.speed || 0;
      var score = 0;

      if (lines > 0) {
        score += lines * this['level' + this.level][1];
        this.incLines(lines);
      }
      if (shape === true) {
        score += shape * this['level' + this.level][2];
      }
      /*if (speed > 0){ score += speed * this["level" +this .level[3]];}*/
      this.incScore(score);
    },
    checkScore: function () {
      if (this.score >= this['level' + this.level][0]) {
        this.incLevel();
      }
    },
    gameOver: function () {
      this.clearTimers();
      isStart = false;
      this.canvas.innerHTML = '<h1>GAME OVER</h1>';
    },
    play: function () {
      var me = this;
      if (this.timer === null) {
        this.initTimer();
      }
      var gameLoop = function () {
        me.move('D');
        if (me.curComplete) {
          me.markBoardShape(me.curX, me.curY, me.curShape);
          me.curSqs.eachdo(function () {
            me.sqs.push(this);
          });
          me.calcScore({ shape: true });
          me.checkRows();
          me.checkScore();
          me.initShapes();
          me.play();
        } else {
          me.pTimer = setTimeout(gameLoop, me.speed);
        }
      };
      this.pTimer = setTimeout(gameLoop, me.speed);
      this.isActive = 1;
    },
    togglePause: function () {
      if (this.isActive === 1) {
        this.clearTimers();
        this.isActive = 0;
      } else {
        this.play();
      }
    },
    clearTimers: function () {
      clearTimeout(this.timer);
      clearTimeout(this.pTimer);
      this.timer = null;
      this.pTimer = null;
    },
    move: function (dir) {
      var s = '';
      var me = this;
      var tempX = this.curX;
      var tempY = this.curY;
      switch (dir) {
        case 'L':
          s = 'left';
          tempX -= 1;
          break;
        case 'R':
          s = 'left';
          tempX += 1;
          break;
        case 'D':
          s = 'top';
          tempY += 1;
          break;
        case 'RT':
          this.rotate();
          return true;
          break;
        default:
          throw new Error('wtf');
          break;
      }
      if (this.checkMove(tempX, tempY, this.curShape)) {
        this.curSqs.eachdo(function (i) {
          var l = parseInt(this.style[s], 10);
          dir === 'L' ? (l -= me.pSize) : (l += me.pSize);
          this.style[s] = l + 'px';
        });
        this.curX = tempX;
        this.curY = tempY;
      } else if (dir === 'D') {
        if (this.curY === 1 || this.time === this.maxTime) {
          this.gameOver();
          return false;
        }
        this.curComplete = true;
      }
    },
    rotate: function () {
      if (this.curShapeIndex !== 6) {
        //square
        var temp = [];
        this.curShape.eachdo(function () {
          temp.push([this[1] * -1, this[0]]);
        });
        if (this.checkMove(this.curX, this.curY, temp)) {
          this.curShape = temp;
          this.removeCur();
          this.drawShape(this.curX, this.curY, this.curShape);
        } else {
          throw new Error('Could not rotate!');
        }
      }
    },
    checkMove: function (x, y, p) {
      if (this.isOB(x, y, p) || this.isCollision(x, y, p)) {
        return false;
      }
      return true;
    },
    isCollision: function (x, y, p) {
      var me = this;
      var bool = false;
      p.eachdo(function () {
        var newX = this[0] + x;
        var newY = this[1] + y;
        if (me.boardPos(newX, newY) === 1) {
          bool = true;
        }
      });
      return bool;
    },
    isOB: function (x, y, p) {
      var w = this.boardWidth - 1;
      var h = this.boardHeight - 1;
      var bool = false;
      p.eachdo(function () {
        var newX = this[0] + x;
        var newY = this[1] + y;
        if (newX < 0 || newX > w || newY < 0 || newY > h) {
          bool = true;
        }
      });
      return bool;
    },
    getRowState: function (y) {
      var c = 0;
      for (var x = 0; x < this.boardWidth; x++) {
        if (this.boardPos(x, y) === 1) {
          c = c + 1;
        }
      }
      if (c === 0) {
        return 'E';
      }
      if (c === this.boardWidth) {
        return 'F';
      }
      return 'U';
    },
    checkRows: function () {
      var me = this;
      var start = this.boardHeight;
      this.curShape.eachdo(function () {
        var n = this[1] + me.curY;
        console.log(n);
        if (n < start) {
          start = n;
        }
      });
      console.log(start);

      var c = 0;
      var stopCheck = false;
      for (var y = this.boardHeight - 1; y >= 0; y--) {
        switch (this.getRowState(y)) {
          case 'F':
            this.removeRow(y);
            c++;
            break;
          case 'E':
            if (c === 0) {
              stopCheck = true;
            }
            break;
          case 'U':
            if (c > 0) {
              this.shiftRow(y, c);
            }
            break;
          default:
            break;
        }
        if (stopCheck === true) {
          break;
        }
      }
      if (c > 0) {
        this.calcScore({ lines: c });
      }
    },
    shiftRow: function (y, amount) {
      var me = this;
      for (var x = 0; x < this.boardWidth; x++) {
        this.sqs.eachdo(function () {
          if (me.isAt(x, y, this)) {
            me.setBlock(x, y + amount, this);
          }
        });
      }
      me.emptyBoardRow(y);
    },
    emptyBoardRow: function (y) {
      for (var x = 0; x < this.boardWidth; x++) {
        this.markBoardAt(x, y, 0);
      }
    },
    removeRow: function (y) {
      for (var x = 0; x < this.boardWidth; x++) {
        this.removeBlock(x, y);
      }
    },
    removeBlock: function (x, y) {
      var me = this;
      this.markBoardAt(x, y, 0);
      this.sqs.eachdo(function (i) {
        if (me.getPos(this)[0] === x && me.getPos(this)[1] === y) {
          me.canvas.removeChild(this);
          me.sqs.splice(i, 1);
        }
      });
    },
    setBlock: function (x, y, block) {
      this.markBoardAt(x, y, 1);
      var newX = x * this.pSize;
      var newY = y * this.pSize;
      block.style.left = newX + 'px';
      block.style.top = newY + 'px';
    },
    isAt: function (x, y, block) {
      if (this.getPos(block)[0] === x && this.getPos(block)[1] === y) {
        return true;
      }
      return false;
    },
    getPos: function (block) {
      var p = [];
      p.push(parseInt(block.style.left, 10) / this.pSize);
      p.push(parseInt(block.style.top, 10) / this.pSize);
      return p;
    },
    getBoardIdx: function (x, y) {
      return x + y * this.boardWidth;
    },
    boardPos: function (x, y) {
      return this.board[x + y * this.boardWidth];
    },
    markBoardAt: function (x, y, val) {
      this.board[this.getBoardIdx(x, y)] = val;
    },
    markBoardShape: function (x, y, p) {
      var me = this;
      p.eachdo(function (i) {
        var newX = p[i][0] + x;
        var newY = p[i][1] + y;
        me.markBoardAt(newX, newY, 1);
      });
    },
    isIE: function () {
      return this.bTest(/IE/);
    },
    isFirefox: function () {
      return this.bTest(/Firefox/);
    },
    isSafari: function () {
      return this.bTest(/Safari/);
    },
    bTest: function (rgx) {
      return rgx.test(navigator.userAgent);
    },
  };
  const btn = document.querySelector('#start');
  btn.addEventListener('click', function () {
    btn.style.display = 'none';
    if (!isStart) {
      tetris.init();
    }
  });
})();

if (!Array.prototype.eachdo) {
  Array.prototype.eachdo = function (fn) {
    for (var i = 0; i < this.length; i++) {
      fn.call(this[i], i);
    }
  };
}
if (!Array.prototype.remDup) {
  Array.prototype.remDup = function () {
    var temp = [];
    for (var i = 0; i < this.length; i++) {
      var bool = true;
      for (var j = i + 1; j < this.length; j++) {
        if (this[i] === this[j]) {
          bool = false;
        }
      }
      if (bool === true) {
        temp.push(this[i]);
      }
    }
    return temp;
  };
}

Final Output:


Creating a Tetris Game with HTML, CSS and JavaScript



Source Code : Download files

Conclusion:


In conclusion, we've successfully implemented a Tetris game using HTML, CSS, and JavaScript. By combining the power of these web technologies, we've created an interactive and engaging gaming experience.


Throughout the implementation, we've covered various aspects of game development, including setting up the game board, managing Tetris shapes, handling player input for movement and rotation, detecting collisions, scoring points, and clearing filled rows.


Additionally, we've ensured cross-browser compatibility and provided a user-friendly interface with intuitive controls.


By leveraging the capabilities of HTML for structure, CSS for styling, and JavaScript for dynamic behavior, we've demonstrated the versatility and flexibility of web development in creating fun and entertaining games.


With further enhancements and refinements, this Tetris game can be expanded to include additional features, such as multiplayer support, customizable themes, and leaderboard integration, offering endless possibilities for creativity and innovation in web-based gaming.


Tags: #JavaScript #GameDevelopment #WebDevelopment #Tetris #HTML #CSS #SourceCode

إرسال تعليق

ملفات تعريف الارتباط
نستخدم ملفات تعريف الارتباط (Cookies) لفهم كيفية استخدامك لموقعنا وتحسين تجربتك في المحتوى والإعلانات. باستمرارك في تصفح الموقع، فإنك توافق على استخدامنا لملفات تعريف الارتباط وفقًا لسياسة الخصوصية لدينا.
أُووبس!
يبدو أن هناك خطأ ما في اتصالك بالإنترنت. يرجى الاتصال بالإنترنت وبدء التصفح مرة أخرى.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.