#' S4 class to represent a card
#'
#' @slot suit character.
#' @slot value numeric.
#' @export
methods::setClass("card", slots = c(
suit = "character",
value = "numeric"
)
)
#' An S4 class to represent a deck of cards
#'
#' @slot withdrawn list.
#'
#' @export
#'
methods::setClass("deck", slots = c(
withdrawn = "list" #A deck is characterised by the
) #cards withdrawn from it.
)
#' An S4 class to represent a poker player
#'
#' @slot hand list of cards that have been dealt to them.
#' @slot chips the number of chips a player has available to play with.
#' @slot community the cards available to everyone e.g. flop,turn,river...
#'
#' @export
#'
methods::setClass("player", slots = c(
hand="list",
chips = "numeric",
community="list" #Cards that are available for
) #all players to use e.g. flop
)
#' Generate an object of class "deck"
#'
#' @return An new object of the S4 class "deck"
#' @export
#'
new_deck <- function(){
deck <- new("deck", withdrawn = list())
return(deck)
}
#' Generate a new card
#'
#' @return A new object of the S4 class "card"
#' @export
new_card <- function(){
suit <- c("Spades", "Clubs", "Hearts", "Diamonds")
new("card",
suit = suit[purrr::rdunif(1,1,4)],
value = purrr::rdunif(1,1,13)
)
}
#' Draw cards from a given deck.
#'
#' @param n The number of cards to be drawn from the deck
#' @param deck An object of the S4 class "deck" which
#' may have had cards drawn from it previously.
#'
#' @return A list of n+1 elements with the generated cards, as
#' well as the deck contained in the last element.
#' @export
new_cards <- function(n,deck){
if (n > 52-length(deck@withdrawn)) stop("Not enough cards remaining in the deck")
cards <- c()
count <- 0
while (count<n){
newcard <- new_card()
#Check to see if this new card has already been removed from the deck
if (exists(paste(newcard@value,newcard@suit),where = deck@withdrawn)){
next
}
count = count +1
cards <- c(cards, newcard)
#Now we add a name to the new card added to the vector.
names(cards)[count] <- paste(newcard@value,newcard@suit)
deck@withdrawn <- c(deck@withdrawn, newcard) #Update the deck
names(deck@withdrawn)[length(deck@withdrawn)] <- paste(newcard@value,newcard@suit)
}
return(c(cards,deck))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.