randint()
in CodeCraft
We use random integers a lot in CodeCraft. The random
module has a function called randint()
that makes it easy to generate random integers.
To use randint()
, we need to import it from the random
module. To save typing, we can comment out the line at the very top,import random
, and replace it with this line:
from random import randint
Now, let's try using randint()
in CodeCraft!
Example 1
Make a list of random integers:
lst = []
for i in range(5):
lst.append(randint(1,20))
print ( lst ) # [12,8,9,15,3]
Each time you run the above code, you should get a different list of numbers.
Example 2: build blocks at random locations with random material
Generating blocks at random locations would be easy with randint()
. For example, if you use randint(1, 20)
as the input value for the block's x
coordinate, the block will show up at random x
locations from 1 to 20.
Next, let's generate random materials.
materials
is a dictionary in which each material name is paired with a number from 1 to 88, so we can use the numbers from 1 to 88 when choosing the material. Let's use the function block_m(x,y,z,m)
for this purpose.
# random x, y, z, m
# 10 blocks with different materials at different locations
for i in range(10):
block_m(randint(1,20), randint(1,20), randint(-20,-10), randint(1,88) )
Each time you run the above code you will get a set of 10 different blocks at different locations.
Example 3: building columns using randint()
You can also generate columns of random materials with random heights. Let's use the function column_m()
:
for i in range(10):
column_m(i, -10, randint(1, 20), randint(1, 16))
(When I ran example 3, I didn't comment out the other examples and didn't reload the screen, so previous results are in the background.)
Example 3 generated ten random colored columns with random heights between 1 and 20.
Run all the programs a few times and see what you get! Can you explain why some of these columns below have different color segments?
Example 4: random way to go
In this example we will grow a plant, which is really a bunch of blocks "grown" in random directions. A random integer is used to control which way it grows into. 0: left, 1: right, 2: up. (The plant won't grow downwards, because that won't help it survive!)
x = 0
y = 1
for i in range(20):
game.set_block(Position(x, y, -30), 3)
direction = randint(0, 2)
if direction == 0:
x -= 1
elif direction == 1:
x += 1
else:
y += 1