O'Reilly logo

Raspberry Pi For Dummies by Mike Cook, Sean McManus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 and 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 1 to 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 -180 and 180.

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required