我刚开始学习R,并被要求为简化的Yahtzee游戏编写一个函数。游戏的目的是通过掷五个骰子来进行某些组合来得分。
有6种不同的类别: 如果所有五个骰子都相同,则玩家获得50分(Yahtzee)。 五个连续的骰子(即所有唯一的骰子)产生40分(直线) 一个数字中的三个和另一个中的两个产生25分。 如果四个骰子相同,则给出所有骰子总和的分数。 如果三个骰子相同,则给出所有骰子总和的分数。 任何剩余的条件都会给出所有骰子总和的分数。
这是我尝试过的方式(尽管我认为可以将后三类归纳为同一逻辑测试):
yahtzee <- function(){
dices <- sample(1:6,5,TRUE)
t <- table(dices)
t.x <- unname(t)
if(length(unique(dices) == 1)){
print("Yahtzee")
score <- 50
}
else if(dices == c(1,2,3,4,5) | dices == c(2,3,4,5,6)){
print("Straight")
score <- 40
}
else if(t.x[1] == 3 & t.x[2] == 2 | t.x[1] == 2 & t.x[2] == 3){
print("Full House")
score <- 25
}
else if(t.x[1] == 4 & t.x[2] == 1 | t.x[1] == 1 & t.x[2] == 4){
print("Four Of A Kind")
score <- sum(dices)
}
else if(t.x[1] == 3 & t.x[2] == 1 & t.x[3] == 1 | t.x[1] == 1 & t.x[2] == 3 & t.x[3] == 1 | t.x[1] == 1 & t.x[2] == 1 & t.x[3] == 3){
print("Three Of A Kind")
score <- sum(dices)
}
else{
print("Chance")
score <- sum(dices)
}
print(dices)
print(score)
}
当我运行该功能时,无论骰子组合是什么,我总是获得50分,并且出现“ Yahtzee”。如果语句或以某种方式卡在第一行中,我的代码不会遍历其余的其他代码。我该如何解决?
答案 0 :(得分:1)
您基本上只有一对配偶不匹配。我认为您不需要t.x
,而可以利用t
的属性和any
函数的组合。这是我重写您的函数的方法:
yahtzee <- function(){
dices <- sample(1:6,5,TRUE)
t <- table(dices)
if(length(unique(dices)) == 1){
print("Yahtzee")
score <- 50
}
else if(length(unique(dices)) == 5){
print("Straight")
score <- 40
}
else if(any(t == 3) * any(t == 2)){
print("Full House")
score <- 25
}
else if(any(t == 4)){
print("Four Of A Kind")
score <- sum(dices)
}
else if(any(t == 3)){
print("Three Of A Kind")
score <- sum(dices)
}
else{
print("Chance")
score <- sum(dices)
}
print(dices)
print(score)
}
yahtzee()
答案 1 :(得分:0)
yahtzee <- function () {
dices <- sample(1:6, 5, TRUE)
if( length(unique(dices)) == 1 ) {
print("Yahtzee")
score <- 50
} else if ( length(unique(dices)) == 5 ) {
print("Straight")
score <- 40
} else if ( length(unique(dices)) == 2 && length(which(dices ==
unique(dices)[1])) == 2 ||
length(which(dices == unique(dices)[2])) == 2 ) {
print("Full House")
score <- 25
} else if ( length(unique(dices)) == 2 && length(which(dices ==
unique(dices)[1])) == 1 ||
length(which(dices == unique(dices)[2])) == 1 ) {
print("Four Of A Kind")
score <- sum(dices)
} else if ( length(unique(dices)) == 3 && length(which(dices ==
unique(dices)[1])) == 3 ||
length(which(dices == unique(dices)[2])) == 3 ||
length(which(dices == unique(dices)[3])) == 3 ) {
print("Three Of A Kind")
score <- sum(dices)
} else {
print("Chance")
score <- sum(dices)
}
print(dices)
print(score)
}