Skip to content

Commit 3130a3d

Browse files
committed
implement insurance bets
1 parent f3399cd commit 3130a3d

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

10_Blackjack/ruby/game.rb

+13
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ def start
2222
loop do
2323
collect_bets_and_deal
2424
play_players
25+
check_for_insurance_bets
2526
play_dealer
2627
settle
2728
end
@@ -48,6 +49,18 @@ def play_players
4849
end
4950
end
5051

52+
def check_for_insurance_bets
53+
return if @dealer_hand.cards[0].label != "A"
54+
55+
print "ANY INSURANCE? "
56+
return if gets.strip != "Y"
57+
58+
@players.each_entry do |player|
59+
print "PLAYER #{player.id} INSURANCE BET? "
60+
player.bet_insurance(gets.to_i)
61+
end
62+
end
63+
5164
def play_dealer
5265
puts "DEALER HAS A \t#{@dealer_hand.cards[1].label} CONCEALED FOR A TOTAL OF #{@dealer_hand.total}"
5366

10_Blackjack/ruby/model/hand.rb

+4
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ def is_standing?
2929
@state == HAND_STATE_STAND
3030
end
3131

32+
def is_blackjack?
33+
total == 21 && @cards.length == 2
34+
end
35+
3236
def total(is_dealer: false)
3337
return @total unless @total.nil?
3438

10_Blackjack/ruby/model/player.rb

+23-2
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,21 @@ class Player
55
def initialize(id)
66
@id = id
77
@balance = 0
8+
@original_bet = 0
9+
@insurance = 0
810

911
@hand = nil
1012
@split_hand = nil
1113
end
1214

13-
attr_reader :id, :balance, :hand, :split_hand
15+
attr_reader :id, :balance, :hand, :split_hand, :insurance
1416

1517
## Begining of hand dealing actions
1618
def deal_initial_hand(hand)
1719
@hand = hand
1820
@split_hand = nil
21+
@max_insurance = @hand.bet / 2
22+
@insurance = 0
1923
end
2024

2125
def has_split_hand?
@@ -32,7 +36,18 @@ def split
3236
@hand, @split_hand = @hand.split
3337
end
3438

35-
def bet_insurance(insurance_bet)
39+
def bet_insurance(bet)
40+
if bet < 0
41+
bet = 0
42+
puts "NEGATIVE BET -- using 0 insurance bet"
43+
end
44+
45+
if bet > @max_insurance
46+
bet = @max_insurance
47+
puts "TOO HIGH -- using max insurance bet of #{bet}"
48+
end
49+
50+
@insurance = bet
3651
end
3752

3853
## End of hand dealing actions
@@ -45,6 +60,12 @@ def update_balance(dealer_hand)
4560
balance_update += get_balance_update(@split_hand, dealer_hand)
4661
end
4762

63+
if dealer_hand.is_blackjack?
64+
balance_update += 2 * @insurance
65+
else
66+
balance_update -= @insurance
67+
end
68+
4869
@balance += balance_update
4970

5071
balance_update

0 commit comments

Comments
 (0)