Level 03 Lesson 03 [Random Values]

Every programming language has commands that allow us to generate random numbers.  Random numbers can be used along with conditional statements to give games more variety.  This lesson will give you an introduction to how you can start using random values with conditions.

Part A – Setting Variables to Random Values
To save time, a pre-made game project has been made that will help us learn about random values and variables. Go the resources folder and open the game project called L03-03-A-StartHere.gmk

Watch the video: 03-03-A
Done File: L03-03-A-Done.gmk


Challenge 1 – Random in Step Event
Continue using the project you have open and try and complete the following.

a)  In the step event of the banana, pick a random number between 0 and 30.  If the number is a 1, change the direction of the banana to a random value between 0 and 359. If successful, this will have the banana changing directions every second or so.

b) In the step event of the burger, add onto the existing code. Pick a number between 0 and 1000. If the number is 10 or less, set the x and y variables of the burger to new, random values (the values should be between 0 and 400 (the size of the room) ). You should see the burger ‘jump’ to a new position in the room every 3 seconds or so if you complete this properly.

Challenge 1 Solution
Watch the Video: 03-03-X1Solution
Solution File: L03-03-X1-Done.gmk


Part B – Random Values, Random Actions
To save time, a pre-made game project has been made. Go the resources folder and open the game project
called L03-03-B-StartHere.gmk

Watch the video: 03-03-B
Done File: L03-03-B-Done.gmk


Challenge 2 – Random Generation

Use the done file from the last video, L03-03-B-Done.gmk.  Lets add three new things to add to the game.

a) When you press the “M” key, make the player randomly decide whether to start moving up, down, left, or right at a speed of 4.

b) When the player touches the chest, destroy the chest and randomly decide whether to create a coin or some gold at that location.  Code it so that the chance of a coin appearing is greater than the chance of some gold appearing.

c) When the ghost is hit by an arrow, there is a 1/5th chance that the ghost is destroyed (that’s a 20% chance).

Challenge 2 Solution
Watch the Video: 03-03-X2Solution
Solution File: L03-03-X2-Done.gmk