class TreasureHunt::Game
Attributes
title[R]
Public Class Methods
new(title)
click to toggle source
# File lib/treasure_game/game.rb, line 10 def initialize(title) @title = title.capitalize @players = [] end
Public Instance Methods
add_player(p)
click to toggle source
# File lib/treasure_game/game.rb, line 31 def add_player(p) @players << p end
high_score_entry(player)
click to toggle source
# File lib/treasure_game/game.rb, line 15 def high_score_entry(player) formatted_name = player.name.ljust(20, '.') "#{formatted_name} #{player.score}" end
load_players(from_file)
click to toggle source
# File lib/treasure_game/game.rb, line 27 def load_players(from_file) File.foreach(from_file) { |line| add_player(Player.new(line.chomp)) } end
play(rounds)
click to toggle source
# File lib/treasure_game/game.rb, line 64 def play(rounds) treasures = TreasureHunt::TREASURES puts "\nThere are #{treasures.length} treasures to be found:" treasures.each { |t| puts "A #{t.name} is worth #{t.points} points" } puts "\nThere are #{@players.length} players in the game." 1.upto(rounds) do |r| # break if yield if block_given? puts "\nRound #{r}:" @players.each do |p| GameTurn.take_turn(p) end end end
print_stats()
click to toggle source
# File lib/treasure_game/game.rb, line 39 def print_stats puts "\n#{@title} statistics:" @players.sort.each do |p| puts "\n#{p.name}'s points totals:" p.each_found_treasure do |t| puts "#{t.points} total #{t.name} points" end puts "#{p.points} grand total points" end puts "\n#{total_points} total points from treasures found" strong_players, weak_players = @players.partition { |p| p.strong? } puts "\n#{strong_players.size} strong players:" strong_players.sort.each { |p| puts p } puts "\n#{weak_players.size} weak players:" weak_players.sort.each { |p| puts p } puts "\n#{@title} High Scores:" @players.sort.each { |p| puts high_score_entry(p) } end
save_high_scores(to_file='highscores.txt')
click to toggle source
# File lib/treasure_game/game.rb, line 20 def save_high_scores(to_file='highscores.txt') File.open('highscores.txt', 'w') do |file| file.puts "#{@title} High Scores:" @players.sort.each { |p| file.puts high_score_entry(p) } end end
total_points()
click to toggle source
# File lib/treasure_game/game.rb, line 35 def total_points @players.reduce(0) { |memo, object| memo += object.points } end