-
Notifications
You must be signed in to change notification settings - Fork 0
/
hangman_spec.rb
92 lines (72 loc) · 1.64 KB
/
hangman_spec.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
describe 'playing hangman' do
it 'displays a masked word' do
play("hangman")
expect(placeholder.to_s).to eq("_______")
end
it 'reveals letters guessed correctly' do
word = "hangman"
play(word)
placeholder.make_guess("h")
expect(placeholder.to_s).to eq("h______")
placeholder.make_guess("a")
expect(placeholder.to_s).to eq("ha___a_")
end
it 'ignores incorrect guesses' do
word = "hangman"
play(word)
placeholder.make_guess("i")
expect(placeholder.to_s).to eq("_______")
end
it 'returns false if incorrect guess' do
word = "hangman"
play(word)
expect(placeholder.make_guess("i")).to be_false
end
it 'knows when it is not completed' do
word = "hangman"
play(word)
placeholder.make_guess("h")
expect(placeholder.completed).to eq(false)
end
it 'knows when it has completed' do
word = "hangman"
play(word)
placeholder.make_guess("h")
placeholder.make_guess("a")
placeholder.make_guess("n")
placeholder.make_guess("g")
placeholder.make_guess("m")
placeholder.make_guess("n")
expect(placeholder.completed).to eq(true)
end
def play(word)
@placeholder = Placeholder.new(word)
end
def placeholder
@placeholder
end
class Placeholder
def initialize(word)
@word = word
@placeholder = "_" * @word.size
end
def make_guess(guess)
@word.chars.each_with_index do |char, index|
update_placeholder(index, guess) if char == guess
end
!!@word[guess]
end
def update_placeholder(index, guess)
self[index] = guess
end
def []=(index, char)
@placeholder[index] = char
end
def completed
[email protected]?("_")
end
def to_s
@placeholder
end
end
end