Previous |
Next
Using a Trap
The applications that we discussed thusfar run endlessly. However, you may want to write commands that stop under certain conditions. For instance, in games you may want a level to be finished when a certain amount of time has passed or a certain score has been reached. To stop commands, you can use
traps. In this section, you will learn how they work.
We will make a game that stops after a certain amount of time. The game can be made using the macros we made in the drawing application. This very basic game will work as follows: two players pick an object, red or blue. When the game starts, the player has to light as many cells as possible in his color with his object within 15 seconds. After 15 seconds, the application will stop and the players will not be able to light up any more cells. Such a game would look as follows:
//
Right-click to download this codeimport "tagtiles.esp"
main = (stampAlot)
stampAlot = (
trap Game (
(waitTime 15000; exit Game) |
handleBlue |
handleRed
)
)
handleBlue = (
handleColor isBlueBlock blue
)
handleRed = (
handleColor isRedBlock red
)
handleColor obj clr = (
loop (
await (tagEvent down obj);
drawShape (Cell lastTagCoord) clr
)
)
Note how we reused quite some code from drawingApp3.esp. Furter note how we have made use of the a trap. With trap, you first write a name, and then a block of code between brackets, like this:
trap MyName (
... //the body of the trap
)
The name of the trap is called the trap label. The block of code between the brackets is called the body of the trap.
The trap works as follows: when a trap with label MyName is started, it runs the Command in the body, until exit MyName is reached.
For our stampAlot application, this means the body of trap Game will be stopped when the application has waited for 15 seconds, because after 15 seconds exit Game will be reached.
Exercise
Change the application such that it will stop after 5 moves, rather than after 15 seconds. Compile and test your application.
Previous |
Next