In this task, we will add a power value to the cards. We will also create a Card
object to get the original value back.
Before going into the core part, we will get the interface prepared.
There is not much to add in HTML. Add the power
element inside the front face
element, as shown in the following code:
<div class="front face"> <div class="power">100</div> </div>
Also, add some very basic CSS styling to define the power text, which is large and aligned in the center, as shown in the following code:
.card .power{ position: absolute; width: 100%; text-align: center; bottom: 30px; font-size: 2em; }
The core part of this task is the JavaScript logic, explained as follows:
game-scene.js
file. The benefit of separating this logic is to make changing the power formula easy in the future:;(function() { var game = this.cardBattleGame = this.cardBattleGame || {}; // Cache elements query var allPowerElms = document.querySelectorAll('.power'), game.randomizePower = function() { allPowerElms.forEach(function(elm){ elm.textContent = Math.round(Math.random() * 60) + 40; }); } })();
Card
definition inside the gameScene
object:var Card = (function(){ function Card(node) { this.node = node; } Card.prototype.power = function() { return 1 * this.node.querySelector('.power').textContent // convert string to integer } return Card; })();
gameScene.restartGame = function() { game.randomizePower(); // rest of the existing code in restartGame. }
new Card
instance, and then check the power of the card after logging into the game:/* select a card */ selectedCard = new Card(elm); console.log("Power of selected card: ", selectedCard.power()); // rest of original code for card selection.
We have added a power value to the cards. These values will be used for comparison when we add the battle logic later.
The game randomizes the power values in all cards for every round when the game begins. It is a separate logic that selects all the power elements and adds a randomized value ranging from 40 to 100 to it. After we get the value, we use the textContent
property to set the string value to the card node.
Most of the card logic is done on the HTML node directly, such as the toggling classes. But the power is stored in the node as a string type. We want to get the integer type of the power value to make the battle calculations easier. That's why we create a Card
object definition.
The Card
object contains the original HTML node reference and a power
method to get the integer power value from the text content of the HTML node.
The reason why we only instantiate the selected card is because we don't read any power value of the non-selected card.
When do you define an object definition and when do you declare an object instance directly?
When something is going to be reused many times, declaring the definition allows us to create many instances using the new
operator. Otherwise, if we just need the object once, an object instance is more than enough.
52.14.149.128