-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman.rb
109 lines (93 loc) · 2.55 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
require 'yaml'
require_relative 'lib/color'
require_relative 'lib/serialize'
class Game
include BasicSerializable
attr_reader :random_word
attr_accessor :display, :incorrect_guesses, :guesses
def initialize
@guesses = 10
@random_word = generate_word
@display = Array.new(@random_word.size, '_')
@incorrect_guesses = []
end
def get_input(game)
puts '*************************************************************************'
puts "Enter #{'"save"'.green} to save the game"
puts ''
puts game.display.join(' ')
puts ''
puts "Incorrect letters: #{game.incorrect_guesses.join(' ')}"
puts ''
puts "Remaining guesses: #{game.guesses}"
puts ''
print 'Enter a letter to make a guess> '
gets.chomp.downcase
end
def over?(game)
game.display.include?('_') && game.guesses > 0
end
def decide_winner(game)
puts ''
puts game.display.join(' ')
puts ''
if game.guesses > 0
puts "Congrats! You guessed '#{game.random_word.yellow}'"
else
puts "You lost. Correct answer was '#{game.random_word.yellow}'"
end
end
def execute(game, input)
if input == 'save'
puts 'Saving...'
save_game(game.serialize)
else
populate(game, input)
end
end
private
def save_game(save_file)
Dir.mkdir('saves') unless Dir.exist?('saves')
filename = 'saves/save.txt'
File.open(filename, 'w') do |file|
file.puts save_file
end
end
def generate_word
words_list = File.read('5desk.txt').split(' ')
words_correct_size = words_list.filter_map { |word| word if word.size.between?(5, 12) }
words_correct_size.sample.downcase
end
def populate(game, input)
game.random_word.split('').each_with_index do |letter, index|
game.display.each_with_index do |_placeholder, _display_index|
if letter.downcase == input
game.display[index] = input
elsif !game.random_word.include?(input)
break if game.incorrect_guesses.include?(input)
game.guesses -= 1
game.incorrect_guesses.push(input)
end
end
end
end
end
game = Game.new
puts "Enter '1' to start a new game"
puts "Enter '2' to load a save file"
choice = gets.chomp
if choice == '1'
while game.over?(game)
input = game.get_input(game)
game.execute(game, input)
end
game.decide_winner(game)
elsif choice == '2'
puts 'Loading..'
game.unserialize(File.read('saves/save.txt'))
while game.over?(game)
input = game.get_input(game)
game.execute(game, input)
end
game.decide_winner(game)
end