Match‑3 Game Development Tutorial with JavaScript and Cocos
This article provides a step‑by‑step tutorial on building a match‑3 (candy‑crush style) game, covering basic rules, core matching and removal algorithms in JavaScript, and a complete implementation in Cocos Creator with grid layout, touch handling, swap animation, piece falling, and refill logic.
Introduction
The tutorial starts by reviewing the previous "Two‑Day Cocos Plane Battle" tutorial and introduces the more complex match‑3 game, explaining its basic rules such as eliminating three or more identical pieces in a line and special piece effects.
Match‑3 Basic Rules
Using the example of "Happy Match‑3", the article lists standard elimination rules and special patterns (four‑in‑a‑row creates a line piece, L/T shapes create explosion pieces, five in a row creates a "life bird" that swaps any matching piece, etc.).
Core JavaScript Algorithm
A 2‑D array represents the board, with numbers indicating piece types. The article provides code for swapping pieces, checking matches, removing matched pieces, moving pieces down, and refilling empty cells.
const chessBoard = [
[1, 2, 3],
[2, 4, 2],
[1, 4, 3]
];
swapPiece([row1, col1], [row2, col2]) {
const temp = this.chessBoard[row1][col1];
this.chessBoard[row1][col1] = this.chessBoard[row2][col2];
this.chessBoard[row2][col2] = temp;
}The checkMatch function uses a cross‑expansion method to collect contiguous identical pieces horizontally or vertically, returning matches only when the count is ≥ 3.
checkMatch(row, col, horizontal) {
const matches = [[row, col]];
const current = this.chessBoard[row][col];
// left/right or up/down loops …
return matches.length >= 3 ? matches : [];
}After removal, movePiecesDown collapses columns, and refillAndCheck fills null cells with random pieces, then recursively checks for new matches.
Cocos Implementation
The article transitions to Cocos Creator, describing two layout options (Grid component vs. manual coordinate calculation) and shows how to generate the board programmatically.
generateBoard() {
this.chessBoard = Array.from({ length: this.boardHeight }, () =>
Array.from({ length: this.boardWidth }, () => null)
);
// instantiate pieces and set positions …
}Touch handling is performed on the board node: the start position is captured, the touched piece is identified by converting UI coordinates to node space and checking each piece's bounding box.
getPieceAtPosition(pos) {
const uiTransform = this.node.getComponent(UITransform);
const { x, y } = uiTransform.convertToNodeSpaceAR(v3(pos.x, pos.y));
for (let row = 0; row < this.chessBoard.length; row++) {
for (let col = 0; col < this.chessBoard[row].length; col++) {
const piece = this.chessBoard[row][col];
const box = piece?.getComponent(UITransform).getBoundingBox();
if (box?.contains(v2(x, y))) return [row, col];
}
}
}Movement direction is determined by comparing the delta of the current touch point with the start point; a threshold prevents accidental swaps.
if (Math.abs(diffX) > Math.abs(diffY)) {
target = diffX > threshold ? [row, col + 1] : [row, col - 1];
} else {
target = diffY > threshold ? [row - 1, col] : [row + 1, col];
}Swapping triggers an animation using Cocos' tween system, and a lock ( isSwap ) prevents overlapping swaps.
swapAnimation(a, b, callback) {
const aPos = new Vec3(a.position.x, a.position.y);
const bPos = new Vec3(b.position.x, b.position.y);
tween(a).to(0.2, { position: bPos }).call(() => resolve()).start();
tween(b).to(0.2, { position: aPos }).call(() => resolve()).start();
Promise.allSettled([p1, p2]).then(callback);
}If the swapped pieces are identical, the swap is reverted; otherwise the algorithm checks for matches starting from the two swapped positions. Matching pieces are removed from both the logical board and the scene graph, then movePiecesDown and refillAndCheck are called with falling and spawn animations.
Conclusion
The tutorial ends with a working basic match‑3 game in Cocos, a link to the source repository, and suggestions for further enhancements such as explosion effects, sound, and additional game mechanics.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.