Sådan bygger du et matchende spil i din fritid med Easel.js

En del af min rejse i programmeringsverdenen er at lære om spiludvikling. Jeg har prøvet flere sprog som Java og C ++, men til sidst vil jeg gerne gå med Javascript. Jeg har bygget et spil, før jeg brugte JS. Spillet hedder Pong Ping, som er klonen for spillet Pong. Dette spil blev bygget udelukkende ved hjælp af native Javascript.

Men i dag vil jeg gerne bygge et spil baseret på en Javascript-spilramme kaldet Easel.js. Det spil, jeg skal bygge, er faktisk et meget simpelt spil: vi vender firkanter over, og hvis de har samme farve, forsvinder de. Spillet slutter, når hver farve matches. Her er et eksempel på spillet i videoen nedenfor, men de bruger billeder.

Trin 1

Jeg opretter index.html-filen og henviser til easel.js-biblioteket. Jeg vælger at bruge CDN (Content Deliver Network) til dette formål. Jeg bliver også nødt til at henvise til main.js, hvor al min Javascript-kode vil være.

#index.html Pairing Game  

Jeg er nødt til at sikre mig, at alle DOM-elementerne er fuldt indlæst, før Javascripts kunne udføres, så jeg bruger onload-metoden til at binde Javascript gennem funktionen init ().

Trin 2

Jeg opretter derefter main.js-filen og opsætter easel.js-miljøet.

#js/main.jsvar squarHeight = 200;var squareWidth = 200;
function init() { var stage = new createjs.Stage("myCanvas"); var square = drawSquare();
stage.addChild(square); stage.update();}

Easel bruger en klasse kaldet Stage som en container til at vise ethvert element til det definerede lærred. Nu tegner jeg en firkant gennem funktionen drawSquare. Jeg vil bruge alle de tilgængelige API'er fra easel.js

#js/main.jsfunction drawSquare() { var graphics = new createjs.Graphics().setStrokeStyle(5).beginStroke("rgba(20,20,20,1)") graphics.beginFill(randomColor()).rect(5,5,squareWidth,squareHeight); var shape = new createjs.Shape(graphics); return shape;}
function randomColor() { var num1 = Math.floor(Math.random()*255); var num2 = Math.floor(Math.random()*255); var num3 = Math.floor(Math.random()*255); return "rgba("+num1+","+num2+","+num3+",1)"; }

Først definerer jeg den slagstørrelse, jeg gerne vil bruge. Derefter anvender jeg streg med en bestemt farve, definerer firkantets farve og opretter firkanten. Kvadratets farve er en tilfældig farve genereret ud fra funktionen randomColor. Nedenfor er, hvordan det vil se ud i browseren.

Trin 3

Når jeg har gengivet en firkant med en tilfældig farve, skal jeg designe, hvor mange rækker og kolonner der vil være for kvadraterne at udfylde. Jeg bliver også nødt til at designe algoritmen til at gengive en firkant i hver kolonne og rækker

#js/main.js##upated codesvar squarHeight = 200;var squareWidth = 200;var squareGap = 10;var column = 3;var row = 2;
function init() { var stage = new createjs.Stage("myCanvas"); var square;
for(i=0; i < column*row; i++) { square = drawSquare(); square.x = (squareWidth+squareGap)*(i%column); square.y = (squarHeight+squareGap)*Math.floor(i/column); stage.addChild(square); stage.update(); }
}
function drawSquare() { var graphics = new createjs.Graphics().setStrokeStyle(5).beginStroke("rgba(20,20,20,1)") graphics.beginFill(randomColor()).rect(5,5,squarHeight,squareWidth); var shape = new createjs.Shape(graphics); return shape;}
function randomColor() { var num1 = Math.floor(Math.random()*255); var num2 = Math.floor(Math.random()*255); var num3 = Math.floor(Math.random()*255); return "rgba("+num1+","+num2+","+num3+",1)"; }

Fra ovenstående koder får jeg en gengivet HTML sådan noget:

Der er mange måder at implementere den kvadratiske gengivelse på. Vi kunne bruge looping i et flerdimensionelt array, eller vi kunne manipulere kvadratstørrelsen med en eller anden matematisk funktion. I dette tilfælde bruger jeg den senere. Men her er algoritmen, hvis du vil bruge den flerdimensionelle metode:

#alternativevar positionX =0; var positionY = 0;
for(i=0;i
    

Step 4

Again, the objective of this game is to match a pair of colors together. So I need to modify the code in order for it to generate groups of colors in pairs. To do that, I will use an if else logic to make sure the two similar colors are used during the square rendering.

#js/main.jsvar temp;var genOnce = false;
function drawSquare() {var color = randomColor();var graphics = new createjs.Graphics().setStrokeStyle(5).beginStroke("rgba(20,20,20,1)")
 if(!genOnce) { graphics.beginFill(color).rect(5,5,squarHeight,squareWidth); temp = color; genOnce = true; }else { graphics.beginFill(temp).rect(5,5,squarHeight,squareWidth); genOnce = false; }
 var shape = new createjs.Shape(graphics); return shape;}

This will render a group of squares something like this:

Step 5

Next, I want each of the squares to be rendered in a random position so the pairs are separated from each other. This can be achieved by first creating an array consisting of all indices of the squares, then shuffling the array so the index number is randomly placed.

#js/main.jsvar squarePlacement = [];
##function to generate array with all the squares indexfunction randomDoubleColor() { for(i=0; i
     
}
##function of the array random shufflingfunction shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array;}

Then I’ll need to change how I render the square. Instead of iterating through the length of total squares, I will iterate through the randomly shuffled array.

#js/main.jsfunction init() { var stage = new createjs.Stage("myCanvas"); var square; randomDoubleColor();
for(i=0; i < squarePlacement.length; i++) { square = drawSquare(); square.x = (squareWidth+squareGap)*(squarePlacement[i]%column); square.y = (squarHeight+squareGap)*Math.floor(squarePlacement[i]/column); stage.addChild(square); stage.update(); }
}

This will get me a group of squares like this:

I can see the effect better if more squares are rendered:

Step 6

My goal is now to create a function that will compare two squares which will be selected subsequently.

#js/main.jsvar highlight = createjs.Graphics.getRGB(255, 0, 0);var tileChecked;

I will start with defining a variable highlight. This will be used to highlight the first selected squares and a variable tileChecked to store the same square.

#js/main.jsfor(i=0; i < squarePlacement.length; i++) { square = drawSquare(); square.x = (squareWidth+squareGap)*(squarePlacement[i]%column); square.y = (squarHeight+squareGap)*Math.floor(squarePlacement[i]/column); stage.addChild(square); square.addEventListener("click", handleOnPress); stage.update(); }
}

I will then create an event listener which will respond to a mouse click and trigger the function defined, handleOnPress. Now I will define the function as follows:

function handleOnPress(e) { var tile = e.target; if(!!tileChecked === false) { tile.graphics.setStrokeStyle(5).beginStroke(highlight).rect(5, 5, squareWidth, squarHeight); tileChecked = tile; }else { if(tileChecked.graphics._fill.style === tile.graphics._fill.style && tileChecked !== tile) { tileChecked.visible = false; tile.visible = false; }else { console.log("not match"); tileChecked.graphics.setStrokeStyle(5).beginStroke("rgba(20,20,20,1)").rect(5, 5, squareWidth, squarHeight); } tileChecked = null; } stage.update();
}

Basically the function will first check the variable tileChecked. If it is undefined, the selected square will be highlighted. The selected square object will be saved in the variable tileChecked. Otherwise (which I expect to happen on the second click), the color between the current selected square and the one which is stored in the variable tileChecked will be compared.

In this second comparison, if the color is a match, I will make both the squares disappear. If it is not a match, I will remove the highlight and reset the variable tileChecked to undefined.

Step 7

To create a real puzzle game, all of the colors should not be displayed. I will make the squares covered by grey squares, and when each is clicked, then it will reveal the color. So when it is not a match, the grey square will cover the box again.

To make it more playable, I will make sure other squares are not clickable during the comparison. I will also put some delay between when the second color is displayed and when both squares disappear or turn to grey. Some modification needs to be done in order for everything to work properly

function init() { var stage = new createjs.Stage("myCanvas"); randomDoubleColor();
for(i=0; i < squarePlacement.length; i++) { var color =randomColor(); console.log(color); var square = drawSquare(color); console.log(square); square["color"] = square.graphics._fill.style; square.graphics._fill.style = "rgb(140, 136, 136)"; square.x = (squareWidth+squareGap)*(squarePlacement[i]%column); square.y = (squareHeight+squareGap)*Math.floor(squarePlacement[i]/column); stage.addChild(square); square.addEventListener("click", handleOnPress); stage.update(); } function handleOnPress(e) { var tile = e.target;
tile.graphics.beginFill(tile.color).rect(5,5,squareHeight,squareWidth); console.log(tile.mouseEnabled); tile.mouseEnabled = false; console.log(tile.mouseEnabled);
if(!!tileChecked === false) { tileChecked = tile; }else {
stage.mouseChildren = false; tile.graphics.beginFill(tile.color).rect(5,5,squareHeight,squareWidth);
setTimeout(function() { console.log("in"); console.log(tile); console.log(tileChecked); if(tileChecked.color === tile.color && tileChecked !== tile) { tileChecked.visible = false; tile.visible = false; }else { console.log("not match"); tile.graphics.beginFill("rgb(140, 136, 136)").rect(5,5,squareHeight,squareWidth); tileChecked.graphics.beginFill("rgb(140, 136, 136)").rect(5,5,squareHeight,squareWidth);
} tile.mouseEnabled = true; tileChecked.mouseEnabled = true; stage.mouseChildren = true; tileChecked = null;
stage.update(); }, 1000); } stage.update();
}
}
function drawSquare(color) { var graphics = new createjs.Graphics().setStrokeStyle(5).beginStroke("rgba(20,20,20,1)")
if(!genOnce) { graphics.beginFill(color).rect(5,5,squareHeight,squareWidth); temp = color; genOnce = true; }else { graphics.beginFill(temp).rect(5,5,squareHeight,squareWidth); genOnce = false; } var shape = new createjs.Shape(graphics); return shape;}

Below is a video of the game in action:

This game can be enhanced further by adding the winning or losing rules, or maybe by adding a timer to record each player’s finishing time. At the moment I will stop development up until this point. The full code can be found on GitHub below, and anybody is free to use it for any other project.

muyaszed/Matching-game-using-Easel.js

Contribute to Matching-game-using-Easel.js development by creating an account on GitHub.github.com

DEMO

Notes: There are probably many ways to implement this feature, but this way was easiest for me. Anybody is free to comment on any mistakes or improvements that I can apply. This guide is initially for me to learn and remember what I have done. Nonetheless anybody is welcome to follow this guide if you find it is helpful.