Game Development Reference
In-Depth Information
We can get the number from a dice roll, and now we need to move the player based on that dice roll.
Let's create the function that moves the player based on the dice roll:
function movePlayer(playerNo, paces)
if paces<1 or paces>6 then return end
-- Just to make sure that we do not get an invalid number of paces
if playerNo>#players or playerNo <1 then return end
-- Just to make sure that we do not get an invalid player number
if players[playerNo].isPlaying == false then return end
-- Make sure that the player is still playing
local square=players[playerNo].square+paces
if square>100 then return end
-- You need to have the exact paces to reach the 100th square
if square == 100 then
-- Reached the 100th square, won or finished the game
player[playerNo].isPlaying=false
print("Player " .. players[playerNo].name .. " has completed the game.")
playersInGame=playersInGame - 1
end
-- Check if we have reached a snake or a ladder
local square1=specialSquare(square)
if square1 then
print("Got a special square on " .. square .. ", leading to " .. square1)
end
players[playerNo].square=square
-- The player is now at the new square
print("The player " .. players[playerNo].name .. "is now on sqaure " .. square)
end
In the preceding function, movePlayer takes two variables, a playerNo and paces . First, we do a few
checks to make sure that we do not get any invalid parameters. First we check the paces, which
have to be in the range 1 to 6, as this is what we get from the dice roll. If the paces are invalid, then
we return from the function. Next, we check if the playerNo is valid, which should be between 1
and the number of elements in the players array. We also check if the player is still in play and has
not completed the game. We check that using the player[playerNo].isPlaying flag, which tells us
if the player is still playing or not. After all these checks, we are sure that the player is valid and in
play, and that the number of paces is valid too. We then store the value of the square the player is at
with the paces into a variable called square . According to the game rules, the player can only win by
arriving at the 100th square, so if the player is on 99 and rolls a 2, they cannot move; they must roll a
1 to win. The first thing we do is check if the total is greater than 100; if it is, then we return from the
function (i.e., do nothing). If the total is 100, then we flag the player as having finished and set the
isPlaying flag to false . We also display the message that the player has completed the game.
Since this is Snakes and Ladders, we also need to check if the player has reached the head of a
snake or is at the bottom of a ladder. When you arrive at the head of the snake the player moves to
the tail and if the player arrives at the bottom of the ladder, the player moves to the top of the ladder.
Search WWH ::




Custom Search