Generating New Pizzas & Orders With Math
📝 We continue in the Speedy Chef project folder throughout this section.
Creating the pizzas randomly
We can use what we know about JavaScript Math to generate random pizzas and orders. First, make sure the function is empty from the previous examples:
function generateNewPizza() {}
And we can begin to use this function to generate a random pizza from our pizzas array:
function generateNewPizza() {
// generate a random number between 1-3
const quantity = Math.ceil(Math.random() * 3); // quantity 1-3
// get random pizza object
const randomPizza = pizzas[Math.floor(Math.random() * pizzas.length)];
// construct a new pizza object with a name and random quantity
const pizza = {
quantity,
name: randomPizza.name,
};
return pizza;
}
// wrap function in log to see returned value:
console.log(generateNewPizza());
Test this in the console by refreshing the browser. You should see an object with a random pizza name and quantity:
name: "Margherita"
quantity: 2
Creating the orders
This leaves us with the random pizzas to create in the generateNewOrder function. This will be used to create an order, generate an order number, and call our generateNewPizza function:
// 1. set initial order number equal to orders +1 (+1 since arrays begin at zero)
let orderNumber = orders.length + 1;
function generateNewOrder() {
// 2. create empty pizzas array so we can build a random amount of items
let pizzas = [];
// 3. generate 1-5 order lines- can change if you prefer
const orderItem = Math.ceil(Math.random() * 5);
for (i = 1; i <= orderItem; i++) {
pizzas.push(generateNewPizza()); // push random pizza to array
}
// 4. Create order object
const newOrder = {
// SET ORDER NUMBER VARIABLE ABOVE
id: orderNumber,
pizzas,
};
// 5. push new order to orders array:
orders.push(newOrder);
// 6. Increase order number for next order
orderNumber++;
}
Then we need to call this function to generate our orders at the bottom of the file:
generateNewOrder();
You should now be able to start the game and see order number 4, this order should also be random. We will build on this next and generate new orders after a certain time delay. And also, re-visit JavaScript Math by drawing with the canvas.