Edit a script as you play (Python Trick)

Hey bge scripters, this is something that others might find useful if you want to edit scripts without restarting the game engine.

I used this to tweak YoFrankie gliding, it works especially well if you can play your game with a joystick (gamepad in my case), since then you dont even need to switch the window focus from the editor.

You simply copy your script into an external python file (say game_test.py), make sure there is a main() function that runs the full script, put it in the .blender/scripts directory, and replace the text in the game engine with…


import game_test
reload(game_test) # reloads the module from the file
game_test.main()

When you save the updates will be applied immediately.
reload() will slow things down a little - reloading all the time but its well worth it for testing game logic - you get feedback immediate, script errors, dynamics etc.

Not sure if this is a common thing to do, so thaught Id post.

Neat trick, I usually have my python scripts external so this will pretty good.

Yeah, that could be very useful… Thanks!

thats a great trick :eek:

why havent i thought of that ^^

i was tweaking a lot the last days and thought i’ll go mad.

greetings
manarius

sweet!! (that’s all I have to say)

So does this make it possible to implement an in-game console?

I’ve always liked editing within the game engine. It makes the code’s problems immediately apparent.

Another thing I like to use is the exec “code” tool in python. It runs strings as python code. So exec ‘print “Hello”’ prints Hello. This is useful in the game engine. You can set positions, orientations, levels, etc. In order to use it in a simple, chaotic way, use a keyboard sensor, have it write the thing to a string property and run a python script with exec own.YourPropHere. There are much better implementations, but this is a very simple use.

Hi, that’s a nice trick but I wasn’t able to get it to work.
Download this file: http://www.porcaro.org/reloadproblem.zip
and follow these directions to see what is going on:

  • Make a link from your blender scripts folder with
    named scalealpha pointing to this folder. From a
    Unix shell do this (for example):

    ln -s /Users/nick/alphatest/scalealpha /Applications/blender.app/Contents/MacOS/.blender/scripts/scalealpha
    
  • Open the attached .blend, hit P then hit X, then change something
    in the scalealpha.py script in this folder then hit X – again you should see
    the result of your change in the console (or whatever you intended).

But it doesn’t work for me on a macbook pro running 10.4.11 running blender 2.48a … the
script doesn’t actually reload.