Deutsch English |
YOU LEARN HERE... |
that event-driven programming is a new programming concept. Instead of giving commands to the Turtle with your program, you can control the Turtle with mouse clicks. |
EXAMPLES |
Mouse events are used to trigger mouse-controlled actions. The mouse clicks are recorded by the system and lead to a so-called callback function being called. This returns the coordinates of the mouse click and defines what should happen when the mouse is clicked. The callback function is registered as a named parameter of makeTurtle().
Program:
|
Program: from gturtle import * def drawStar(): repeat 9: forward(40) right(160) def onMousePressed(x, y): setPos(x, y) drawStar() makeTurtle(mousePressed = onMousePressed) hideTurtle() setPenColor("magenta") |
Program: from gturtle import * def drawPoint(x, y): global n moveTo(x, y) dot(5) n += 1 if n == nbCorners: fillPath() makeTurtle(mousePressed = drawPoint) hideTurtle() n = 0 nbCorners = InputInt("GibAnzahl Ecken an") setFillColor("red") startPath() |
REMEMBER... |
The new programming technique can be recognized by the fact that the function onMousePressed(x, y) is not called anywhere by your program. It is called by the system when an event occurs. We call such a function a callback function or callback for short. The variable n in the last example is called a global variable because it is used both in the main program and in the callback function drawPoint(x,y). A variable that is only used in one function is called a local variable. |
TO SOLVE BY YOURSELF |
|
ADDITIONAL MATERIAL |
YOUR FIRST GAME |
from gturtle import * def square(): for i in range(4): forward(60) right(90) def drawBoard(): for x in range(3): for y in range(3): setPos(60 * x, 60 * y) square() def drawDot(x, y): global player if player == 1: setPenColor("red") player = 2 elif player == 2: setPenColor("lime") player = 1 setPos(x, y) dot(45) player = 1 makeTurtle(mousePressed = drawDot) hideTurtle() drawBoard() It would be interesting to extend the game so that it automatically recognizes when one player has won or when the game is tied. |
TO SOLVE BY YOURSELF |
4*. |
|