Game Development Reference
In-Depth Information
Throwing a Die
In some RPG-style games, a coin flip might not be enough. You might want to have more possible
values than either 1 or 2—something that would emulate the roll of a die. The most common die has
six sides, and the numbers that one can get are in the range of 1 to 6.
local theDice=math.random(1,6)
print("we got ", theDice)
In RPG-type games or board games of a similar genre, the dice are often nonstandard and could
have more than six sides. It is just as easy to simulate that as the previous example. The only change
that we need to make is the maximum value that we can get on the die. For example, for a 20-sided
die, we'd use this:
local maxValue=20
local theDice=math.random(1,maxValue)
print("we got ", theDice)
In case you want multiple rolls, you can simply change this into a function and get the dice-roll values:
function diceRoll(maxSides)
local maxSides=maxSides or 6
return math.random(1,maxSides)
end
In the preceding example with inc and dec , you might have noted that we used a nifty feature of
Lua that allows for assigning a default value to a variable. In the diceRoll function just shown, if
the function is called without any value (i.e., the maxSides parameter is nil ), then the second line
creates a local variable called maxSides and assigns it the value of the parameter maxSides (or 6 if the
parameter is nil or missing).
Using Flags
This doesn't refer to the flag that we all recognize flying from the flagpole. The flag in reference
here is instead a variable that holds the value true or false . For example, in a game, one flag could
indicate whether you have a treasure chest's key or not; if you have the key, then you can open the
treasure box, but if you don't, then you can't. So the code would check if you have the key or not
and allow you to open the treasure chest accordingly.
function openTreasureChest(withKey)
if withKey == true then
print("The treasure chest opens")
else
print("Nothing happens, you are unable to open the chest")
end
end
local hasKey=false
openTreasureChest(hasKey)
hasKey=true
openTreasureChest(hasKey)
 
Search WWH ::




Custom Search