Blender Python script to create animation with numerous cubes randomly changing colors and going up and down

OK, I see that the title with the randomly changing cubes grabbed your attention. Everyone likes randomly changing colors.
The script has some comments to aid in understanding. I am just learning about this so there are probably more efficient ways of doing the same. It worked though.

The code below took probably around 12 hours to render on my 3-4 year old PC (HD, 25fps). I would practice with smaller values.


import bpy
import random
# randloc states how high the cubes will go
randloc = random.randint(-3,3)
# frame_num shows every how many frames the cube location will be set
frame_num = 10

# loop through x and y coordinates, adjust to your liking. range(1,20) for x and y will fill up a nice 20x20 area with cubes
# note: z coordinate is set with randloc
for xposition in range(1,20):
    for yposition in range(1,20):
	#starting frame
        frame_num = 10
	#add cube
        bpy.ops.mesh.primitive_cube_add()
        cube = bpy.context.object
	# name the cubes uniquely
        cube.name = "Cube.00"+str(yposition)
        cube_do = bpy.data.objects[cube.name]
	# create a default material called visuals. without this you cannot set color
        mat=bpy.data.materials.new('visuals')
	# Set length of animation. With 25 fps mine was around 4 minutes with 600 set here
        for frames in range(1,600):
            # set which frame is being changed
            bpy.context.scene.frame_set(frame_num)
            # give the material a random color and assign to cube
            mat.diffuse_color = (random.random(),random.random(),random.random())
            cube.data.materials.append(mat)
            # set cube position
            cube_position = (xposition*2-20,yposition*2-20,random.choice([2,0,-2]))
            cube_do.location = cube_position
            # set the location to the frame in question
            cube_do.keyframe_insert(data_path="location", index=-1)
            # set the material and color to the frame in question
            cube_do.active_material.keyframe_insert("diffuse_color")
            # increment the frame
            frame_num += 10

I set the camera position manually to focus in on the generated cubes.

Here is the result in a music video: