'Function to simulate snakes and ladders with 2 players

I have an assignment to simulate snakes and ladders in R without using libraries.The board has 100 squares and u can only win if u reach the square 100, for example if you are in square 97 and roll 5 u reach 98 because u go forward 3 steps to 100 and bounces back 2 steps. My problem is to make the function to run the game and see who wins the games most likely.the game is with 2 players and thats my code:

> nplayers<- 2
> SnakesAndLadderS<-
+   function(nplayers)
+   {
+     transitions <- rbind(
+       c(4,25),
+       c(13,46),
+       c(27,5),
+       c(33,49),
+       c(40,3),
+       c(42,63),
+       c(43,18),
+       c(50,69),
+       c(54,31),
+       c(62,81),
+       c(66,45),
+       c(74,92),
+       c(76,58),
+       c(89,53),
+       c(99,41))
+     
+     
+     transmat <- 1:106
+     names(transmat) <- as.character(1:106)
+     transmat[transitions[,1]] <- transitions[,2]
+     
+     lastpos <- 0
+     curpos <- history <- NULL
+     while(all(curpos < 100)) {
+       curpos <- lastpos + sample(1:6, nplayers, repl=TRUE)
+       curpos <- transmat[curpos]
+       if(any(curpos > 100)) curpos[curpos > 100] <- lastpos[curpos > 100]
+       
+       lastpos <- curpos
+       history <- rbind(history, curpos)
+     }
+     
+     history
+   }
r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source