Created
October 27, 2019 17:45
-
-
Save DaveGavin/5a1123232d839f486e6f7eaf2299b43a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Game | |
GAME_NAME = "Ghost" | |
MAX_SCORE = GAME_NAME.length | |
ALPHABET = Set.new("a".."z") | |
def initialize(player_list) | |
@players = player_list | |
@word_fragment = "" | |
@dictionary = initialize_dictionary("dictionary.txt") | |
@scoreboard = initialize_scoreboard | |
end | |
def initialize_dictionary(file_name) | |
words = File.readlines(file_name).map(&:chomp) | |
Set.new(words) | |
end | |
def initialize_scoreboard | |
players = {} | |
@players.each { |player| players[player] = 0 } | |
players | |
end | |
attr_reader :players, :dictionary, :scoreboard | |
attr_accessor :word_fragment | |
# Helper Methods | |
def active_players | |
active = @scoreboard.select { |_, v| v <= MAX_SCORE } | |
active.keys | |
end | |
def valid_char?(char) | |
unless ALPHABET.include?(char) | |
return false | |
end | |
new_fragment = @word_fragment + char | |
@dictionary.any? { |word| word.start_with?(new_fragment) } | |
end | |
def update_game_state(player, player_letter_choice) | |
@word_fragment += player_letter_choice | |
if word_complete? | |
@scoreboard[player] += 1 | |
end | |
end | |
def word_complete? | |
@dictionary.any? { |word| word == @word_fragment } | |
end | |
# Display Methods | |
def prompt_choice_redo | |
puts [ "The character you chose was not valid.", | |
"Valid choices continute to build towards a word.", | |
"The current fragment is #{word_fragment}.", | |
"Please choose again." | |
].join("\n") | |
end | |
def display_game_state(player) | |
puts "#{player} added #{@word_fragment[-1]} to the fragment." | |
puts "It is now #{@word_fragment}." | |
if word_complete? | |
puts "#{player} spelled a word!" | |
end | |
end | |
end | |
players = ["Dave", "Josh"] | |
ghost = Game.new(players) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This version of the ghostgame does not give me an unexpected end error.