Using Random Numbers
Games wouldn’t be much fun if they were always exactly the same, so Scratch enables you to use random numbers in your scripts. To keep players on their toes, we can make the alien appear at a random X position at the top of the screen.
Click your alien in the Sprite List, and then drag in the Green Flag Control block. As with the other sprites, we need to create a script that resets the alien to its starting position. In the case of the alien, the sprite switches to a different costume when it’s hit, so we should make sure it is using its normal costume at the start of a new game and that it is visible onscreen.
For its screen position, the alien needs to have a Y coordinate of
150, which is near the top of the screen. We don’t want to use the full width of the Stage because it looks odd when half the alien is off the edge of the Stage. From experimentation, I found that the ideal starting X position for my alien is between
180, but yours might vary depending on its size.
Drag in the Motion block you used previously to go to a particular X and Y position. If you click Operators at the top of the Blocks Palette, you can find a block to pick a random number from
10. Drag this block into the hole where you would normally type the X position, and then change the numbers in the random number block to
Figure 11-9 shows your initial script for the alien. You can use the green flag to test whether it works and positions the alien at a random ...