在R中模拟蛇和梯子
我是R的初学者,我必须在R中模拟蛇和梯子游戏进行作业。董事会有100个正方形。唯一的获胜广场是100,例如,如果您在Square 98上并滚动一个6,您将向前2到100,然后将4个空间反弹到96。矩阵,并编码获胜条件。这是我到目前为止的代码:
snakesNladders <-
function()
{
transitions <- rbind(
c(40, 3),
c(4, 25),
c(27, 5),
c(13, 46),
c(43, 18),
c(54, 31),
c(33, 49),
c(99, 41),
c(42, 63),
c(66, 45),
c(50, 69),
c(89, 53),
c(76, 58),
c(62, 81),
c(74, 92))
transmat <- 1:100
names(transmat) <- as.character(1:100)
transmat[transitions[,1]] <- transitions[,2]
firstpos <- 0
curpos_player1 <- NULL
curpos_player2 <- NULL
while(curpos_player1 & curpos_player2 < 100) {
curpos_player1 <- firstpos + curpos_player1 + sample(1:6, 1, replace=TRUE)
curpos_player2 <- firstpos + curpos_player2 + sample(1:6, 1, replace = TRUE)
curpos_player1 <- transmat[curpos_player1]
curpos_player2 <- transmat[curpos_player2]
if(curpos_player1 | curpos_player2 == 100){
print(win)
}else if(curpos_player1 > 100){
return()
}else if(curpos_player2 > 100){
return()
}
}
}
}
}
不确定我应该在返回括号中放置什么来模拟获胜条件。另外,如果代码的其余部分似乎还可以。我真的很感谢任何帮助。
I am a beginner in R and I have to simulate a snakes and ladders game in R for an assignment. The board has 100 squares. The only winning square is 100, for example if you’re on square 98 and roll a 6 you would go forward 2 spaces to 100 and then bounce back 4 spaces to 96. My difficulty is insterting the snakes/ladders transitions in the complete transition matrix, and coding the winning condition. Here is my code so far:
snakesNladders <-
function()
{
transitions <- rbind(
c(40, 3),
c(4, 25),
c(27, 5),
c(13, 46),
c(43, 18),
c(54, 31),
c(33, 49),
c(99, 41),
c(42, 63),
c(66, 45),
c(50, 69),
c(89, 53),
c(76, 58),
c(62, 81),
c(74, 92))
transmat <- 1:100
names(transmat) <- as.character(1:100)
transmat[transitions[,1]] <- transitions[,2]
firstpos <- 0
curpos_player1 <- NULL
curpos_player2 <- NULL
while(curpos_player1 & curpos_player2 < 100) {
curpos_player1 <- firstpos + curpos_player1 + sample(1:6, 1, replace=TRUE)
curpos_player2 <- firstpos + curpos_player2 + sample(1:6, 1, replace = TRUE)
curpos_player1 <- transmat[curpos_player1]
curpos_player2 <- transmat[curpos_player2]
if(curpos_player1 | curpos_player2 == 100){
print(win)
}else if(curpos_player1 > 100){
return()
}else if(curpos_player2 > 100){
return()
}
}
}
}
}
Not sure what I should put in the return brackets to simulate the winning condition. Also if the rest of the code seems ok. I would really appreciate any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是我可能会如何处理的。也许您可以通过浏览代码来获得一些想法。
Here's how I might approach it. Maybe you can get some ideas by walking through the code.