======== Module I ======== .. index:: template for authors .. |a| image:: /images/all/blender-extended/modul-100.png Objectives ========== .. tabularcolumns:: | c | l | :border: none +-------+-------------------------------------------------------------------------+ | |a| | Large projects can no longer manage them in a file. The source code | | | will quickly become confusing. Therefore, there is, as in other | | | languages also, for Python a solution that is shown here. | +-------+-------------------------------------------------------------------------+ Instructions ============ :Tasks: 1. Move parts of the source code in a second file (levels.py) from. 2. Import the outsourced parts. 3. Check whether the program behaves, as previously working. 4. Add a third level in the file levels.py. One module for levels ===================== To separate level definitions from the code that creates the maze we create two files. The first one is named *levels.py*. From now on, a game designer could create new levels, while a programmer cares about the game logic. .. literalinclude:: files/levels.py :language: python :emphasize-lines: 0 The main module =============== Reusing code from other files (other authors/programmers) is achieved with the *import* statement. .. literalinclude:: files/sokoban_m1.py :language: python :emphasize-lines: 9,10 :linenos: Errors ====== Again and again, errors occur and it is important to find the cause. For example a small typo occurred. The errors are always shown as a **traceback** in the console. :: Traceback (most recent call last): File "/Users/.../sokoban.py", line 10, in ImportError: cannot import name Level_01 Error: Python script fail, look in the console for now... | The file path in this Traceback is shorten. Important is the line number, often indicating the main cause of the error. Also important is the type of error, in this case the *ImportError*, because Python is case-sensitive. So the Error will disappear, if you replace *L* with *l*. Connecting Python scripts with a Blender file ============================================= The classical way to find modules in Python is limited in Blender. The easiest workaround is to include the Python scripts into the Blender file. Step by step ============ 1. Create a new blend file. 2. Load every Python script. 3. For each file call the menu: Text | Make internal. .. image:: /images/all/blender-extended/make-internal.png Save the Blender file and all modules are available. External Editors ================ The internal Editor is not so bad, but if you like to use your prefered Editor, for example emacs, vi on Linux or PyCharm on Windows, you can edit the external Python scripts. A small icon is indicating, that you have altered the content of the file and you are forced to reload the script, starting with a right click on this icon. .. image:: /images/all/blender-extended/out-of-sync.png