Game Development Reference
In-Depth Information
function startGame()
if #players<2 then return end
-- Need to have at least 2 players
-- This is our check that if one player is left, then the game is over
while playersInGame>1 do
local thePlayer=players[playersTurn]
if thePlayer.isPlaying == true then
print("it is " .. thePlayer.name .. " turn")
local diceRoll=rollDice()
print("and rolled a " .. diceRoll)
movePlayer(playersTurn, diceRoll)
end
-- It's the next player's turn
nextPlayer()
end
print("Game over")
playersTurn in the preceding function block, but we need to make sure that
is in the range of 1 and the maximum number players. We also need to ensure that the
playersTurn=playersTurn+1
-- Loop back to the first if the current player was the last player
if playersTurn>#players then playersTurn=1 end
if players[playersTurn].isPlaying == false then
nextPlayer()
end
-- All done, nothing more to do really...
end
Put all of the code together, and we have an automatic-running game of Snakes and Ladders. The
idea behind this code is to teach you how to create functions that are modular, and that it is mostly
Lua code that runs the app; the framework is more of glue that allows the glitter to stick.
In case you are wondering why we do not see any output to the terminal window, it is because we need
to start the game. We can quickly create a function called restart , which will set all the variables to
the initial values and then start the game for us:
function restart()
init()
startGame()
end
To run the game, we simply call restart() , and the game runs in the console (see Figure 4-4 ).
Search WWH ::




Custom Search