We will build a game similar to the classic Whac-A-Mole game. The user will need to tap on the orc that shows up randomly on the screen within a limited time.
Canvas, Sprite, Label, Horizontal Arrangement, Button, Clock, TinyDB, Sound
Clock – Disable both clock by default
Sprite image – https://csplayground.io/wp-content/uploads/2021/01/skull.png
Hit sound – https://csplayground.io/wp-content/uploads/2021/01/hit.wav
The default value of CountdownClock’s time interval property is 1000, which means the event will trigger every 1000 milliseconds (one second). When the start game button clicked, we enable the CountdownClock to start the clock. Every time the clock event is triggered, update the countdown value on the screen and reduce the value of the counter. If the countdown value equals zero, disable the clock.
Moving the Sprite
Create a procedure and in the procedure, we move the sprite to a random X and Y position from 0 to the end of the canvas. Similar to the countdown timer, enable the MoveSpriteClock when StartGameButton click. In the MoveSpriteClock timer event, we call the moveSprite procedure. If the countdown equals zero, we stop the clock.
Create a variable to keep track of clicks on the sprite. Use the canvas touched event, check if the sprite is touched. If so, increase the value of the score and update the ScoreLabel. The touchedAnySprite parameter is a Boolean value.
Reset Game State
Create a procedure to reset the game states when prior to game starts.
Make Sprite Clickable Only During Gameplay
Create a variable with a Boolean value to keep track of the current state – started (true) or end (false). Add an if statement to the canvas touched event so that score will only be updated when the game has started. In the below example we used a compound operator AND to join two conditional expressions.
Update the game state when the countdown ends. Here, the code was refactored into a procedure.
Sprite Clickable Only Once Per Interval
Create a variable isHit to keep track if the sprite is hit within the time interval. Modify the canvas touched event so that the score will only be updated when all three conditions are satisfied.