-
Notifications
You must be signed in to change notification settings - Fork 0
/
round.rb
138 lines (124 loc) · 2.71 KB
/
round.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
require_relative 'deck.rb'
class Round
attr_accessor :user, :dealer, :interface, :bank
def initialize(user, dealer, interface)
@player = user
@dealer = dealer
@deck = Deck.new
@interface = interface
@bank = 0
end
def start!
interface.prepare_deck
first_distribution
make_beats(10)
interface.show_cards(@player)
interface.show_dealer_cards(@dealer)
begin
action = interface.get_action
raise 'Incorrect choice' unless (1..3).cover?(action)
rescue RuntimeError => error
p error.message.to_s
retry
end
do_action(action)
end
private
def stand
if @dealer.hand.size < 3 && @dealer.scores < 17
dealer_hit
else
interface.show_cards(@dealer)
interface.line
interface.show_cards(@player)
end
end
def player_hit
take_card(@player)
interface.show_last_card(@player)
dealer_hit
interface.line
open_cards
interface.line
end
def dealer_hit
return if @dealer.scores >= 17
take_card(@dealer)
interface.show_last_card(@dealer)
interface.line
open_cards
interface.line
end
def first_distribution
2.times do
take_card(@player)
take_card(@dealer)
end
end
def do_action(action)
case action
when 1 then player_hit
when 2 then stand
when 3 then open_cards
end
show_winner
end
def open_cards
users = [@player, @dealer]
users.each { |user| interface.show_info(user) }
end
def show_winner
win = who_win?
if win.is_a?(User)
win.winning(@bank)
interface.show_winner(win)
else
@player.cash += (@bank / 2)
@dealer.cash += (bank / 2)
interface.nobody_wins
end
end
def make_beats(value)
@player.bet(value)
@dealer.bet(value)
@bank += (value * 2)
end
def who_win?
if @player.scores > @dealer.scores && @player.scores <= 21
@player
elsif @player.scores > @dealer.scores && @player.scores > 21
@dealer
elsif @dealer.scores > @player.scores && @dealer.scores <= 21
@dealer
elsif @dealer.scores > @player.scores && @dealer.scores > 21
@player
else
false
end
end
def take_card(user)
raise 'Cant take card if you have more than 2' if user.hand.size > 2
card = @deck.cards.slice!(0)
user.hand << card
calculate_cards!(user)
end
def calculate_cards!(user)
value = 0
if user.hand.size.zero?
value
else
user.hand.each do |card|
mid_value = card.value
if card.ace?
if user.scores < 11
card.value
else
mid_value = 1
end
end
value += mid_value
user.scores = value
end
end
end
end