Skip to contents

Handles the player's turn in a Blackjack game, allowing them to hit or stand.

Usage

player_turn(player_hand, deck, input_fn = readline)

Arguments

player_hand

A vector of cards representing the player's hand.

deck

A vector of cards representing the remaining deck.

input_fn

a holder to obtain player actions (defaults to readline); can be overridden to inject fake input for unit tests or if the user want to add fake actions.

Value

A list containing:

hand

The updated player hand after the turn.

deck

The updated deck after the player's turn.

total

The total value of the player's hand.

Details

1. Displaying the hand:

Before each prompt, the function prints the player’s current hand and its total value as computed by card_value(player_hand). Card names are shown via format(player_hand) while also account for vctrs class.

2. Hit or Stand:

If the user types "hit" or "h", the function calls deal_hand(deck, 1) to draw one card. That card is appended to player_hand, and deck is updated accordingly. If the user types "stand" or "s", the loop ends and the final total is printed. Any other input triggers an “Invalid choice” message and re-prompts.

3. Stopping conditions: The loop continues until the player chooses to stand or their total reaches 21 or higher. When player reach 21 then the loop end immediately.

Examples

# Example: Player always stands immediately
deck <- create_shuffled_deck()
player_hand <- deal_hand(deck, 2)$hand
fake_input <- function(prompt) "stand"
player_turn(player_hand, deck, input_fn = fake_input)
#> [1] Your hand: 4♠ 2♣ (Total = 6 )
#> [1] You stand at 6
#> $hand
#> card[2]
#> 4♠ 2♣ 
#> 
#> $deck
#> card[208]
#> 4♠ 2♣ 7♣ 2♠ 8♠ 3♥ 9♠ 6♠ 10♣ 5♦ 9♥ 5♣ 2♦ 3♣ Q♠ 6♥ 10♥ K♦ 7♦ Q♦ 6♦ K♦ 8♦ 3♥ 8♠ 3♠ 3♣ 8♦ Q♦ 6♦ A♥ A♠ J♠ 2♣ 3♦ 6♥ 6♠ 4♦ A♦ 9♠ 9♣ 2♥ 9♥ Q♦ K♣ J♠ 8♣ 7♥ J♣ 4♠ 9♦ 8♣ A♥ 3♠ 8♣ Q♥ 10♠ K♠ 10♥ 4♦ 6♣ 8♦ 2♠ 8♣ K♣ Q♥ 5♥ 10♣ 10♦ 7♥ 10♦ A♣ 2♥ A♣ 5♥ 3♦ K♠ 7♠ 7♣ J♣ 5♣ 7♠ 6♣ A♦ 6♦ 3♠ J♦ 4♠ 6♣ J♠ 5♠ K♣ 4♥ 3♣ 10♠ 7♣ 4♣ A♣ K♠ 5♠ Q♠ 6♥ J♥ Q♣ 4♦ 10♠ 9♥ 5♦ 4♥ 9♣ 9♠ 2♣ 4♣ 10♣ 9♣ A♦ Q♣ 10♦ 8♥ J♦ Q♦ 3♣ J♥ 3♥ 3♦ J♠ 10♥ 8♦ 4♣ 5♦ 5♣ Q♥ 10♦ 2♦ 4♥ Q♣ 8♠ 2♣ 5♥ 7♦ J♥ A♠ 3♠ K♥ 3♥ 8♥ 5♦ A♣ 7♥ 6♥ 2♦ 5♣ J♥ 7♠ 8♥ 2♠ Q♥ 10♠ J♦ A♥ J♣ 9♥ K♥ 7♥ 7♦ 4♣ K♥ 4♥ 10♥ 6♠ 2♥ 9♣ 6♦ Q♠ K♦ Q♣ K♦ 7♠ 9♠ Q♠ 4♦ J♣ 10♣ 5♥ 2♠ J♦ 9♦ 6♠ 5♠ A♦ 9♦ 3♦ 8♠ A♥ 8♥ 4♠ 2♥ K♠ 6♣ A♠ 5♠ A♠ 7♣ 2♦ 9♦ K♣ 7♦ K♥ 
#> 
#> $total
#> [1] 6
#>