- script.js
JavaScript
var gameRules = {
diceNumber: 1,
maxAttempts: 1
};
var firstCat = {
name: 'Muffin',
points: 0
};
var secondCat = {
name: 'Rudolph',
points: 0
};
var thirdCat = {
name: 'Rocky',
points: 0
};
var cats = [firstCat, secondCat, thirdCat];
var runGame = function (rules, players) {
for (var currentAttempt = 1; currentAttempt <= rules.maxAttempts; currentAttempt++) {
for (var i = 0; i < players.length; i++) {
var throwResult = muffin.throwDice(rules.diceNumber, rules.diceNumber * 6);
players[i].points += throwResult;
console.log(players[i].name + ' rolled ' + players[i].points);
}
}
return players;
};
var getWinners = function (players) {
var winners = [];
var max = players[0];
for (var i = 0; i < players.length; i++) {
var currentPlayer = players[i];
if (currentPlayer.points > max.points) {
max = currentPlayer;
winners = [max];
} else if (currentPlayer.points === max.points) {
winners.push(currentPlayer);
}
}
return winners;
};
var printWinners = function (players, winners) {
if (players.length === winners.length) {
console.log('All cats rock!');
return;
}
var message = 'The winner is ';
for (var i = 0; i < winners.length; i++) {
message += winners[i].name;
}
message += ' with the number of points: ' + winners[0].points;
console.log(message);
};
cats = runGame(gameRules, cats);
console.log(cats);
var tops = getWinners(cats);
console.log(tops);
printWinners(cats, tops);
Result
Goalscompleted
In the body of the printWinners
function:
- After declaring the variable
message
, add a check to make sure that the number of winners is greater than1
. - If the condition is true, override the value of the variable
message
to'The winners are '
. - At the beginning of the loop body, add a check to make sure that
i
is greater than or equal to1
. - If the condition is met, add
', '
string tomessage
(that way a comma will be added between all the names if there are more than one). - Remove console log for arrays
cats
andtops
at the end of the program.
Comments