14.4. Using Random NumbersΒΆ
We can generate random numbers in Python using the randrange
function in the random
library. This function takes an optional starting value (inclusive) and the ending value for the range (exclusive). We can use random numbers in games to add an element of chance. We can also use random numbers to move the turtle to random positions as shown below. We are using conditionals to alternate the drawing color each time the turtle moves.
Can you modify the code above to use 3 different colors? You can use num % 3
to give you 3 possible results.
- randX = random.randrange(minX, maxX)
- This will range from the minimum x value (inclusive) to the maximum x value (exclusive). It will cover the whole width of the drawing area.
- randX = random.randrange(0, maxX)
- This will range from 0 to the maximum x value (exclusive). It will cover the right half of the drawing area.
- randX = random.randrange(minX, 0)
- This will range from the minimum x value (inclusive) to 0. It will cover the left half o the drawing area.
What could you use to limit the x values to just the left half of the drawing space (screen)?
In the first section this chapter we created the chevron image on the left using turtles. Modify the code to create the stampped image on the right. The turtles will stamp/draw in blue and green. The color will be chosen at random.