-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaster.rb
More file actions
98 lines (78 loc) · 1.73 KB
/
master.rb
File metadata and controls
98 lines (78 loc) · 1.73 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class Code
COLORS = ['R','B','G','Y','P','O','C','M']
NUM_PEGS = 8
def initialize(answer_code="RBGY")
@answer_code = answer_code
end
def self.colors
COLORS
end
def self.num_pegs
NUM_PEGS
end
def self.random
colors = (COLORS.sample(3) + COLORS.sample(3) + COLORS.sample(2)).shuffle
# for i in 0..3
# colors << ['R','B','G','Y'].sample
# end
Code.new(colors.join(''))
end
def self.sanitize(code)
if code.scan(/[rgbypocmRGBYPOCM]+/).join('').length == NUM_PEGS
return code.scan(/[rgbypocmRGBYPOCM]+/).join('').upcase
end
false
end
def code
@answer_code
end
def count_colors(code)
count_colors = Hash.new(0)
code.split('').each do |col|
count_colors[col] += 1
end
count_colors
end
def exact_matches(code)
total = 0
for i in 0..code.length-1
if @answer_code[i] == code[i]
total += 1
end
end
total
end
def near_matches(code)
total = 0
answer_colors = count_colors(@answer_code)
player_colors = count_colors(code)
player_colors.each do |col, val|
# total += [answer_colors[col], val].min
if answer_colors[col] > val
total += val
else
total += answer_colors[col]
end
end
total - exact_matches(code)
end
end
class Game
attr_reader :answer
MAX_TURNS = 5
def initialize(answer = Code.random)
if answer.class == Code
@answer = answer
else
@answer = Code.new(answer)
end
end
def display_matches(guess)
exact_matches = @answer.exact_matches(guess)
near_matches = @answer.near_matches(guess)
[exact_matches, near_matches]
end
def win?(guess)
@answer.exact_matches(guess) == Code.num_pegs
end
end