Hello Every body,
Hi I'm stuck on a javascript problem. I have a set of instructions with declared variables and functions that is meant to simulate the game of snakes and ladders. I have used the instructions to attempt it but keep getting undefined results where the squres with the snakes and ladders are unrecognised? I was wandering if Anyone could point me in the right direction. Sorry it's such a long post. I have included my attempt at a solution below aswell.
INSTRUCTIONS
call the function rollDie and store the return value as the player’s score
write out the score
add the score to the player’s position
write out a message saying what square the player is on
call the function findIndexOf with suitable arguments to look for the index of the player’s position in the special squares array and store the value returned
if the index is not -1
set the player’s position to the number of the square at the same index in the connected squares array
write out a message saying what square the ladder has taken the player to
end if
write out a line break
<HTML>
<HEAD>
<TITLE>
Snakes and Ladders
</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
/*
*imitates a normal 6-sided die, by returning a random whole number between 1 and 6 inclusive.
*/
function rollDie()
{
return Math.floor(Math.random() * 6) + 1;
}
/*
*searches for a number in a number array.
*
*function takes two arguments
* the number to search for
* the number array to search
*function returns the array index at which the number was found, or -1 if not found.
*/
function findIndexOf(number, numberArray)
{
var indexWhereFound = -1;
for (var position = 0; position < numberArray.length; position = position + 1)
{
if (numberArray[position] == number)
{
indexWhereFound = position;
}
}
return indexWhereFound;
}
//ARRAYS that represent the board -- you do not need to change these
//array of special squares
var specialSquaresArray = [1,7,25,32,39,46,65,68,71,77];
//array of corresponding squares the player ascends or descends to
var connectedSquaresArray = [20,9,29,13,51,41,79,73,35,58];
//VARIABLES used -- you do not need to change these
//the square the player is currently on
var playersPosition;
//play is initially at START
playersPosition = 0;
//what they score when they roll the die
var playersScore;
//the index of the player's position in the special squares array or -1
var indexOfNumber;
MAIN PROGRAM - MY ATTEMPT!
playersScore = rollDie();
document.write('Your Score is: ' + playersScore);
playersPosition = playersScore + playersPosition;
document.write(' You are on Square ' + playersPosition);
indexOfNumber = findIndexOf(playersPosition, specialSquaresArray);
document.write(' ladder to square ' + connectedSquaresArray[indexOfNumber]);
document.write('<BR>');[/COLOR][/COLOR]
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Any suggestions greatly appreciated! Thank you.
Comment