forked from bitmakerlabs/hangman
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhangman.rb
85 lines (71 loc) · 1.75 KB
/
hangman.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
class Hangman
#This class will be used to run an instantce of a hangman game
#It is only concerned with one run through of the game
#It is not responsible for human interaction
class InvalidGuessException < Exception
end
attr_accessor :word, :chances, :wboard, :word_arrayed, :guesses, :guess
attr_reader :board, :result_index, :array_word
def initialize(word)
puts "Welcome to our hangman game! Please guess a letter to start."
puts "-----------------------------------"
@word = word.downcase
@chances = 8
@word_arrayed =[]
@wboard = []
@guesses = []
@result_index = []
@guess = ""
array_word
workingboard
end
def array_word
@word_arrayed = @word.split("")
return @word_arrayed
end
def workingboard
@wboard = Array.new(@word.length) {|slot| "_"}
end
def board
return @wboard.join(" ")
end
def guess!(letter)
@guess = letter.downcase
if guesses.include?(@guess)
raise InvalidGuessException.new("You've already guessed that letter! Enter a new letter!")
elsif (guess.class == String) && (@guess.length == 1) && (true if guess.match(/[a-z]/) != nil)
if @word_arrayed.include?(@guess)
good_guess
else
bad_guess
end
else
raise InvalidGuessException.new("Please enter a one letter string!")
end
end
def good_guess
@guesses << @guess
# compact eliminates "nil"s
@result_index = @word_arrayed.map.with_index {|letter, index| index if letter == @guess}.compact
update_board
end
def bad_guess
@guesses << @guess
@chances -= 1
end
def update_board
@result_index.each do |matchindex|
@wboard[matchindex] = @guess
end
end
def won?
if @wboard == word_arrayed
return true
end
end
def lost?
if @chances < 1
return true
end
end
end