Use randint() in CodeCraft

We use random integers a lot in CodeCraft. random module has a function randint() that's easy to generate random integers.

To use randint(), we need to import it from random module. To save typing, we like comment out the line at the very top,import random, and replace it with another way to import,

from random import randint

Use randint() in CodeCraft

Example 1:

Make a list of random integers, then use them to build blocks

lst_y = []
for i in range(5):
    lst_y.append(randint(1,20))
print ( lst_y )            # [12,8,9,15,3]

for i in range( len(lst_y) ):
    block(i, lst_y[i], -20, 1)   # brick blocks

Run the above application, we will have 5 brick blocks at random y locations (1 to 20), each time we run again, these locations will change, so you get different blocks.

Example 2:

A different way to generate blocks at random locations:

# 10 blocks at random x, y
for i in range(10):
     block(randint(1,20), randint(1,20), -20, 76)      # yellow blocks

# diamonds in the sky (blocks at random x, y, z)
for i in range(10):
     block(randint(1,20), randint(1,20), randint(-20, -10), 3)      # diamond

See the image, the brick blocks have random y values(1-20), the yellow blocks have random x and y values(1-20), the diamonds have random x,y (1-20) and random z (-20 to -10):

random materials

materials is a dictionary, each material name is paired with a number. So we can try random integer from 1 to 76 when choosing material value.

Example 3:

# at x:1,3,5,7,9, just above ground (y=2) generate a line of random material blocks

for i in range(1,10,2)
    block(i, 2, -20, randint(1,76))

# use randint() for x and m, two lines of blocks
for j in range(10):
    block(randint(1,10), 10, -20, randint(1,76))
    block(randint(1,10), 8, -20, randint(1,76))  

# random x,y,z, and m
# 10 different material blocks at various (x,y,z) locations
for i in range(10):
    block( randint(1,20), randint(1,20), randint(-20,-10), randint(1,76) )

# each time you run the above app you will get a set of 10 different blocks at different locations.

Can you recognize the 3 sets of blocks generated by different for loops

Turn to another angle, it's more obvious

Example 4: It's easy to generate some random height columns of random materials:

for i in range(10):
    column(i, -10, randint(1,20), randint(39, 50))

(When I run the above example 4, I didn't comment out previous examples and didn't reload the screen, so previous results are at the background, also, do you notice the random blocks increase due the second run?)

Example 4 generated ten random colored columns of random height(1-20), the shulker color blocks are easy to count numbers, see in the picture:

Run all the programs a few times, guess what you'll get? take a look, see if you can explain why some columns have various color segments:

results matching ""

    No results matching ""