You can allow the user to specify how many penguins there should be with the prompt()
method:
var penguinCount = prompt("How many penguins should there be?");
In order to randomise the type of penguin, you'd call Math.random()
to grab a random number between 1
and 8
, and affix that number to the end of the word penguin
when creating your elements.
The following will create as many penguins as is specified by the user, each with a random class between penguin1
and penguin8
:
for(var i = 0; i < penguinCount.length; i++) {
document.createElement("penguin" + Math.ceil(Math.random() * 8));
}
The same can be done for the snow mounds as well; just make use of a second variable :)
However, assuming the only difference between the penguins is their image, it would be to make use of a single class of .penguin
, and instead randomise the background image when creating the element for said penguin, which can be done with the style
property:
for(var i = 0; i < penguinCount.length; i++) {
var penguin = document.createElement("penguin");
penguin.style.backgroundImage = "url('penguin'" + Math.ceil(Math.random() * 8) + "'.png')";
}
Doing the latter would mean you'd only need a single class for all the penguins, significantly cutting down on your CSS :)
Hope this helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…