First, let's talk about the functions to be implemented.
- Generate a level based on certain rules
- Logic such as elimination
- Game end Detection
- Locally cache game progress
Preparations
Build a project and use the editor to create a game scenario. The scenarios I set up are as follows:
Simple Description:
- New SpriteIs the background image in the scenario
- StarrootIt is an empty node, and the star blocks created later will be added to this node.
- ActionrootIt is the parent node of some animation nodes, such as the comb special effect on this node.
- UirootThat is, the root node on the user interface, such as the highest score, current score, and current level of the game, are all placed on this node.
- ResultrootIs the root node of the settlement interface. The node is grayed out because it is not activated.
- SoundctlIt is also an empty node. It is mainly used to mount a script on the node to process the game sound.
Make Star preparations
For more information, see the official documentation.
The root node has only one Genie node. Blue indicates a premade image. Let's talk about it.StarScript component onStarctr. js
Because there are more than one stars, you need to changeNew Sprite. Stars have the following attributes:
properties: { _starType: 0, _gx: 0, _gy: 0, starSprite: cc.Sprite, starSpriteFrames: { default: [], type: cc.SpriteFrame, },},
Corresponding to starspriteNew SpriteThe sprite component; starspriteframes stores the textures of all the stars; _ startype indicates the category of the stars, which determines which texture starsprite displays in starspriteframes; _ Gx and _ Gy are used to store the grid coordinates of the star blocks in the 10x10 map.
initStar (type, gx, gy) { this._starType = type; this.starSprite.spriteFrame = this.starSpriteFrames[this._starType]; this.updateGrid(gx, gy);},updateGrid (gx, gy) { this._gx = gx; this._gy = gy;},
The initialization function of the initstar. updategrid is used to update the Coordinate Position of the stars.
An operation is also performed in the pre-made process to process users' click operations. Therefore, the start function of the script listens to the touch. Start is the callback function of the life cycle of the component script. It is triggered before the first activation of the component, that is, before the first update execution.
Start () {This. node. On (CC. node. eventtype. touch_start, function (event) {// todo: Touch processing}, this );},
The specific touch processing is described later. Finally, let's take a look at the script components in the property Checker:
Generate level data
- Generation rules: Stars are randomly generated for each grid. (A simple logic rule is selected here. You can modify the logic generated by the stars based on the actual situation)
- Store 10x10 map data using a two-dimensional array
The following describes two objects and create two scripts respectively.Gamedata. js and utils. js
Gamedata processes game data, such as game scores, the current level, and map data.
// Gamedata. jsvar level = 0; // record the current Level VAR targetscore = 0; // The current level target score var currscore = 0; // The current score var bestscore = 0; // The highest historical score var starmatrix = NULL; // map data, two-dimensional array var starsprite = []; // One-dimensional array stores the nodemodule of the stars. exports = {level: Level, targetscore: targetscore, currscore: currscore, bestscore: bestscore, starmatrix: starmatrix, starsprite: starsprite ,};
Utils is mainly used to process some common logic, such as the logic of level generation rules.
// Utils. jsvar Config = require ("psconfig"); var randomcolorbyarray = function (array) {var I = math. floor (math. random () * array. length); Return array [I];} // random generation of the star Level Logic Function initmatrixdataportraitrandom () {var matrixdata = new array (config. matrixrow); For (var row = 0; row <config. matrixrow; row ++) {matrixdata [row] = new array (config. matrixcol); For (VAR Col = 0; Col <config. matrixcol; Col ++) {matrixdata [row] [col] = randomcolorbyarray (config. totalcolors) ;}} return matrixdata ;}; module. exports = {initmatrixdataportraitrandom: initmatrixdataportraitrandom ,};
Script utils. js loads another scriptPsconfig. jsIt mainly stores some game configurations. The Code is as follows:
// Psconfig. jsvar cellsize = 73; // The Edge length of the star texture var matrixrow = 10; // Number of map rows (high) var matrixcol = 10; // Number of map columns (width) vaR totalcolors = [0, 1, 2, 3, 4]; // indicates five star modules. exports = {cellsize: cellsize, matrixrow: matrixrow, matrixcol: matrixcol, totalcolors: totalcolors ,};
Here, the level data has been generated, and the following is a map of Stars Based on the generated data.
Draw stars
As mentioned at the beginning, all the stars created will be placed inStarroot. ScenarioStarrootIs an empty node with a script componentMatrixctrSee:
The length of a single grid side is 73, and there is a gap between two pixels between the cells, soStarrootIt is a square with a side length of 748. It sets its anchor in the lower left corner to facilitate the conversion between the grid coordinate and the pixel coordinate.
Add two functions to the utils script to convert coordinates.
//Utils.jsfunction grid2Pos (gx, gy) { var px = Config.cellSize * 0.5 + (Config.cellSize + 2) * gy; var py = Config.cellSize * 0.5 + (Config.cellSize + 2) * gx; return cc.v2(px, py);};function pos2Grid (px, py) { var gx = (py - Config.cellSize * 0.5) / (Config.cellSize + 2); var gy = (px - Config.cellSize * 0.5) / (Config.cellSize + 2); return cc.v2(Math.round(gx), Math.round(gy));};
Finally, do not forget to export and add the variable in module. Exports:
module.exports = { grid2Pos: grid2Pos, pos2Grid: pos2Grid, initMatrixDataPortraitRandom: initMatrixDataPortraitRandom,};
Next, let's talk about the script.Matrixctr. js
The script has two pre-fabricated attributes, star and particle. Star is the star pre-made. The particle is mainly a playback particle, which is a special effect when the stars are eliminated.
properties: { starPrefab: cc.Prefab, starParticle: cc.Prefab, _starPool: null, uiCtr: cc.Node, actCtr: cc.Node, combCtr: cc.Node, soundCtr: cc.Node,},
Because the game needs to frequently create and destroy stars, these operations are very performance-consuming, so the object pool is used here. For more information, see the official documentation.
// Matrixctr. jsvar utils = require ("utils"); var Config = require ("psconfig"); var gamedata = require ("gamedata"); onload () {// initialize the object pool this. _ starpool = new CC. nodepool (); For (VAR I = 0; I <config. matrixcol * config. matrixrow; ++ I) {var star = cc. instantiate (this. starprefab); this. _ starpool. put (STAR) ;}} ondestroy () {This. _ starpool. clear () ;}, createstar (type, GX, GY) {var star = NULL; If (this. _ starpool. size ()> 0) {star = This. _ starpool. get ();} else {star = cc. instantiate (this. starprefab);} star. setposition (utils. grid2pos (GX, GY); this. node. addchild (STAR); var starctr = Star. getcomponent ("starctr"); starctr. initstar (type, GX, GY); Return star },
Note: CC. class and other common code are omitted here. With the createstar function, we can draw stars based on the data generated above.
// matrixCtr.jsinitMatrix () { for(var row = 0; row < GameData.starMatrix.length; row++) { var cols = GameData.starMatrix[row]; for(var col = 0; col < cols.length; col++) { var type = cols[col]; var index = Utils.indexValue(row, col); if (type >= 0) { var node = this.createStar(type, row, col); GameData.starSprite[index] = node; } else { GameData.starSprite[index] = null; } } }},
The initmatrix function uses the indexvalue function in the utils script. This is because the two-dimensional array is used to store the star data, and the one-dimensional array is used to store the star node, which is the index conversion between the two. Of course, a two-dimensional array can also be used to store star nodes.
//Utils.jsfunction indexValue (row, col) { return row * Config.matrixCol + col;};function resolveIndex (index) { var col = index % Config.matrixCol; var row = (index - col) / Config.matrixCol; return cc.v2(row, col);};
Do not forget to export the variable in module. exports. This is omitted. The last one is used.
Write it at the end. Welcome to subscribe. Get more information and stay up-to-date.
If you have any questions, please add a discussion (Verification: jimao Xin)
Conventions
- Source code download not provided
- The article will contain at least 90% of the source code, which describes the source code of 60%.
- If you repost the article, please note
Cocos creator development game to eliminate stars-star generation