Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am completing the project: https://googlecreativelab.github.io/coder-projects/projects/pop_up_penguins/ which allows a user to click on 8 penguins within a page. However i'm trying to populate the page in javascript rather than html such that a player can easily adjust the number of penguins within the game.

I was thinking to first build an array from some user selected number.

penguinarray[count];

Then use a for loop to repeatedly place each penguin based on the size of the array.

for(var i = 0; i < penguinarray.length; i++) {
    document.createElement("penguin1");
}

Im not sure however how I can still randomize all the different types of penguins and the snow mounds from the 8 available, or allow the page to change given a different number of penguins.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
153 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...