Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
@DaveGavin
Copy link
Author

DaveGavin commented Oct 27, 2019

This version of the ghostgame does not give me an unexpected end error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment