Last active
October 27, 2019 18:18
-
-
Save DaveGavin/eb955b4fd9f16d11974a5202627ec1ea 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) | |
return false unless ALPHABET.include?(char) | |
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 | |
@scoreboard[player] += 1 if word_complete? | |
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}." | |
puts "#{player} spelled a word!" if word_complete? | |
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
When I try to run this code in pry I get an "unexpected end" error.
I suspect that the single line if and unless statements are the cause. I've posted another version of this code in another gist with them removed. The code with them removed does not give me any error.