[英]r if else for loop with logical and boollean operators
[英]If, else if, else statements and logical operators in R and creating functions
我已经为此工作了两天,只是我陷入了困境,我正在使用 R 中的 if、else if 和 else 语句
我创建了一个 function 来为两个玩家随机抽取 3 张牌来模拟游戏
face=c("king", "queen", "jack", "ten", "nine", "eight", "seven", "six", "five", "four", "three", "two", "ace")
value=c(13, 12,11,10,9,8,7,6,5,4,3,2,1)
deck <-data.frame(face=rep(face,4),
suit=c(rep("spades", 13), rep("clubs", 13), rep("diamonds", 13), rep("hearts",
13)),
value=rep(value,4))
这是我为得到他们的手而创建的 function
get_cards<-function(){
Player.A<-draw_n_random_cards(deck, 3)
Player.B<-draw_n_random_cards(deck, 3)
}
1 我将每个玩家手牌的值加起来得到他们的分数
Sum.Player.A<-sum(Player.A$value)
Sum.Player.B<-sum(Player.B$value)
2 如果手中的所有牌都是相同的花色(所有红心),它们的总和将乘以 2 #3 如果所有的牌都是相同的花色(所有 A),那么它们的总和也将乘以 2 好的,所以我创建了对我的 if、else if、else 语句的逻辑测试
combo.1=c("ace", "ace", "ace")
combo.2=c("heart", "heart", "heart")
这是我的 if 语句
if (Sum.Player.A==combo.1){
Sum.Player.A<-Sum.Player.A*2
}else{
Sum.Player.A
}
if(Sum.Player.A==combo.2){
Sum.Player.A<-Sum.Player.A*2
}else{
Sum.Player.A
}
if (Sum.Player.B==combo.1){
Sum.Player.B<-Sum.Player.B*2
}else{
Sum.Player.B
}
if(Sum.Player.B==combo.2){
Sum.Player.B<-Sum.Player.B*2
}else{
Sum.Player.B
}
我的最终结果是编写一个 function 来显示每个玩家的手牌并宣布获胜者。
winner<-function(){
if(Sum.Player.A<Sum.Player.B){
"Player B is the winner"
}else if (Sum.Player.A>Sum.Player.B){
"Player A is the winner"}else {
"tie"}
}
所以我的麻烦是将这个功能序列放入一个 function 来玩我创建的这个游戏。 如果我创建一个名为 function
play_game<-function(){
#1 draw 3 random cards for each player
#2 score their cards
#3 compare their score to delcare a winner
}
这就是我被卡住的地方。 我正在寻找这个问题的方向。
我在创建卡片组时添加了 stringsAsFactors=FALSE。 抽 n 张随机牌一次抽牌,否则您可能会抽到相同的牌(需要在不更换的情况下完成)。 最后,获胜者 function 将 A 的手牌和 B 的手牌之和作为 arguments。
face=c("king", "queen", "jack", "ten", "nine", "eight", "seven", "six", "five", "four", "three", "two", "ace")
value=c(13, 12,11,10,9,8,7,6,5,4,3,2,1)
deck <-data.frame(face=rep(face,4),
suit=c(rep("spades", 13), rep("clubs", 13), rep("diamonds", 13), rep("hearts",
13)),
value=rep(value,4), stringsAsFactors = FALSE)
get_cards<-function(){
return(draw_n_random_cards(6))
}
draw_n_random_cards=function(n) {
s=sample(1:52, 6, replace=FALSE)
return(deck[s,])
}
winner<-function(A, B){
if(A<B){
"Player B is the winner"
}else if (A>B){
"Player A is the winner"}else {
"tie"}
}
play_game=function() {
cards=draw_n_random_cards()
Player.A=cards[1:3,]
Player.B=cards[4:6,]
Sum.Player.A<-sum(Player.A$value)
Sum.Player.B<-sum(Player.B$value)
combo.1=c("ace", "ace", "ace")
combo.2=c("heart", "heart", "heart")
if (identical(Player.A$face, combo.1) | identical(Player.A$suit, combo.2)) {
Sum.Player.A<-Sum.Player.A*2
}
if (identical(Player.B$face, combo.1) | identical(Player.B$suit, combo.2)) {
Sum.Player.B<-Sum.Player.B*2
}
winner(Sum.Player.A, Sum.Player.B)
}
在一场比赛中:
> play_game()
[1] "Player B is the winner"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.