R/take_bets.R

Defines functions take_bets

Documented in take_bets

#' Conduct a round of betting.
#'
#' @param players A list of elements from the S4 class "player".
#' @param start The index of the player who is due to act first.
#' @param pot A numeric value represting the size of the pot.
#' @param skip A logical vector representing which players have folded.
#' @param preflop A logical value which is true if it is the preflop
#' round of betting.
#' @param human A logical value which takes the value TRUE if the
#' actions are to be inputted in the console.
#'
#' @return A named list containing the players, pot and the skip vector.
#' @export
#'
take_bets <- function(players,start,pot,skip,preflop = TRUE,human = TRUE){
  n <- length(players)
  bets <- rep(0,n)

  #CREATE BLINDS
  if(preflop == TRUE){
    bets <- blinds(players,bets,start)
    players <- bets[1:n]
    bets <- unlist(bets[(n+1):(2*n)])
  }

  #STARTING VALUES
  pot <- pot + sum(bets)
  turn <- start - 1
  counter <- 0
  raise <- 0

  #RETRIEVE ACTIONS
  while (!end_criteria(bets,skip,counter)){
    #Track the total number of actions have been made and who's
    #due to make the next action.
    turn <- (turn + 1) %% n
    if (turn == 0) turn <- n
    if (skip[turn]) next
    counter <- counter +1
    validity <- list(FALSE)
    display(players,turn = turn,pot = pot,bets = bets)
    while (!validity[[1]]){ #Iterate until a valid action is provided.
      #Determine what the source of the action is.
      if (human) action <- readline(prompt = "Action:")

      #Return a warning if invalid and request another action.
      validity <- validate_bet(player = players[[turn]],action = action,
                               turn=turn,bets = bets, raise = raise)
      if (!validity[[1]]){
        display(players,turn = turn,pot = pot,bets = bets)
        options(warn=1)
        warning(validity[[2]])
        options(warn=0)
      }
    }

    #UPDATE DISPLAY VALUES
    if (action == "fold"){
      bets[turn] <- 0
      skip[turn] <- TRUE
    } else {
      if (as.numeric(action) > max(bets)){ #Check if player made
        raise <- as.numeric(action) - max(bets) #a raise.
      }
      bets[turn] <- bets[turn] + as.numeric(action)
      players[[turn]]@chips <- players[[turn]]@chips - as.numeric(action)
      pot <- pot + as.numeric(action)
    }
  }
  #Determine if player has won the round
  #due to other players folding.
  if(sum(skip) == n-1){
    turn <- (turn + 1)%%n
    if (turn == 0) turn <- n
    players[[turn]]@chips <- players[[turn]]@chips + pot
    print(paste("Player",turn,"wins"))
  }
  return(list("players" = players,"pot" = pot, "skip" = skip))
}
dfcorbin/pokersim2 documentation built on Jan. 15, 2020, 12:20 a.m.