How globals works in mouse interactions functions (python)

Hi guys !

We’re actually trying to create an interface in processing to play chess.
The problem is the following:

  • if the user clicks on something that isn’t empty (mouseClicked()), a global var named “pieceClicked” turns into a boolean True
  • in the other function mouseDragged(), it normally catches the boolean and print the image on mouseX, mouseY
  • but we tried to print these values in draw(), mouseClicked() then mouseDragged():
    - draw() is True as default
    - mouseClicked() returns True
    - mouseDragged() is False (??)

The global is announced in the draw()

Perhaps you need to use global in your mouse event functions?

state = 'idle'

def draw():
    global state
    if state != 'idle':
        print('{} on frame #{}'.format(state, frameCount))
        state = 'idle'

def mouseClicked():
    global state
    state = 'click released'

def mouseDragged():
    global state
    state = 'dragged with button down'
1 Like

Hello, @nuanz, and welcome to the Processing Foundation Forum!

See What are the rules for local and global variables in Python?. Though that references Python 3, and Processing Python Mode uses Python 2, the rules discussed there apply to both.

Essentially, if you assign a value to a variable with a function, and you wish that assignment to apply to a global variable, then declare the name of that variable as global within that function. If you do not declare it as global within that function, then you will have created a local variable by that name within the scope of the function, even while there is also a global variable with the same name outside the scope of that function.

2 Likes