Class: TreasureHunt::Game

Inherits:
Object
  • Object
show all
Defined in:
lib/treasure_game/game.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(title) ⇒ Game

Returns a new instance of Game.



10
11
12
13
# File 'lib/treasure_game/game.rb', line 10

def initialize(title)
  @title = title.capitalize
  @players = []
end

Instance Attribute Details

#titleObject (readonly)

Returns the value of attribute title.



8
9
10
# File 'lib/treasure_game/game.rb', line 8

def title
  @title
end

Instance Method Details

#add_player(p) ⇒ Object



31
32
33
# File 'lib/treasure_game/game.rb', line 31

def add_player(p)
  @players << p
end

#high_score_entry(player) ⇒ Object



15
16
17
18
# 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) ⇒ Object



27
28
29
# 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) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 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


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 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') ⇒ Object



20
21
22
23
24
25
# 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_pointsObject



35
36
37
# File 'lib/treasure_game/game.rb', line 35

def total_points
  @players.reduce(0) { |memo, object| memo += object.points }
end