fa-labyrinth

Übersicht: Python & Blender


Objectives

This station is a repetition of techniques already shown. But wait, it is also the starting point for a game that we build in the End of these course. It is named »Sokoban«. If you don't know this game you can read more about it at Game Sokoban

Instructions

Tasks:
  1. Construct your own level.
  2. Create objects with different shape for each symbol.

Labyrinth

Our starting point is a maze build out of cubes.

blender-basics/f-labyrinth/labyrinth.py (Source)

 1 #! bpy
 2 """
 3 Name: 'labyrinth.py'
 4 Blender: 27x
 5 Group: 'Example'
 6 Tooltip: 'Creating a maze'
 7 """
 8 import bpy
 9 
10 level_00 = ["###################",
11             "#.                #",
12             "#        $        #",
13             "#                 #",
14             "#                 #",
15             "#        @        #",
16             "#                 #",
17             "#                 #",
18             "#                 #",
19             "#                 #",
20             "###################"]
21 
22 
23 level_01 = ["    #####           ",
24             "    #   #           ",
25             "    #$  #           ",
26             "  ###  $##          ",
27             "  #  $ $ #          ",
28             "### # ## #   ###### ",
29             "#   # ## #####  ..# ",
30             "# $  $          ..# ",
31             "##### ### #@##  ..# ",
32             "    #     ######### ",
33             "    #######         "]
34 
35 
36 def sokobanLevel(level):
37     """Create a maze by adding cube objects"""
38 
39     cols = len(level[0])
40     rows = len(level)
41 
42     for row in range(rows):
43         for i in range(cols):
44             if level[row][i] == '#':
45                 bpy.ops.mesh.primitive_cube_add(location=(row*2, i*2, 0))
46 
47 if __name__ == '__main__':
48     sokobanLevel(level_00)

Iterate with for

The function len gives us the number to iterate in a for loop through the lists.

blender-basics/f-labyrinth/labyrinth.py (Source)

    cols = len(level[0])
    rows = len(level)

Comparison

With each comparison we decide to generate a new object otherwise nothing happened.

blender-basics/f-labyrinth/labyrinth.py (Source)


    for row in range(rows):
        for i in range(cols):
            if level[row][i] == '#':
                bpy.ops.mesh.primitive_cube_add(location=(row*2, i*2, 0))

Function call with parameter

The function is now called with one of the available levels (level_00, level_01,level_02...).

blender-basics/f-labyrinth/labyrinth.py (Source)

if __name__ == '__main__':
    sokobanLevel(level_00)

Result of the script

/blender-basics/f-labyrinth/labyrinth1.png

View from top...

/blender-basics/f-labyrinth/labyrinth2.png

View from an other perspective ...

Comments