I am making a Ludo game and my condition is if there are three 6 in a row then the user's chance will be passed to the next user. I made a random number from 1 to 6. I was storing the last digit with a variable called lastDice and compared the last one with a recent random number but I can not get the idea of the last 3 random numbers to compare. But the condition is if the last 3 random numbers are 6s(6,6,6) then the game must stop. Codes are as follows:
const playing = true;
const random = Math.floor(Math.random() * 6 + 1);
const lastDice = 0;
if (playing) {
if (random === 6 && lastDice === 6) {
document.getElementById('score--1').textContent = 0; // update the ui
} else {
nextPlayer(); // its a function to call the next player
}
lastDice = dice; // storing the last random number for comparing next random number
}
You can create a simple array, and use Math.random to get the index of the number to pick:
var lastNums = [0, 0, 0]; // 3rd last, 2nd last, and last number
var index = Math.floor(Math.random()*3);
var chosenNumber = lastNums[index];
// then compare
If you want to remove the first number and replace it with a new dice roll, simply use:
lastNums.shift(); // remove the 3rd last number
lastNums.push(lastDice); // add the current dice roll
Edit: If handling arrays are a bit too complex for you, here's another method using three variables:
// create 3 number variables
// I'll give the variables a non-zero value first
var firstNum = 1;
var secondNum = 2;
var thirdNum = 3;
// shuffle the number variables after each turn
// to set lastDice as previous dice roll
// here I treat firstNum as the last dice roll,
// secondNum as the second last dice roll,
// and thirdNum as the third last dice roll
thirdNum = secondNum;
secondNum = firstNum;
firstNum = lastDice;
Example: I rolled a 4. After each turn, when the numbers are shuffled, thirdNum gets replaced with secondNum, secondNum gets replaced with firstNum, firstNum gets replaced with lastDice. So I should have: firstNum = 4, secondNum = 1, thirdNum = 2.
I guess, I solved the problem. I added the random number to an array and used a condition if the array is more than 3 first index of the array will be removed. and then I compared the indexing value of an array with each other to see if all their value is equally 6. like the following code:
const random = Math.floor(Math.random()*6+1);
// container is an empty array called before
container.push(random);
//remove if conditon full fills
if(container.length >3){
container.shift();
};
console.log(container);
if(container[0] === 6 && container[1] === 6 && container[2] === 6){
scores[activePlayer] = 0;
document.getElementById('score--'+activePlayer).textContent = 0;
switchPlayer();
};