Game Development Reference
In-Depth Information
Converting This to Code
We can have the board set up like a class that would hold information about the snakes and ladders,
as in the preceding code where we randomly stored a value to the board. However, for now, we shall
store this code in an array. Each record in this table shall have two fields: a start and an end square.
local tableSquares={
{startPos=20, endPos=58},
{startPos=47, endPos=68},
{startPos=55, endPos=76},
{startPos=69, endPos=90},
{startPos=78, endPos=97},
{startPos=22, endPos=5},
{startPos=35, endPos=12},
{startPos=51, endPos=34},
{startPos=80, endPos=57},
{startPos=89, endPos=66},
{startPos=99, endPos=76},
}
We also need to have an array to hold the player's locations, so we create an array:
local players={}
local playersInGame=0
local playersTurn=1
Because this is an array, we can add as many players are we want by simply inserting their record
into the table. Let's create a function to add a new player:
function addPlayer(playerName)
playersInGame=playersInGame+ 1
table.insert(players, {name=playerName, square=0, isPlaying=true})
end
What this function does is first increase the number of players represented by the playersInGame
variable by 1, and then add a record for the player that includes fields called name , square , and
isPlaying . The name is taken from what we pass to the function, and we set the player to be on
square 0 and also set isPlaying to true . So, we can track the players and check if they are still
playing or if they have already finished the game.
We can always get the number of players from the array using the # operator, but when players finish
the game, we reduce playersInGame to reflect how many are still in the game instead of looping
through all of the players and checking if they are in the game or not.
We will need another function that returns a dice roll for us, similar to the one we wrote earlier:
function rollDice(maxSides)
local maxSides=maxSides or 6
return math.random(1,maxSides)
end
 
Search WWH ::




Custom Search