Lunch Game
Starting point for the Lunch Game project from Chapter 18 of JavaScript for Kids For Dummies by Chris Minnick and Eva Holland
by Kanatantsin
HTML
<h1>Lunch Game!</h1>
<div id="instructions">
<p>You get a weekly allowance of $<span id="money"></span> to buy lunch. Sandwiches are always between $1 and $5, but you never know the price until you get to school.</p>
<p>Your goal is to be able to buy lunch every day of the week.</p>
</div>
<div id="orderForm">
<label>How many sandwiches do you want per day?
<br />
<input type="number" id="numSandwiches" />
</label>
<button type="button" id="placeOrder">Place Order</button>
</div>
<div id="receipt"></div>
CSS
body {
font-family: sans-serif;
}
#instructions {
background-color: pink;
padding: 6px;
margin: 6px;
}
#orderForm {
width: 75%;
margin: 20px auto;
}
#receipt {
background-color: #996600;
color: yellow;
padding: 6px;
}
}
JavaScript
// declare globals
var money = 20;
var lunches = 0;
//display lunch budget
document.getElementById("money").innerHTML = money;
//listen for order
document.getElementById("placeOrder").addEventListener("click", buyLunches);
/*
buys specified number of sandwiches per day at current prices
*/
function buyLunches() {
resetForm();
var day = 0;
while (money > 0) {
day++;
var priceToday = getSandwichPrice();
var numberOfSandwiches = document.getElementById("numSandwiches").value;
var totalPrice = priceToday * numberOfSandwiches;
if (money >= totalPrice) {
money = money - totalPrice;
lunches++;
document.getElementById("receipt").innerHTML += "<p>On day " + day + ", sandwiches are: $" + priceToday + ". You have $" + money.toFixed(2) + " left.</p>";
} else {
document.getElementById("receipt").innerHTML += "<p>Today, sandwiches are: $" + priceToday + ". You don't have enough money. Maybe your sister will give you some of her sandwich.</p>";
money = 0;
}
}
document.getElementById("receipt").innerHTML += "<p>You bought " + lunches + " lunches this week.</p>";
/*function buyLunches() {
resetForm();
var day = 0;
while (money > 0) {
var priceToday = getSandwichPrice();
var numberOfSandwiches = document.getElementById("numSandwiches").value;
var totalPrice = pricetoday * numberOfSandwiches;
if (money >= totalPrice) {
money = money - totalPrice;
lunches++;
document.getElementById("receipt").innerHTML += "<p>On day " + day + ", sandwiches are: $" + priceToday + ". You have $" + money.toFixed(2) + " left.</p>";
} else {
document.getElementById("receipt").innerHTML += "<p>Today, sandwiches are: $" + priceToday + ". You don't have enough money. Maybe your sister will give you some of her sandwich.</p>";
money = 0;
}
}
document.getElementById("reciept").innerHTML += "<p>You...