Tetris Là Gì – Game Super Tetris

Home » Let’s try to write a complete puzzle game (Tetris) from scratch (Part 1: Interface and game loop)

Surely all of us know and have tried ittetris (tetris)yes, but it’s not a “jigsaw puzzle” like you think. Tetris is a very simple game made by our Soviet friends from the 80s, accompanied by indispensable music of the legendary Red Army.Korobeiniki.

Watching: What is Tetris

Although so simple and old, Tetris has great charm and addiction (the original author of the game also said that while developing the game, heI was so busy playing this game that I forgot to complete itnote the code snippets!).Tetris Effect Syndromefamous also refers to the state of players playing a game (like Tetris) so much, that they see falling blocks everywhere, even in dreams.

Today, I will be with youmake a complete Tetris game from AZ, no bugs, most functional. In this post, I would like to chooseJavascript languagefor the convenience of demo right in the browser. However, after reading this article, you can absolutely afford to do it withany languageany other object oriented.

About Tetris

You probably already know or have played Tetris game many times already. But just to be sure, I would like to remind you a little bit about the principle of this game:

Game Board

Also known as “playfield”, or “matrix”,… Kind of like the grid layout, and the main place to play your game. On the screen when playing the game, you will see the game board is 20 rows x 10 columns wide. However, do you know the fact that in Tetris games, the board game has a real height of 22 up to 40 cells (ie 40 rows x 10 columns), and the upper cells from the 20th from the bottom up are actually blocked. hidden from the screen? In this post, I will usegame board 23 x 10″ widewithTop 3 rows are hiddenfrom the game interface.

**

Please try to guess why I left the top 3 rows left over.

Tetromino

These are monstrous shapes falling from the sky. There are 7 types in all: L, J, O, T, S, Z, and I blocks. Each type of block has a different corresponding color.

**

These blocks can all be rotated (clockwise) as well as moved (left or right). However, the block will not be able to rotate or move if it encounters a collision (with the edge or with the landed blocks).

Game ticks

After the same short amount of time (usually set from 0.5 to 1 second), the current Tetromino block will drop one more tile. After falling to the bottom (hit the ground or other landed blocks), the current block will be reattached, and another new block will fall.

Eat points

When a row is “completed”, or filled with blocks, you will earn points. The more rows completed at once, the more points you get, up to 4 rows with I-blocks.

The completed rows are then removed from the table, along with causing the blocks above it to drop down.

Game over

The game ends when the number of fallen blocks has piled up to the point where it touches the top edge of the board, and new blocks can no longer fall.

Xem thêm bài viết hay:  Công trình riêng lẻ là gì? Được phân cấp ra sao?

The outline as above is also quite detailed, now let’s get to work.

Conduct

Project Initialization

Create folders and files like this:

tetris-html/├── index.html└── main.jsInitialize fileindex.html:

Step 1: Build the basic interface for the game

With a simple game like Tetris, we can choose to build the game interface with HTML and CSS (based on the DOM), or use HTML5 Canvas. In this article, I will try to build a game using HTML5 Canvas.

See also: August White Cinnamon Orchid And Things To Know, Scc Vietnam

Our goal will be to build an interface that looks like this:

***

As another example, let’s try to draw a rectangle with a red border:

ctx.strokeStyle = “rgb(255, 0, 0)”ctx.rect(10, 20, 50, 100)ctx.stroke() You will immediately have a rectangle without fill but with red border, set at coordinates x = 70, y = 20, 50px wide and 100px high.

**

Writing text on canvas is also very simple. Similar to the two examples above, this text is written in black, 14px in size, placed at coordinates x = 10, y = 140:

ctx.fillStyle = “black”ctx.font = “14px”;ctx.fillText(“HAPPY NEW YEAR”, 10, 140)

**

Demo as below, click on the Result tab.

Apply to the lesson

First of all, for the game to work, we need some variables to store the state of the game over time. For example the following:

boardWidth,boardHeight is the width and height of the game board.currentTetromino holds the current Tetromino block object currentBoard helps to save the current state of the game board.currentBoard is a 2-dimensional array that stores integer elements, with all elements being zero (ie not yet). any block is placed on). Although javascript does not have a 2-dimensional array concept, we can simulate it by defining a sub-array inside an array.landedBoard is similar to currentBoard. But instead of storing both information about the falling block and the “landed” blocks like currentBoard, the landedBoard only stores information about the “landed” blocks. Maybe say currentBoard=landedBoard+currentTetromino.score to save the current score.

We will go into more depth about these properties later in the article.

I will use the ES6 class syntax to define a Game class:

class Game { constructor() { this.score = 0 this.boardWidth = 10 this.boardHeight = 23 this.currentBoard = new Array(this.boardHeight).fill(0).map(() => new Array(this. boardWidth.fill(0)) this.landedBoard = new Array(this.boardHeight).fill(0).map(() => new Array(this.boardWidth).fill(0)) this.currentTetromino = null / * TODO */ } /* TODO */} In this section, we add a tag, where we will draw the game graphics:

canvas width=”420″ height=”600″>canvas>Getcontextof that element:

class Game { constructor() { /* … */ this.canvas = document.getElementById(“tetris-canvas”) this.ctx = this.canvas.getContext(“2d”) }Add a draw() method to classGame. In this method, we need to do 3 things:

Draw the outer frame, which is a rectangle with only border color. Draw each small block square in the form of a 20×10 grid, fill it with light white. We need 2 nested for loops to do this. Add some more text.

class Game { /* … */ draw(blockSize = 24, padding = 4) { /* Draw the board frame */ this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.ctx.lineWidth = 2 this.ctx.rect(padding, padding, blockSize*this.boardWidth+padding*(this.boardWidth+1), blockSize*(this.boardHeight-3)+padding*(this.boardHeight- 3+1)) this.ctx.stroke() /* Loop through the elements of the board array and draw blocks at the correct positions */ for (let i = 3; i this.boardHeight; i++) { for (let j = 0; j this.boardWidth; j++) { if (this.currentBoard > 0) { this.ctx.fillStyle = “rgb(0, 0, 0)” } else { this.ctx.fillStyle = “rgb(248, 248, 248)” } this.ctx.fillRect(padding*2+ j*(blockSize+padding), padding*2+(i-3)*(blockSize+padding), blockSize, blockSize) } } /* Write out the text */ this.ctx.fillStyle = “rgb(0, 0, 0)” this.ctx.font = “28px”; this.ctx.fillText(“NEXT:”, 300, 28) this.ctx.fillText(“Score:”, 300, 200) this.ctx.fillText(this.score.toString(), 300, 230) }}Ask: Why does the repeated value i start at 3?

Xem thêm bài viết hay:  Quản lý là gì? Vai trò của nhiệm vụ của nhà quản lý thế nào?

Answer: Since we need to leave the top 3 of the board, don’t show the game interface.

Ask: What is that mess of adding, subtracting, multiplying and dividing?
!

Answer: It is a calculation to calculate the position of small cells (blocks), so that they are evenly spaced and have the most reasonable padding between them. You can rest assured because now that I re-read the last paragraph, I don’t understand anything

***

As in the previous section, we used the currentBoard property as a2-dimensional arraysto describe our game board. The elements of this array will beintegersrepresenting the corresponding small cells (blocks) in the board:

Number 0: There are no blocks hereNumber 1: Block belongs to an L-block Number 2: Block belongs to a J-block Number 3: Block belongs to an OS-block Number 4: Block belongs to an alpha-block Digit 5: Block belongs to an S-block : Block belongs to a block of letters ZNumber 7: Block belongs to a block of letters I

To describe the shape of Tetromino blocks, I will also use 2-dimensional arrays, for example with a vertical L-block:

/* Vertical L block */, , >Yes but in Tetris the player canrotate Tetrominoare falling at various angles (clockwise): 0, 90, 180 and 270 degrees. If you want, you can make a method to “rotate” the above array and return the rotated array using a little algorithm. However, for the sake of simplicity, here we will define all rotations of the Tetrominos. For example with Tetromino letter L as follows:

row,col: position in rows and columns.angle: current rotation direction, which are the numbers 0, 1, 2, 3 (corresponding to the angles 0, 90, 180, 270 degrees).width,height: dimension length and width.move(): move left right.fall(): move down.rotate(): rotate…

To summarize, we have classes that define Tetrominos as follows:

Step 3: Make the Tetromino block fall!

Randomly get Tetromino block

First of all, I will create a method to randomly get 1 out of 7 Tetromino block types. When creating a new Game, I also randomly take a Tetromino block attached to the currentTetromino.

class Game { constructor() { /* … */ this.currentTetromino = this.randomTetromino() /* … */ } randomTetromino() { const randNum = Math.floor(Math.random() * Math.floor(7) ) switch (randNum) { case 0: return new LShape(1, 4) case 1: return new JShape(1, 4) case 2: return new OSShape(2, 4) case 3: return new TShape(2, 4) case 4: return new SShape(2, 4) case 5: return new ZShape(2, 4) case 6: return new IShape(0, 4) } } /* … */} However, sometimes RNGs are a bit weird Publicly, if you have poor character, you will probably randomize the entire S or Z block in a row, while the I block will never be found, which is quite inhibiting.Afterwe’ll find a wayimproved random mechanicsof the game to play the best (hint: we will create a mechanismrandom 7-bag).

Game Loop

You’re probably familiar with the command line (consoleniceterminal) on operating systems already? While waiting for the user to enter the command, the command line will display a cursor waiting for user input. If you type ls -l and pressenter, the command line window will show the files and folders in your current directory. After returning the result, the command line window returns to the apostrophe state, waiting for you to enter the next command. If you do not enter anything, the command line will alsodo nothing.

Xem thêm bài viết hay:  Quy hoạch là gì? Quy định ở đâu?

But video games are different. If the game is running, then even if you don’t control anything,the game will still runas usual. The wind will still blow, the clouds will still fly, the birds will still sing, the day will gradually turn to night, the NPCs will still walk on the street and the enemies will still rush to beat you, etc. More specifically, in the game Tetris, even if you No input input, Tetromino block on the screen stillwill gradually decrease, forcing you to soon find a suitable place to place this Tetromino block. This is the basic understanding ofgame loop.

In this lesson, I will temporarily set the time every time a Tetromino block falls on a tile to be0.8 seconds. To do this, in this article I will simply use setInterval.setInterval which allows us to perform logic and draw the canvas at regular intervals.approximately0.8 seconds. Note that, becauseevent loopof Javascript and also the thread scheduling of the operating systemsetInterval will definitely be latefrom little delay to very long delay, depending on the speed of the computer and the number of tasks to be processed. However, for games where the time between loops is long like Tetris, using setInterval is enough.

See also: Flowers for the Opening of the Store, Beautiful Company, 179 Flowers for the Opening (Beautiful)

For every 0.8 seconds, we need to do 3 things:

Run the progress() method to calculate the next state of the game. Update the currentBoard table with updateCurrentBoard(). This method will combine the LandedBoard and the currentTetromin into the currentBoard. Like I said, currentBoard=landedBoard+currentTetrominhé. Draw the new state of the game with draw().

class Game { /* … */ play() { setInterval(() => { this.progress() this.updateCurrentBoard() this.draw() }, 800); } progress() { /* TODO */ this.currentTetromino.fall() } updateCurrentBoard() { for (let i = 0; i this.boardHeight; i++) { for (let j = 0; j this.boardWidth; j++ ) { this.currentBoard = this.landedBoard } } for (let i = 0; i this.currentTetromino.height; i++) { for (let j = 0; j this.currentTetromino.width; j++) { if (this.currentTetromino.shape > 0) { this.currentBoard = this.currentTetromino.shape } } } }}document.addEventListener(“DOMContentLoaded”, () => { const game = new Game() game.updateCurrentBoard() game.draw() game.play()})You get a Tetromino block as a result moving from top to bottom:

Bạn thấy bài viết Tetris Là Gì – Game Super Tetris có khắc phục đươc vấn đề bạn tìm hiểu ko?, nếu ko hãy comment góp ý thêm về Tetris Là Gì – Game Super Tetris bên dưới để Trường Cao đẳng Nghề Khách sạn Du lịch Quốc tế IMPERIAL có thể thay đổi & cải thiện nội dung tốt hơn cho các bạn nhé! Cám ơn bạn đã ghé thăm Website: imperialhotelschool.edu.vn của Trường Cao đẳng Nghề Khách sạn Du lịch Quốc tế IMPERIAL

Nhớ để nguồn: Tetris Là Gì – Game Super Tetris của website imperialhotelschool.edu.vn

Chuyên mục: Là gì?

Viết một bình luận