Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active December 7, 2018 08:35
Show Gist options
  • Save harrisonmalone/f4df29c7e43fdc399da417ba1a5627e5 to your computer and use it in GitHub Desktop.
Save harrisonmalone/f4df29c7e43fdc399da417ba1a5627e5 to your computer and use it in GitHub Desktop.
le wagon moving background image with keyup js challenge
.racer_table td {
height: 200px;
width: 200px;
border: 3px solid black;
}
.racer_table td.active {
background-repeat: no-repeat;
background-size: cover;
}
#player1_race td.active {
background-image: url("cartoon_car.png");
}
#player2_race td.active {
background-image: url("cartoon_car.png");
}
.finish {
background: black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="race.css">
<script defer src="race.js"></script>
</head>
<body>
<table class="racer_table">
<tr id="player1_race">
<td class="active"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="finish"></td>
</tr>
<tr id="player2_race">
<td class="active"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="finish"></td>
</tr>
</table>
</body>
</html>
// set main variables
const playerOneParent = document.querySelector('#player1_race')
const playerOneBoard = Array.from(playerOneParent.children)
const playerTwoParent = document.querySelector('#player2_race')
const playerTwoBoard = Array.from(playerTwoParent.children)
const movePlayerOne = () => {
const active = findActivePosition(playerOneBoard)
const index = playerOneBoard.indexOf(active) + 1
playerOneBoard[index].classList.add('active')
if (index === playerOneBoard.length - 1) {
alert('Player one wins! Press enter to restart ๐Ÿ‘Œ')
location.reload()
}
}
const movePlayerTwo = () => {
const active = findActivePosition(playerTwoBoard)
const index = playerTwoBoard.indexOf(active) + 1
playerTwoBoard[index].classList.add('active')
if (index === playerTwoBoard.length - 1) {
alert('Player two wins! Press enter to restart ๐Ÿ”™')
location.reload()
}
}
// function to find board piece with active class
const findActivePosition = (board) => {
const active = board.find((position) => {
if (position.classList.contains('active')) {
position.classList.remove('active')
return position
}
})
return active
}
document.addEventListener('keydown', event => {
if (event.key === 'j') {
movePlayerOne()
}
else if (event.key === 'a') {
movePlayerTwo()
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment