import scene3d
import random
SKY = scene3d.Sky.PURE_SKY
GROUND = scene3d.Material.Grass.Bright
COUNT = 12
scene = scene3d.Scene()
scene.set_sky(SKY)
ground = scene.set_ground(length=30, width=30)
ground.set_material(GROUND)
ground.set_tiling(8)
colors = ['#e94560', '#f5a623', '#4488ff', '#44cc88', '#cc44ff']
def make_object(scene, x, z):
size = random.uniform(0.5, 2.5)
if size > 1.5:
shape = scene3d.Shapes.Box(width=size, height=size * 1.5, depth=size)
else:
shape = scene3d.Shapes.Sphere(diameter=size, segments=12)
shape.set_color(random.choice(colors))
shape.set_position(x, size / 2, z)
scene.add(shape)
for i in range(COUNT):
x = random.uniform(-10, 10)
z = random.uniform(-10, 10)
make_object(scene, x, z)Now Experiment!
You’ve covered a lot in Lesson 2. Here’s what you now know how to do:
- Repeat code automatically with
forloops andwhileloops - Make decisions using
ifstatements and comparison operators - Add unpredictability with
random.randint(),random.uniform(), andrandom.choice() - Group code under a name by defining your own functions with
def
The cell below is your sandbox. It starts with a scene that uses all four ideas: a function, a loop, an if statement, and random numbers. The rest is up to you.
Ideas to try: - Change the if threshold so large objects use a different color instead of a different shape - Add a second function — maybe make_tree from the functions lesson — and mix it into the loop - Add a while loop that stacks a tower of boxes in the center of the scene - Use random.randint to choose COUNT instead of setting it manually - Add @scene.on_frame animation: make the objects slowly spin, bob up and down, or change color when they get too big