Permalink
Browse files

add winner-detection

  • Loading branch information...
1 parent 6981d3c commit e3f6d93ad5b3d625b10e25e05eaf942f89aa6f0b @grosser committed Dec 31, 2010
Showing with 50 additions and 1 deletion.
  1. +15 −1 lib/tic_tac_toe.rb
  2. +35 −0 spec/tic_tac_toe_spec.rb
View
@@ -26,7 +26,6 @@ class TicTacToe
attr_reader :position, :player
def initialize
- @board = BOARD
@fields = Array.new(9).fill(' ')
@position = 0
@player = PLAYERS.first
@@ -53,6 +52,21 @@ def set
switch_player
end
+ def winner
+ [
+ [0,1,2],[3,4,5],[6,7,8], # vertical
+ [0,3,6],[1,4,7],[2,5,8], # horizontal
+ [0,4,8],[2,4,6] # diagonal
+ ].each do |pattern|
+ players = pattern.map{|i| @fields[i] }.uniq
+ next if players.size != 1
+ winner = players.first
+ next if winner == ' '
+ return winner
+ end
+ nil
+ end
+
private
def switch_player
View
@@ -71,4 +71,39 @@ def ttt; subject; end
ttt.player.should == 'O'
end
end
+
+ describe :winner do
+ def set_fields(a)
+ ttt.instance_eval{@fields = a}
+ end
+
+ it "is nil when no-one has set" do
+ ttt.winner.should == nil
+ end
+
+ it "is nil when no-one has won" do
+ set_fields ['O','X','O', 'O','X','O', 'X','O','X']
+ ttt.winner.should == nil
+ end
+
+ it "finds diagonal" do
+ set_fields ['X','O',' ', ' ','X',' ', ' ','O','X']
+ ttt.winner.should == 'X'
+ end
+
+ it "finds vertical" do
+ set_fields ['X','O',' ', ' ','O',' ', ' ','O','X']
+ ttt.winner.should == 'O'
+ end
+
+ it "finds horizontal" do
+ set_fields ['X','O',' ', 'O','O','O', ' ','X','X']
+ ttt.winner.should == 'O'
+ end
+
+ it "finds multiple" do
+ set_fields ['O','O','O', 'X','O','X', ' ','X','O']
+ ttt.winner.should == 'O'
+ end
+ end
end

0 comments on commit e3f6d93

Please sign in to comment.