class StudioGame::Game
Attributes
title[R]
Public Class Methods
new(title)
click to toggle source
# File lib/studio_game/game.rb, line 12 def initialize(title) @title = title @players = [] end
Public Instance Methods
add_player(player)
click to toggle source
# File lib/studio_game/game.rb, line 32 def add_player(player) @players.push(player) end
high_score_entry(player)
click to toggle source
# File lib/studio_game/game.rb, line 110 def high_score_entry(player) formatted_name = player.name.ljust(20, '.') "#{formatted_name} #{player.score}" end
load_players(filename)
click to toggle source
using the csv class
# File lib/studio_game/game.rb, line 25 def load_players(filename) CSV.foreach(filename) do |row| player = Player.new(row[0], row[1].to_i) add_player(player) end end
play(rounds) { || ... }
click to toggle source
# File lib/studio_game/game.rb, line 36 def play(rounds) puts "There are #{@players.size} players in #{@title}:" 1.upto(rounds).each do |round| if block_given? break if yield end puts "\nRound: #{round}" @players.each do |player| GameTurn.take_turn(player) puts player end end treasures = TreasureTrove::TREASURES puts "\nThere are #{treasures.size} treasures to be found:" treasures.each do |treasure| puts "A #{treasure.name} is worth #{treasure.points} points" end end
print_name_and_health(player)
click to toggle source
# File lib/studio_game/game.rb, line 60 def print_name_and_health(player) puts "#{player.name} (#{player.health})" end
print_stats()
click to toggle source
# File lib/studio_game/game.rb, line 64 def print_stats strong_players, wimpy_players = @players.partition { |player| player.strong? } puts "\n#{@title} statistics:" puts "\n#{strong_players.size} strong players:" strong_players.each do |player| print_name_and_health(player) end puts "\n#{strong_players.size} weak players:" wimpy_players.each do |player| print_name_and_health(player) end # my soulution # sorted_players = strong_players, wimpy_players.partition { |player| player.score } # their solution # sorted_players = @players.sort { |a, b| b.score <=> a.score } puts "\n#{@title}'s High Scores:" @players.sort.each do |player| puts high_score_entry(player) end @players.each do |player| puts "\n#{player.name} total points:" puts "#{player.points} grand total points" end @players.each do |player| puts "\n#{player.name}'s point totals:" player.each_found_treasure { |treasure| puts "#{treasure.points} total #{treasure.name} points" } end puts "\n#{total_points} total points from treasures found" end
save_high_scores(filename="high_scores.txt")
click to toggle source
# File lib/studio_game/game.rb, line 115 def save_high_scores(filename="high_scores.txt") File.open(filename, "w") do |file| file.puts "\n#{@title} High Scores:" @players.sort.each do |player| file.puts high_score_entry(player) end end end
total_points()
click to toggle source
# File lib/studio_game/game.rb, line 106 def total_points @players.reduce(0) { |sum, player| sum + player.points } end