Train Game
The starting point for the project from Lesson 12 of JavaScript for Kids For Dummies by Chris Minnick and Eva Holland
by Kanatantsin
HTML
<div id="container">
<p>
<ul>
<!-- instructions go here -->
</ul>
</p>
<div id="track">
<div id="train"><img src="http://www.watzthis.com/images/train.png"></div>
</div>
<div id="stopButton">Stop!</div>
</div>
CSS
body {
font-family: Arial, sans-serif;
}
#container {
padding: 10px;
width: 780px;
height: 80%;
background-color: #0000FF;
}
#track {
width: 760px;
border-top: 2px solid white;
border-bottom: 2px solid white;
margin: 20px auto;
}
#train {
height: 92px;
width: 100px;
position: relative;
left: 0px;
}
#stopButton {
padding-top: 15px;
margin: 10px auto;
background-color: white;
width: 100px;
height: 50px;
color: red;
text-align: center;
font-size: 24px;
line-height: 30px;
}
JavaScript
/*
todo: create three global variables:
* trainSpeed (initial value = 250)
* trainPosition (initial value = 0)
* animation (no initial value)
*/
var trainSpeed = 250;
var trainPosition = 0;
var animation;
/*
todo: listen for click events on the train element and call a function named speedUp when they happen.
*/
var train = document.getElementById("train");
train.addEventListener("click", speedUp);
/*
todo: listen for click events on the stop button element and call a function called stopTrain when they happen.
*/
var stopButton = document.getElementById("stopButton");
stopButton.addEventListener("click", stopTrain);
function speedUp() {
/*
todo: check whether the train is already going as fast as it can. If not, increase the speed.
*/
if (trainSpeed > 10) {
trainSpeed -= 10;
}
//console.log("train speed: " + trainSpeed);
clearInterval(animation);
animation = setInterval(frame, trainSpeed);
/*
If the train is already moving, stop it and then restart with the new speed by calling a function called frame.
*/
function frame() {
/*
reposition the train and check whether the train is crashed
*/
trainPosition += 2;
train.style.left = trainPosition + 'px';
checkPosition(trainPosition);
}
}
function checkPosition(currentPosition) {
if (currentPosition === 760) {
alert("Crash!");
console.log("Crash!");
clearInterval(animation);
}
/*
todo: check the train's current position and crash it if it's at the end of the line
*/
}
function stopTrain() {
/*
todo: test whether the train is already crashed. If not, stop the train.
*/
if (trainPosition < 760) {
clearInterval(animation);
}
}