'I can't get the code to say reached, anything I try to assign to the array position returns [] instead of the current state (index)
let level = 1
const buttonColors = ['red', 'blue', 'green', 'yellow']
const gamePattern = []
const x = gamePattern.slice(gamePattern.length - 1, gamePattern.length)
function nextSequence () {
const randomNumber = Math.floor(Math.random() * 4)
const randomChosenColor = buttonColors[randomNumber]
gamePattern.push(randomChosenColor)
console.log('The Current level: ' + level)
$('#' + randomChosenColor).fadeOut(100).fadeIn(100)
playSound(randomChosenColor)
if (level === 1) {
$('#levelTitle').text('level ' + level)
}
level++
}
// ------------------------------------------------------------------
$('.btn').click(function () {
const userChosenColor = this.id
playSound(userChosenColor)
animatePress(userChosenColor)
checkAnswer(buttonColors.indexOf(userChosenColor))
console.log('User chosen Color: ' + buttonColors.indexOf(userChosenColor)) // indexOf is not a string*
})
// ------------------------------------------------------------------
function animatePress (currentColor) {
$('#' + currentColor).addClass('pressed')
setTimeout(function () {
$('#' + currentColor).removeClass('pressed')
}, 100)
}
function playSound (name) {
const audio = new Audio('sounds/' + name + '.mp3')
audio.play()
}
// ------------------------------------------------------------------
function checkAnswer (currentLevelColor) { // indexOf #1 === indexOf #2
if (currentLevelColor === buttonColors.indexOf(x)) {
console.log('REACHED')
} else {
console.log('NOT REACHED')
}
}
$(document).keydown(nextSequence)
I've been stuck trying to save the array as a variable but my browser never recognizes the code after I try to save it as a variable, but the code on it's own works. - I have tried various methods breaking the code down and restructuring it to no avail; can someone explain what I'm doing wrong - the goal is to get the code to say "REACHED" HTML BELOW*
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css"> <!-- NOTE: CSS -->
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="levelTitle">Press A Key to Start</h1>
<div class="container">
<div class="row">
<div type="button" id="green" class="btn green">
</div>
<div type="button" id="red" class="btn red">
</div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow">
</div>
<div type="button" id="blue" class="btn blue">
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="game.js"></script>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|