-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayer.rb
More file actions
79 lines (61 loc) · 1.3 KB
/
Copy pathplayer.rb
File metadata and controls
79 lines (61 loc) · 1.3 KB
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
# frozen_string_literal: true
require_relative 'interface'
class Player
include Interface
attr_reader :bank, :cards, :name
ACE_CARD_CHAR = 'A'
WINNING_VALUE = 21
def initialize(name, bank)
@name = name
@bank = bank
@cards = []
end
def place_bet(value)
bank.take(value)
end
def add_money(value)
bank.add(value)
end
def take_card(card)
cards << card
end
def show_cards
raise NotImplementedError, 'Should realize in subclass'
end
def open_cards
cards_border { puts "#{cards.map(&:name).join(' ')} | #{calculate_values} | Money: #{bank.amount}" }
end
def calculate_values
if cards.size == 3 && ace?
values = []
%i[min max].each do |m|
val = sum_values(m)
values << val if val <= 21
end
values.max
else
sum_values
end
end
def sum_values(method = :max)
cards.map(&:value).sum(&method)
end
def ace?
cards.map(&:char).include?(ACE_CARD_CHAR)
end
def can_take_card?
cards.size < 3
end
def valid_result?
compare_winning_value_with(calculate_values) <= 0
end
def compare_winning_value_with(player_value)
player_value <=> WINNING_VALUE
end
def <=>(other)
calculate_values <=> other.calculate_values
end
def update_cards
@cards = []
end
end