Events

Start a new line at the end of the code and add this line:

game.onClick(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'll define a function, put_brick, then tell CodeCraft to call that function when the mouse is clicked.

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

The input parameter for this function 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 JavaScript 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 onClick 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 mouse click events.

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

When the game calls back our function, it gives the function one parameter, the location 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.onClick 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 ""