Class: StackWars::Game

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(battlefield) ⇒ Game

Returns a new instance of Game.



3
4
5
6
7
# File 'lib/stack_wars/game.rb', line 3

def initialize(battlefield)
  @players         = [Player.new("black"), Player.new("white")].cycle
  @battlefield     = battlefield
  start_new_turn 
end

Instance Attribute Details

#active_playerObject (readonly)

Returns the value of attribute active_player.



9
10
11
# File 'lib/stack_wars/game.rb', line 9

def active_player
  @active_player
end

Instance Method Details

#game_overObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/stack_wars/game.rb', line 37

def game_over
  ap_deployed_armies  = battlefield.deployed_armies(active_player)
  opp_deployed_armies = battlefield.deployed_armies(opponent)

  if active_player.reserves + ap_deployed_armies == 0 ||
     opponent.reserves      + opp_deployed_armies == 0
    case
    when active_player.successful_invasions > opponent.successful_invasions     
      throw :game_over, "#{active_player.color} won!"
    when active_player.successful_invasions < opponent.successful_invasions
      throw :game_over, "#{opponent.color} won!"
    else
      throw :game_over, "its a draw"
    end
  end
end

#opponentObject



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

def opponent
  @players.peek
end

#play(pos1, pos2 = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/stack_wars/game.rb', line 15

def play(pos1, pos2=nil)
  if pos2.nil?
    territory = territory_at(pos1)     
    
    territory.fortify(active_player)
  else
    from = territory_at(pos1)
    to   = territory_at(pos2)

    raise Errors::IllegalMove unless battlefield.adjacent?(from, to)
    raise Errors::IllegalMove unless from.occupied_by?(active_player)

    if to.occupied_by?(opponent)
      attack(from, to)
    else
      move_army(from, to) 
    end
  end
  
  game_over || start_new_turn
end

#start_new_turnObject



54
55
56
# File 'lib/stack_wars/game.rb', line 54

def start_new_turn
  @active_player = @players.next
end