1
$\begingroup$

When using Game Properties, you can change the value during the game.

Example: "prop" = 50 press r then "prop" -= 5

After pressing "r", the property would subtract 5 from the original number, and then the new number becomes the "original" number.

Is it possible to do the same sort of thing with a python variable? So that i can have a variable in my code set to 50 when the game begins, get changed when "r" is pressed, but not revert back to 50 when the script is run in the next frame?

Example:

Start the game

prop = 50

Press R (Just an example, not real code)

if keyboard.r = just_activated: prop -= 5

But when the script is run again, prop reverts back to 50

$\endgroup$

1 Answer 1

1
$\begingroup$

When using python in the game engine you can use a script or a module. While a script will be run from start to end, a module is a collection of functions that can be called indiviually, the "global" code in a module is run once when the module is first activated, which makes it a good place for a one off initialisation that you are looking for.

import bge

GameScore = 50
print('init once here')

def ChangeScore(cont):
    global GameScore
    ksens = cont.sensors["Keyboard"]
    sce = bge.logic.getCurrentScene()
    scoreDisplay = sce.objects['ScoreDisplay']

    for key,status in ksens.events:
        if status == bge.logic.KX_INPUT_JUST_ACTIVATED:
            if key == bge.events.UPARROWKEY:
                GameScore += 5
            if key == bge.events.DOWNARROWKEY:
                GameScore -= 5

            scoreDisplay['Text'] = str(GameScore)

Paste this into a textblock and end the blocks name with .py you then use a python controller, set to module and enter the textblock name without the py extension followed by the function name like sample.ChangeScore. You will see the "init once here" will only get printed once when the module is first run.

enter image description here

$\endgroup$
1
  • $\begingroup$ Thank you so much sambler! I never really understood modules as they dont always seem to work for me, but now they are much clearer! Thank you! :D $\endgroup$
    – christai
    Commented Dec 30, 2014 at 11:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .