Mouse Click Events

Introducing game.on_click()

Now start a new line and type in:

game.on_click(put_brick)

Let's see this function in action. Click 'run' and enter the CodeCraft world. Move the mouse around, when you see a highlighted block, click the mouse. A brick block appears! Move around and click to build some more blocks. Magic!

Listen to the mouse click events

Let's make the computer perform an action when you click the mouse. In order to do this, we need a function representing the action such as: put_brick, then 'tell' CodeCraft to call that function when the mouse is clicked.

The function game.on_click() registers another function to respond to mouse clicks.

The input parameter for this game.on_click() is not an ordinary value like a number or a string. Instead it's put_brick, a function that was previously defined. A function is a type of object in Python and can be used as an input parameter for another function.

Note: put_brick is used by its name only, without the parentheses, because we want to pass the function object to on_click as an argument so that put_brick can be called later whenever you click the mouse. If you add parentheses to it, then it will be called immediately and will not respond to the later mouse click events.

put_brick is a callback function, because we send it to the game and expect it to be called back later.

Remember in the beginning of this lesson: we defined action(p, cb) that used put_brick as the callback, providing p (a Position object) as argument for put_brick. So we know the new brick block is put at p.

Here,when the game calls back put_brick, it automatically gives the function one parameter, the location(a Position object) of the highlighted block. That's how we know where to build the block in put_brick function.

Conclusion

Overall, game.highlight('air') helps us see the mouse's location. When game.on_click is called with put_brick as an input value, the event 'mouse click' will trigger put_brick into action and build a brick block at the mouse's location.

results matching ""

    No results matching ""