forked from adrianeyre/codewars
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMastermind.rb
More file actions
66 lines (60 loc) · 1.63 KB
/
Mastermind.rb
File metadata and controls
66 lines (60 loc) · 1.63 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
def mastermind(game)
colours = ["Red", "Blue", "Green", "Orange", "Purple", "Yellow"]
amount = Hash.new {|key,value| key[value]=0}
guess = []
colours.each do |colour|
answer = game.check([colour, colour, colour, colour])
colour_amount = answer.count("Black")
amount[colour] = colour_amount
(1..colour_amount).each{|c| guess << colour}
end
answer = false
while answer != "WON!" && answer != "Error"
p answer = game.check(guess.shuffle)
end
end
class MasterMind
Colours = ["Red", "Blue", "Green", "Orange", "Purple", "Yellow"]
def initialize()
srand
@result = []
@goes = 0
(1..4).each do |colour|
@result << Colours[rand(Colours.length)]
end
@amount = Hash.new {|key,value| key[value]=0}
@result.each{|colour| @amount[colour]+=1}
end
def check(attempt)
return "Error" if attempt.length != 4
@goes += 1
return "Error" if @goes>60
if attempt == @result
return "WON!"
end
amount = {"Red"=>0, "Blue"=>0, "Green"=>0, "Orange"=>0, "Purple"=>0, "Yellow"=>0}
@amount.each{|key,value| amount[key]=value}
result = []
new_attempt = []
attempt.each {|colour| new_attempt << colour}
attempt.each_with_index do |colour, index|
return "Error" if !Colours.include? colour
if colour == @result[index]
result << "Black"
amount[colour] -= 1
new_attempt[index] = ""
end
end
new_attempt.each do |colour|
if colour != ""
if amount[colour] > 0
result << "White"
amount[colour] -= 1
end
end
end
result.shuffle
end
end
game = MasterMind.new
mastermind(game)