So I'm picking a random letter from an array that looks like this:
const letters = [
"W",
"A",
"S",
"D"
]
Now I want to pick one randomly, say it picks D. Now once it picks D once, the next run around, it can't do the same thing, so it has to pick W, A, or S, but can't pick D. This isn't forever permanent, this is just so that a random pick isn't re-chosen.
I have this variable to check the last index, when the random letter is chosen, the last index will equal to the random letter.
How can I make it so that the next random letter is NOT the last index?
Code:
const RandomLetterGUI = document.getElementById("RandomLetters")
const TimerGUI = document.getElementById("Timer")
const LivesGUI = document.getElementById("Lives")
const ScoreGUI = document.getElementById("Score")
const letters = [
"W",
"A",
"S",
"D"
]
var seconds = 60;
var lives = 3;
var score = 0;
var timerId = setInterval(countdown, 1000);
var gameIsPlaying = true;
function countdown() {
if (lives == 0) {
clearTimeout(timerId);
}
if (seconds == -1) {
clearTimeout(timerId);
gameIsPlaying = false
} else {
if (seconds > 9) {
TimerGUI.innerHTML = ':' + seconds;
} else {
TimerGUI.innerHTML = ':0' + seconds;
}
seconds--;
}
}
countdown()
setInterval(displayLives, 0)
setInterval(updateScore, 0)
function updateScore() {
ScoreGUI.innerHTML = "Score: " + score
}
function displayLives() {
LivesGUI.innerHTML = "Remaining Lives: " + lives
if (lives == 0) {
gameIsPlaying = false
}
}
var lastIndex
function letter() {
var item = letters[Math.floor(Math.random() * letters.length)];
console.log(item, lastIndex)
if (lastIndex != item) {
RandomLetterGUI.innerHTML = "Next Letter: " + item
} else {
letter()
}
document.onkeypress = function (e) {
if (gameIsPlaying) {
var key = e.key
if (key.toUpperCase() != item) {
lives -= 1;
} else {
lastIndex = item
score += 150;
letter()
}
}
};
}
letter()
Aucun commentaire:
Enregistrer un commentaire