Car Game: Object, this, Users can enter keyboard input (letters).
Each of the car's methods are assigned to a key.
When the user presses a key, it calls the appropriate function.
These letters also trigger a global function called reWriteStats() that logs the car's make, model, color, mileage, and is Working status to the console.
document.onkeyup() function to collect input from the user's keyboard.
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Car Adventures!</title>
</head>
<body>
<h1>Car Adventures!</h1>
<h2>Type "h" to honk, "d" to drive to work, "w" to drive around the world, or "t" to get a tuneup.</h2>
<h2>See console for car stats.</h2>
<script>
// VARIABLES
// ==========================================================================
var car = {
make: "Honda",
model: "Fit",
color: "Blue Raspberry",
mileage: 3000,
isWorking: true,
driveToWork: function() {
alert("Old Mileage: " + this.mileage);
this.mileage = this.mileage + 8;
alert("New mileage: " + this.mileage);
},
driveAroundWorld: function() {
alert("Old Mileage: " + this.mileage);
this.mileage = this.mileage + 24000;
alert("New Mileage: " + this.mileage);
alert("Car needs a tuneup!");
this.isWorking = false;
},
getTuneUp: function() {
alert("Car is ready to go!");
this.isWorking = true;
},
honk: function() {
alert("Honk! Honk!");
},
reWriteStats: function() {
console.log("Make: " + this.make);
console.log("Model: " + this.model);
console.log("Color:" + this.color);
console.log("Mileage: " + this.mileage);
console.log("Is Working: " + this.isWorking);
console.log("------------------------------");
}
};
// FUNCTIONS
// ==============================================================================
// Logs all of our car's current stats to the console.
function reWriteStats() {
console.log("Make: " + car.make);
console.log("Model: " + car.model);
console.log("Color:" + car.color);
console.log("Mileage: " + car.mileage);
console.log("Is Working: " + car.isWorking);
console.log("------------------------------");
}
// MAIN PROCESS
// ==============================================================================
// Captures keyboard input. Depending on the letter pressed it will "call" (execute) different functions.
document.onkeyup = function(event) {
// Captures the key press, converts it to lowercase, and saves it to a variable.
var letter = String.fromCharCode(event.keyCode).toLowerCase();
// If the letter is h, run the following functions/methods.
if (letter === "h") {
car.honk();
reWriteStats();
}
// If the letter is d, run the following functions/methods.
if (letter === "d") {
car.driveToWork();
reWriteStats();
}
// If the letter is w, run the following functions/methods.
if (letter === "w") {
car.driveAroundWorld();
reWriteStats();
}
// If the letter is t, run the following functions/methods.
if (letter === "t") {
car.getTuneUp();
reWriteStats();
}
};
</script>
</body>
</html>