Estoy creando un juego de Ludo y mi condición es que si hay tres 6 seguidos, la oportunidad del usuario pasará al siguiente usuario. Hice un número aleatorio del 1 al 6. Estaba almacenando el último dígito con una variable llamada lastDice y comparé el último con un número aleatorio reciente, pero no puedo hacerme una idea de los últimos 3 números aleatorios para comparar. Pero la condición es que si los últimos 3 números aleatorios son 6s(6,6,6), entonces el juego debe detenerse . Los códigos son los siguientes:
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 }
Puede crear una matriz simple y usar Math.random
para obtener el índice del número a elegir:
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
Si desea eliminar el primer número y reemplazarlo con una nueva tirada de dados, simplemente use:
lastNums.shift(); // remove the 3rd last number lastNums.push(lastDice); // add the current dice roll
Editar: si el manejo de matrices es demasiado complejo para usted, aquí hay otro método que usa tres 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;
Ejemplo: saqué un 4. Después de cada turno, cuando se barajan los números, el tercer número se reemplaza por el segundo número, el segundo número se reemplaza por el primer número y el primer número se reemplaza por el último dado. Entonces debería tener: firstNum = 4, secondNum = 1, thirdNum = 2.
Supongo que resolví el problema. Agregué el número aleatorio a una matriz y usé una condición si la matriz es más de 3, se eliminará el primer índice de la matriz. y luego comparé el valor de indexación de una matriz entre sí para ver si todo su valor es igual a 6. como el siguiente código:
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(); };