Home Web Front-end JS Tutorial Ideas and methods for implementing Tetris game in javascript

Ideas and methods for implementing Tetris game in javascript

May 16, 2016 pm 04:02 PM
javascript

Watch "The Beauty of Programming": "Although programs are difficult to write, they are beautiful. To write programs well, you need to have certain basic knowledge, including programming languages, data structures and algorithms. If you write programs well, It requires rigorous logical thinking skills and a good foundation in programming, as well as familiarity with programming environments and programming tools.”

Have you ever fallen in love with programming after studying computers for several years? In other words, if you haven’t tried to write a game yourself, you don’t really love programming.

The sensation and economic value Tetris has caused can be said to be a major event in the history of games. It seems simple but is endlessly varied and addictive. I believe that most of my classmates were once so obsessed with it that they stopped thinking about food and tea.

Game Rules

1. A flat virtual venue for placing small squares. Its standard size: row width is 10, column height is 20, with each small squares as units.

2. A set of regular graphics composed of 4 small squares. It is called Tetromino in English and commonly known as square in Chinese. There are 7 types of squares, namely S, Z, L, J, I, O and T. Named by the shape of letters.

I: Eliminate up to four layers at a time

J (left and right): Eliminate up to three layers, or eliminate two layers

L: Eliminate up to three layers, or eliminate two layers

O: Eliminate one to two layers

S (left and right): Up to two layers, easy to cause holes

Z (left and right): Up to two layers, easy to cause holes

T: Up to two levels

The blocks will start falling slowly from the top of the area. Players can rotate the block in units of 90 degrees and move the block left and right in units of grids to accelerate the block to fall. When a block moves to the bottom of the area or lands on other blocks and cannot move, it will be fixed there, and new blocks will appear above the area and begin to fall. When a column of horizontal grids in the area is completely filled with squares, the column will disappear and become the player's score. The more columns are deleted at the same time, the score index increases.

Analysis and solution

When each block falls, we can do:

1) Rotate to the appropriate direction

2) Move horizontally to a certain column

3) Drop vertically to the bottom

First, you need to use a two-dimensional array, area[18][10] represents the 18*10 game area . Among them, a value of 0 in the array means empty, and a value of 1 means there are blocks.

There are 7 types of blocks in total, each with 4 directions. Define activeBlock[4]. The value of this array is precalculated before compilation and used directly in the program.

Difficulties

1) Boundary check.

1

2

3

4

5

6

7

8

9

10

11

12

//检查左边界,尝试着朝左边移动一个,看是否合法。

function checkLeftBorder(){

  for(var i=0; i<activeBlock.length; i++){

    if(activeBlock[i].y==0){

      return false;

    }

    if(!isCellValid(activeBlock[i].x, activeBlock[i].y-1)){

      return false;

    }

  }

  return true;

} //同理,需要检测右边界和底边界

Copy after login

2) Rotation requires mathematical logic, a problem of rotating one point 90 degrees relative to another point.
3) The timing and keyboard event monitoring mechanism allows the game to run automatically.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

//开始

function begin(e){

  e.disabled = true;

  status = 1;

  tbl = document.getElementById("area");

  if(!generateBlock()){

    alert("Game over!");

    status = 2;

    return;

  }

  paint();

  timer = setInterval(moveDown,1000);

}

document.onkeydown=keyControl;

Copy after login

Program Process

1) The user clicks Start-> Construct an active graphic and set the timer.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

//当前活动的方块, 它可以左右下移动, 变型。当它触底后, 将会更新area;

var activeBlock;

//生产方块形状, 有7种基本形状。

function generateBlock(){

  activeBlock = null;

  activeBlock = new Array(4);

  //随机产生0-6数组,代表7种形态。

  var t = (Math.floor(Math.random()*20)+1)%7;

  switch(t){

    case 0:{

      activeBlock[0] = {x:0, y:4};

      activeBlock[1] = {x:1, y:4};

      activeBlock[2] = {x:0, y:5};

      activeBlock[3] = {x:1, y:5};

 

      break;

    }

    //省略部分代码..............................

    case 6:{

      activeBlock[0] = {x:0, y:5};

      activeBlock[1] = {x:1, y:4};

      activeBlock[2] = {x:1, y:5};

      activeBlock[3] = {x:1, y:6};

      break;

    }

  }

  //检查刚生产的四个小方格是否可以放在初始化的位置.

  for(var i=0; i<4; i++){

    if(!isCellValid(activeBlock[i].x, activeBlock[i].y)){

        return false;

      }

    }

  return true;

}

Copy after login

2) After each downward movement, check whether it has hit the bottom. If it has hit the bottom, try to eliminate the row.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

//消行

function deleteLine(){

  var lines = 0;

  for(var i=0; i<18; i++){

    var j=0;

    for(; j=0; k--){

        area[k+1] = area[k];

      }

    }

    area[0] = generateBlankLine();

    }

  }

  return lines;

}

Copy after login

3) After finishing, construct an active graphic and set the timer.

To be optimized

1) Set the colors of blocks of different shapes.

Idea: In the create block function, set the activeBlockColor color. The seven different shapes of blocks have different colors (in addition to modifying the generateBlock method, you also need to modify the paintarea method. Because it was not well thought out at the beginning, eliminating a row Finally, redraw the squares while unifying the colors, so you can consider removing n rows of the table, and then adding n rows at the top to ensure the integrity of the squares).

2) When the current block falls, you can check the next block in advance.

Idea: Split the generateBlock method into two parts, one part is used to randomly try the next block, and the other part is used to cache the current block to be drawn. When the current block hits the bottom and is fixed, the next block begins to be drawn, and new blocks are randomly generated again. Repeatedly.

The above is all the content shared with you in this article. I hope you will like it.

【Recommended related tutorials】

1. JavaScript video tutorial
2. JavaScript online manual
3. bootstrap tutorial

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles