Comment créer un jeu d'association pendant votre temps libre avec Easel.js

Une partie de mon parcours dans le monde de la programmation consiste à apprendre le développement de jeux. J'ai essayé plusieurs langages tels que Java et C ++, mais à la fin j'aimerais aller avec Javascript. J'ai construit un jeu avant d'utiliser JS. Le jeu s'appelle Pong Ping, qui est le clone du jeu Pong. Ce jeu a été construit uniquement en utilisant Javascript natif.

Mais aujourd'hui, j'aimerais créer un jeu basé sur un framework de jeu Javascript appelé Easel.js. Le jeu que je vais construire est en fait un jeu très simple: on retourne les carrés, et s'ils sont de la même couleur, ils disparaîtront. Le jeu se terminera lorsque chaque couleur sera assortie. Voici un exemple du jeu dans la vidéo ci-dessous, mais ils utilisent des images.

Étape 1

Je vais créer le fichier index.html et faire une référence à la bibliothèque easel.js. Je choisis d'utiliser CDN (Content Deliver Network) à cette fin. Je devrai également faire référence à main.js où tout mon code Javascript sera.

#index.html Pairing Game  

Je dois m'assurer que tous les éléments DOM sont complètement chargés avant que les Javascripts puissent être exécutés, j'utilise donc la méthode onload pour lier le Javascript via la fonction init ().

Étape 2

Je vais ensuite créer le fichier main.js et configurer l'environnement easel.js.

#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 utilise une classe appelée Stage comme conteneur pour afficher n'importe quel élément sur le canevas défini. Maintenant, je vais dessiner un carré grâce à la fonction drawSquare. J'utiliserai toutes les API disponibles de 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)"; }

Je vais d'abord définir la taille de trait que je souhaite utiliser. Ensuite, je vais appliquer le trait avec une couleur spécifique, définir la couleur du carré et créer le carré. La couleur du carré est une couleur aléatoire générée à partir de la fonction randomColor. Voici à quoi cela ressemblera dans le navigateur.

Étape 3

Une fois que j'ai correctement rendu un carré avec une couleur aléatoire, je dois concevoir le nombre de lignes et de colonnes qu'il y aura pour les carrés à remplir. Je devrai également concevoir l'algorithme pour rendre un carré dans chaque colonne et lignes

#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)"; }

À partir des codes ci-dessus, j'obtiendrai un rendu HTML quelque chose comme ceci:

Il existe de nombreuses façons d'implémenter le rendu carré. Nous pourrions utiliser la boucle dans un tableau multidimensionnel, ou nous pourrions manipuler la taille carrée avec une fonction mathématique. Dans ce cas, j'utiliserai le plus tard. Mais voici l'algorithme si vous souhaitez utiliser la méthode multidimensionnelle:

#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:

Original text


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.