forked from jasonswett/hangman_challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hangman.rb
executable file
·71 lines (58 loc) · 1.61 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
# The above can be replaced with whatever language you choose
# Modify this file to create your hangman program.
#
# The input filename will come as an argument (see completeness_test).
require 'byebug'
class Hangman
def initialize(life_left = 6, word)
@life_left = 6
@word = word
@guessed_chars = []
@guessed_word = compute_guessed_word
print_game_status
end
def guess(guessed_char)
@guessed_chars << guessed_char
@guessed_word = compute_guessed_word
@life_left -= 1 unless @word.include? guessed_char
end
# Return the letters that were guess that are not part of the word.
def incorrect_guesses
@guessed_chars.join.tr @guessed_word, ''
end
def print_game_status
if won?
puts "#{@guessed_word} YOU WIN!"
else
if @life_left == 0
puts "#{@guessed_word} YOU LOSE!"
else
print "#{@guessed_word} life left: #{@life_left}"
print " incorrect guesses: #{incorrect_guesses}" unless incorrect_guesses.empty?
print "\n"
end
end
end
def won?
@guessed_word == @word
end
# Loop through each character in the correct word.
# If the letter was *NOT* one of the guessed letters, then replace it with a _
def compute_guessed_word
@word.chars.map { |c| @guessed_chars.include?(c) ? c : '_' }.join
end
end
input_filename = ARGV[0]
file = File.new(input_filename)
lines = file.readlines
lines.each do |line|
skip if line.empty?
line.chomp!
if line.length > 1 # word
@hangman = Hangman.new(6, line)
else
next if @hangman.won?
@hangman.guess(line)
@hangman.print_game_status
end
end