Computer Science Homework(Python)

profileJoshuaTT

This work should be working on Blender 

Part 1: Creating the Monkey Head Grid

First, make sure you include the following at the top of your script file:

import bpy
from math import *

def selectAll():
    # select objects by type
    for o in bpy.data.objects:
        if o.type == 'MESH':
            o.select = True
        else:
            o.select = False
    return

def clearAll():
    selectAll()
    bpy.ops.object.delete()
    return

Then, write a Python function that, given an integer n, creates a n×n grid of monkey head objects:

  • First, set two of the three axes (e.g., x and y) at -n, and the third axis to 0
     
  • Use a pair of nested loops, each looping n times
     
  • Inside the inner loop:
    • create a monkey head (bpy.ops.mesh.primitive_monkey_add)
    • move it to (x,y,z)
    • set up the location of the next head by incrementing one of the axes
      • for example, if you are creating the grid on the x and y axes, x = x + 3
         
  • Inside the outer loop
    • after each completion of the inner loop (creating a row of heads), increment the other axis by 3 and reset the first axis to -n
      • for example, if you are creating the grid on the x and y axes, y = y + 3 and x = -n

Test your function by first clearing the 3-D view (i.e., by calling the clearAll function), then calling your function with the value 10.

Part 2: Rotating the Monkey Heads

Once your function from Part 1 is working, write another Python function to simulate the Peevish Postman Problem by rotating the monkey heads:

  • Select all of the monkey heads as a list variable, using bpy.context.selected_objects
     
  • Set n to the size of your heads list (i.e., use the len() function)
     
  • Set a rotation variable to 180 degrees in radians (use the function math.radians(180))
     
  • De-select all of the objects:
    for obj in bpy.data.objects:
        obj.select = False
     
  • Again use a pair of nested loops:
    • In the outer loop, loop from 1 to n (for example, loop i from 1 to n)
    • In the inner loop, loop from the current value of i to n by increments of i (for example, loop j from i to n in increments of i)
    • Inside, the inner loop, rotate the head at index j-1 by the rotation on the third axis
      • for example, if you created the grid on the x and y axes, rotate by the rotation on the z axis:

        heads[j-1].rotation_euler.z += rotation


    • 4 years ago
    • 60
    Answer(0)