App Lab Help Randomizing

Good morning, I have a student who would like to create code that chooses a random animal out of 30 different ones and make it operate so when the hatch button is clicked the egg opens and reveals an animal.

I’m thinking a hide element is involved and randomizing block?

Thanks for any input. https://studio.code.org/projects/applab/2934196a-c839-4c3f-b158-397b6d1dd970

Greetings @jcostanza,

Disclaimer; I am not that knowledgeable about applab, but it should follow the same logic as gamelab.

I have discovered a solution involving the use of arrays and objects.

  1. You have to create an array with the elements being objects like this:
var animalList = [
  {name: "Lion",img:"download---2026-01-21T112454.158.jpeg"}
]

The reason for the object however, is that you need to fill 2 values in for the image block.

  1. Create a variable with a random block
var randomAnimal = randomNumber(0, 29) //i've calculated there will be 30 animals, however since arrays start at 0, it ends at 29
  1. Now, to put into practice, we reassign the randomAnimal value each time the player clicks hatch and set the image to the randomAnimal value’s objects:
onEvent("HatchClick", "click", function( ) {
    animalRandom = randomNumber(0, 29);
    image(animalList[animalRandom].name, animalList[animalRandom].img);
});
  1. This step explains how to have only one image on the screen at all times once hatched. This step is optional.
    Set a variable check whenever the egg is hatched. If it’s hatched already, delete the past animal. Then if it’s not hatched yet, create a brand new one from in account for the animalRandom var.
onEvent("HatchClick", "click", function( ) {
  if (hatched) { //if hatched, delete the previous random animal and hatched is set false
    deleteElement(animalList[animalRandom].name);
    hatched = false;
  }
  if (!hatched) { //if hatch false, randomize the animalRandom var and create an image based off the selected element's id and image link
    animalRandom = randomNumber(0, 29);
    hatched = true;
    image(animalList[animalRandom].name, animalList[animalRandom].img);
  }
});

Full Demonstration: App Lab - Code.org

You indicated the topic as being CSD unit 3 which would use Game Lab. Another way to possibly implement this would be to use 30 animations (graphics). If you name them with a number, you can assign a number to a random variable and assign that animation to be the costume or animation for that sprite.

It’s kind of a shortcut, but it works well.

Hope this helps!

Mike