r - 我的 yathzee 函数卡在 if 语句中
问题描述
我刚开始学习 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”。我的代码没有遍历其余的 else if 语句或以某种方式卡在第一行。我该如何解决?
解决方案
你基本上只是有几个不匹配的括号。我认为您不需要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()
推荐阅读
- python - Python Pandas - 按多个列名过滤
- plotly - 显示为“n”、“p”或“f”的小数字
- amazon-web-services - 将 IAM 角色传递给 EC2 上的 Docker
- python - python函数中的return语句不返回任何内容
- deployment - 部署和托管之间的区别
- vue.js - 当元素没有 id 时 v-for 使用什么键?
- sql-server - 前 1 名在加入时不返回结果
- javascript - 如何从javascript中动态创建的复选框和单选按钮获取输入?
- reactjs - 使用 renderToString 将组件渲染为传单标记会丢失主题
- python - PySide2 QDialog 可能的错误