Skip to content

Instantly share code, notes, and snippets.

@hinbody
Created May 29, 2013 03:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hinbody/5667851 to your computer and use it in GitHub Desktop.
Save hinbody/5667851 to your computer and use it in GitHub Desktop.
This is the code from my first remote pair programming session with @marksim. It was a TDD session of tic tac toe
require 'rspec'
# Tic Tac Toe
# is a game
# where two players
class Player
attr_accessor :moves
def initialize
@moves = []
end
def clear_moves
@moves = []
end
def play(x,y)
if x < 0 || x > 2 || y < 0 || y > 2
return false
end
unless @moves.include?([x, y])
@moves << [x, y]
true
else
false
end
end
def winner?
if row_winner || column_winner
true
else
false
end
end
private
def column_winner
(0..2).each do |column|
return true if @moves.select {|move| move.last == column}.count == 3
end
false
end
def row_winner
(0..2).each do |row|
return true if @moves.select {|move| move.first == row }.count == 3
end
false
end
end
describe 'Tic Tac Toe' do
describe 'Player' do
let(:player) { Player.new }
before(:each) do
player.clear_moves
end
it "can place a marker on the board" do
player.play(1, 1).should be_true
end
it "can't play the same place twice" do
player.play(1, 1).should be_true
player.play(1, 1).should be_false
end
it "can't play outside the 3x3 board" do
player.play(-1, 0).should be_false
player.play(0, -1).should be_false
player.play(3, 0).should be_false
player.play(0, 3).should be_false
end
it "wins if top row is filled" do
player.play(0, 0)
player.play(0, 1)
player.play(0, 2)
player.should be_winner
end
it "is not a winner when less than 3 markers are on the board" do
player.play(1, 1)
player.should_not be_winner
end
it "is not a winner if all 3 markers are not in a row " do
player.play(0, 0)
player.play(1, 0)
player.play(0, 2)
player.should_not be_winner
end
it "wins if the left column is filled" do
player.play(0, 0)
player.play(1, 0)
player.play(2, 0)
player.should be_winner
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment