Fly Catch Event Loop
To get this started, we can set up some details for the spider and get it appearing on the screen. We can then add in the event loop which will give us the main control flow of the program.
Basic Drawing
The spider needs a location, size, and shape.
- We can use a circle as the shape for now, and later replace this with an image.
- The location will need a distance from the left and top of the screen. To achieve this we can add two variables:
spiderX
to store the distance from the left of the screen. This can start at half the width of the screen.spiderY
to store the distance from the top of the screen. This can start at half the height of the screen.
- The size will not change, so we can set it as a constant called
SPIDER_RADIUS
.
As we will need the screen width and height, we can code these in constants called SCREEN_WIDTH
and SCREEN_HEIGHT
. We can then use these when we open the window, and when we initialise the spider’s location. These will also be useful later when we need to set the location of the fly.
We can capture this in pseudocode:
Loop until quit
With the basic details drawn, we can now place this within an event loop. This will loop while the user has not asked to quit, with each loop clearing the screen, drawing the game, and processing any events the user has performed. This is captured in the following flowchart.
If you follow the flowchart, you should be able to see how this will keep the program running. While nothing may be changing on the screen, the computer is looping over and over to check if the user has done anything. The logic is captured in the following pseudocode.
Notice how we put the drawing code inside the loop. Code this then run it and think about what is going on. The computer is running through that loop as fast as it can. Each loop it draws the game, clearing the screen, drawing the spider, and showing that to you. You see a static picture, but that is because nothing is changing…yet.
Create a new project for this, and code the program’s instructions using the above pseudocode as your guide. You want to make sure you have this working before continuing. When it works, you should see the “spider” (a black circle) in the center of the screen. The window should stay open until you close it.
We will need to use the following SplashKit methods to get this working:
- Quit Requested - This returns true when the user has asked to close the program. You can use this in the loop
- Process Events - This listens to events such as keystrokes, mouse clicks, quit, etc.
These methods have the following signatures:
There is an example of this logic on the while loop page, and remember you can check our version of the code in the campsite reflections section if you get stuck.