dimanche 28 février 2021

If, else if, else statements and logical operators in R and creating functions

I have worked on this for two days and simply I am stuck in the mud! I am working on using if, else if and else statements in R

I have created a function to draw 3 random cards for two players to simulate a game

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)) 

This is the function I created to get their hands

get_cards<-function(){
  Player.A<-draw_n_random_cards(deck, 3)
  Player.B<-draw_n_random_cards(deck, 3)
}

1 I added up the values of each player's hand to get their scores

Sum.Player.A<-sum(Player.A$value)
Sum.Player.B<-sum(Player.B$value)

2 If all the cards in the hand are the same suit (all hearts) their sum will be multiplied by 2 #3 If all the cards are the same suit (all aces) there sum will be multiplied by 2 also Ok, so I created a logical test for my if, else if, else statement

combo.1=c("ace", "ace", "ace")
combo.2=c("heart", "heart", "heart")

This is my if statement

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
}

My end result is to write a function that displays each player's hand and declares a winner.

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"}
}

So my trouble is putting this sequence of functions into a single function to play this game I created. If I create a function called

play_game<-function(){

#1 draw 3 random cards for each player
#2 score their cards
#3 compare their score to delcare a winner
}

This is where I have been stuck. I am looking for direction on this question.

Aucun commentaire:

Enregistrer un commentaire