Browse files

Delegate move validity to board.

  • Loading branch information...
1 parent 1eeaf48 commit cda4a1223d64d2a7a8bcdc1bc02c5bb967f6de96 @threedaymonk committed Oct 9, 2011
Showing with 26 additions and 12 deletions.
  1. +6 −0 lib/battleship/board.rb
  2. +5 −12 lib/battleship/game.rb
  3. +15 −0 test/board_test.rb
View
6 lib/battleship/board.rb
@@ -13,6 +13,7 @@ def valid?
end
def try(xy)
+ return :invalid unless valid_move?(xy)
@board[xy] = [:ship, :hit].include?(@board[xy]) ? :hit : :miss
end
@@ -44,6 +45,11 @@ def expand_board(fleet)
}
end
+ def valid_move?(move)
+ return false unless move.is_a?(Enumerable)
+ move.all?{ |e| (0 ... @size).include?(e) }
+ end
+
def valid_layout?(fleet)
occupied = {}
fleet.each do |ship|
View
17 lib/battleship/game.rb
@@ -3,7 +3,6 @@
module Battleship
class Game
def initialize(size, expected_fleet, *players)
- @size = size
@state = build_initial_state(size, expected_fleet, players)
@turn = 0
@@ -21,15 +20,14 @@ def tick
player, opponent, board = @state[@turn]
@turn = -(@turn - 1)
- move = player.take_turn(board.report, board.ships_remaining)
+ move = dup_if_possible(player.take_turn(board.report, board.ships_remaining))
+ result = board.try(move)
- unless valid_move?(move)
+ if result == :invalid
@winner = opponent
- return nil
+ elsif board.sunk?
+ @winner = player
end
-
- result = board.try(dup_if_possible(move))
- @winner = player if board.sunk?
result
end
@@ -53,11 +51,6 @@ def dup_if_possible(v)
v
end
- def valid_move?(move)
- return false unless move.class.ancestors.include?(Enumerable)
- move.all?{ |e| (0 ... @size).include?(e) }
- end
-
def build_initial_state(size, expected_fleet, players)
boards = players.map{ |player|
positions = player.new_game
View
15 test/board_test.rb
@@ -65,6 +65,21 @@ def test_should_report_miss
assert_equal :miss, board.try([2, 2])
end
+ def test_should_report_invalid_move_for_nil
+ board = Board.new(4, [4], [[0, 1, 4, :across]])
+ assert_equal :invalid, board.try(nil)
+ end
+
+ def test_should_report_invalid_move_for_nil_element
+ board = Board.new(4, [4], [[0, 1, 4, :across]])
+ assert_equal :invalid, board.try([nil, nil])
+ end
+
+ def test_should_report_invalid_move_for_out_of_range_coordinate
+ board = Board.new(4, [4], [[0, 1, 4, :across]])
+ assert_equal :invalid, board.try([4, 4])
+ end
+
def test_should_still_report_miss_if_try_is_repeated
board = Board.new(4, [4], [[0, 1, 4, :across]])
board.try([2, 2])

0 comments on commit cda4a12

Please sign in to comment.