class BlackjackCli

Class that offers an interactive interface for the user to play blackjack

Public Class Methods

new() click to toggle source

Constructor for the BlackJackCli class @return [nil]

# File src/blackjack_cli.rb, line 25
def initialize
  @default_text_color = [LIGHT_GRAY_BG, BLACK_FG]
  puts " Blackjack CLI started \n\n".set_attributes(@default_text_color)
  @blackjack = Game.new
end

Public Instance Methods

format_cards(cards) click to toggle source

Formats cards to be displayed side-by-side @param [Card Array] cards the cards to be displayed @return [string] a formatted string of all cards side by side

# File src/blackjack_cli.rb, line 96
def format_cards(cards)
  cards_string = ''

  card_parts = []
  cards.each { |card|
    card_parts.push(card.get_ascii_card.split("\n"))
  }

  if card_parts.length == 0
    return ''
  end

  (0...card_parts[0].length).each { |i|
    card_parts.each { |card_part|
      cards_string += card_part[i] + '   '
    }
    cards_string += "\n"
  }
  cards_string
end
game_loop() click to toggle source

the main game loop. It continually asks the user for a new choice of either hit or stand @return [nil]

# File src/blackjack_cli.rb, line 34
def game_loop
  new_game = true

  while true
    if new_game
    print_result(@blackjack.start)
    new_game = false
  end

  result = nil
  case get_play_command
    when "stand\n"
      result = @blackjack.stand
    when "hit\n"
      result = @blackjack.hit
    else
      puts 'Something went wrong'
  end

  print_result(result)

  if result[2] == 'win'
    puts ' You won :D '.set_attributes([GREEN_BG, BLACK_FG])
  elsif result[2] == 'loss'
    puts ' You lost :( '.set_attributes([RED_BG, BLACK_FG])
  elsif result[2] == 'draw'
    puts " It's a draw ".set_attributes([YELLOW_BG, BLACK_FG])
  end

  if result[2] != 'undecided'
    new_game = true
    pause_when_game_ends
  end

  end
end
get_play_command() click to toggle source

Gets the user's input on what to do next @return [string] the (validated) user input

# File src/blackjack_cli.rb, line 119
def get_play_command
puts ' What would you like to do? (hit|stand) '.set_attributes(@default_text_color)
input = gets
while not input == "hit\n" and not input == "stand\n"
  puts " Please enter 'hit' or 'stand' ".set_attributes(@default_text_color)
  input = gets
end
puts "\n"
input
end
pause_when_game_ends() click to toggle source

This pauses the game until the user presses enter/return before starting a new game @return [nil]

# File src/blackjack_cli.rb, line 74
def pause_when_game_ends
  puts ' Press enter to start a new game '
           .set_attributes(@default_text_color)
  gets
end
print_result(result) click to toggle source

Prints the current game state based on the results of a hit or stand action @param [Card Array, Card Array] result the result to be displayed @return [nil]