Skip to content

Instantly share code, notes, and snippets.

@marcoranieri
Created June 27, 2020 16:52
Show Gist options
  • Save marcoranieri/00040fd2f88b053e06a0a5fb5415428a to your computer and use it in GitHub Desktop.
Save marcoranieri/00040fd2f88b053e06a0a5fb5415428a to your computer and use it in GitHub Desktop.
DOM&EVENT
// declare our event listener and wait for KEYUP
document.addEventListener("keyup", event => {
// Someone press a key => Event
console.log(event.keyCode)
// check if the keycode is correct
// if player1 keycode
if (event.keyCode === 81) {
const active = document.querySelector("#player1-race > .active")
// check if win
if (active.nextElementSibling === null) {
alert("YOU WON!")
} else {
// remove the .active class from the current target
active.classList.remove("active")
// add the .active class to next element
active.nextElementSibling.classList.add("active")
}
// if player2 keycode
} else if (event.keyCode === 80) {
const active = document.querySelector("#player2-race > .active")
// check if win
if (active.nextElementSibling === null) {
alert("YOU WON!")
} else {
// remove the .active class from the current target
active.classList.remove("active")
// add the .active class to next element
active.nextElementSibling.classList.add("active")
}
}
});
const winning_logic = () => alert("YOU WON!")
const move_your_wagon = (active) => {
active.classList.remove("active")
active.nextElementSibling.classList.add("active")
}
const check_if_win = (active) => active.nextElementSibling === null
const play = (active) => {
if (check_if_win(active)) {
winning_logic()
} else {
move_your_wagon(active)
}
}
document.addEventListener("keyup", event => {
if (event.keyCode === 81) {
const active = document.querySelector("#player1-race > .active")
play(active);
} else if (event.keyCode === 80) {
const active = document.querySelector("#player2-race > .active")
play(active);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment