This article covers the basic use of events in Small Basic.
An event is something that happens independently of the normal flow of instructions in a program.
Often this is when something happens as a result of user interaction, such as when a key is pressed or the mouse is moved or clicked.
Within Small Basic an event method is shown in the intellisense with a lightning symbol shown below.
An event is initialised by defining which subroutine should be called when the event occurs. The assignment of an associated subroutine needs to be set only once. When the event occurs the associated subroutine will be called.
The following is a simple event that creates a pop-up when the mouse is clicked inside the GraphicsWindow.
Because an event can occur at any time the main program will be doing something else. The event will call its associated subroutine at the same time as the main program is running.
Several points to note about events:
If an event is called again before it has finished working the last time, it will be queued until the previous event has finished. This can result in long delays before all of the events are processed if the event is fired often (like a mouse move) and the
event subroutine is slow.
If the event subroutine and the main code both call a common subroutine, then this subroutine may be called by two pieces of code at the same time with unpredictable results.
If the event subroutine and the main code both share variables, then since the two codes are changing variables at the same time, strange behaviour may occur.
The solution to some if the issues above is to force only one piece of code to be running at a time. We want the main code to run everything in sequential order.
An infinite While loop that keeps running and just processes the results of events is a common programming technique, especially for action games. It is called a ‘game loop’ or ‘event loop’.
We want a flag to be set when the event occurs and use this flag inside the main game loop, where everything will be run in order without the issues of multiple pieces of code running at the same time. A flag is just a variable that is either true or false
or has a simple value like 0(false) and 1(true).
The methodology is to:
The following examples show this for the first two cases shown earlier.