Using JS to achieve 2048 small games
Note Warehouse: https://github.com/nnngu/LearningNotes
1. Introduction to the game
2048 is a casual puzzle series of digital overlay games. (source code and presentation address are given at the end of the article)
2. Game Play Method
In the 4*4 16, you can select the top, bottom, left, and right four directions, the numbers will move in the direction, the next two numbers will be merged to form a larger number, each move or merge will automatically add a number.
The game ends when there are no empty squares in the 16 palace and the four directions are not working.
3, the purpose of the game
The goal is to merge the number 2048 to get a higher score.
4. Games
5, the Game Realization Principle (1) First of all, the 16 palace as a matrix form
(2) Add class names and attributes to each grid in HTML to record the location of each lattice
Note: The class name is the class name of each lattice, the class name of the item
emptyItem
empty lattice, and the nonEmptyItem
class name of the non-empty lattice.
(3) When the game starts, randomly generates two digits, 2 or 4, appearing anywhere in the matrix.
This is done in part by emptyItem
the name of nonEmptyItem
the class.
Steps:
① randomly generates a number 2 or 4
② Get all empty elements (class name emptyItem
)
③ randomly selects an empty element, fills the resulting number into an empty element, and removes the class name, emptyItem
adding the class name nonEmptyItem
, the non-empty element
④ repeats ①, ②, ③, and then randomly generates a number to fill the random position.
(4) The core of the game is mobile
The movement has four directions: top, bottom, left, and right. The following ideas are implemented:
如果触发向左移动 遍历所有非空元素 如果当前元素在第一个位置 不动 如果当前元素不在第一个位置 如果当前元素左侧是空元素 向左移动 如果当前元素左侧是非空元素 如果左侧元素和当前元素的内容不同 不动 如果左侧元素和当前元素的内容相同 向左合并 如果触发向右移动 遍历所有非空元素 如果当前元素在最后一个位置 不动 如果当前元素不在最后一个位置 如果当前元素右侧是空元素 向右移动 如果当前元素右侧是非空元素 如果右侧元素和当前元素的内容不同 不动 如果右侧元素和当前元素的内容相同 向右合并
Move up and move down the idea ibid.
(5) Determine if the game is over
获取所有元素获取所有非空元素如果所有元素的个数 == 所有非空元素的个数 循环遍历所有非空元素 上面元素存在 && (当前元素的内容 == 上面元素的内容) return 下面元素存在 && (当前元素的内容 == 下面元素的内容) return 左边元素存在 && (当前元素的内容 == 左边元素的内容) return 右边元素存在 && (当前元素的内容 == 右边元素的内容)
Source code: https://github.com/nnngu/js_game_2048
Demo Address: https://nnngu.github.io/js_game_2048/index.html
Using JS to achieve 2048 small games