-
-
Save fomigo/02907ece76db4150b9a825adb9202856 to your computer and use it in GitHub Desktop.
Mancala Object-Oriented Recursion example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Well | |
attr_accessor :next_well, :seeds, :owner | |
def initialize anOwner | |
self.seeds = 0 | |
self.owner = anOwner | |
end | |
def sow | |
current_seeds = self.seeds | |
self.seeds = 0 | |
self.next_well.take_seed(current_seeds, self.owner) | |
end | |
def take_seed(count, player) | |
self.seeds += 1 | |
count = count - 1 | |
if count > 0 | |
self.next_well.take_seed(count, player) | |
end | |
end | |
end | |
class GoalWell < Well | |
def take_seed(count, player) | |
if player == self.owner | |
super | |
else | |
self.next_well.take_seed(count, player) | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require './mancala' | |
require 'test/unit' | |
class WellTest < Test::Unit::TestCase | |
def setup | |
@well01 = Well.new(:player1) | |
@well02 = Well.new(:player1) | |
@goalWellPlayer1 = GoalWell.new(:player1) | |
@well03 = Well.new(:player2) | |
@well04 = Well.new(:player2) | |
@goalWellPlayer2 = GoalWell.new(:player2) | |
@well01.next_well = @well02 | |
@well02.next_well = @goalWellPlayer1 | |
@goalWellPlayer1.next_well = @well03 | |
@well03.next_well = @well04 | |
@well04.next_well = @goalWellPlayer2 | |
@goalWellPlayer2.next_well = @well01 | |
end | |
def test_well_setup | |
assert_same(@well01.next_well, @well02) | |
assert_same(@well01.owner, :player1) | |
assert_same(@well01, @goalWellPlayer2.next_well) | |
end | |
def test_sowing | |
@well01.seeds = 1 | |
@well01.sow | |
assert_equal(@well02.seeds, 1) | |
assert_equal(@well01.seeds, 0) | |
@well01.seeds = 2 | |
@well02.seeds = 1 | |
@well02.sow | |
assert_equal(@well01.seeds, 2) | |
assert_equal(@well02.seeds, 0) | |
assert_equal(@goalWellPlayer1.seeds, 1) | |
assert_equal(@well03.seeds, 0) | |
end | |
def test_sowing_to_goalWell | |
@well01.seeds = 6 | |
@well01.sow | |
#Make sure that player2's well does not have any seeds as a result of the sowing | |
assert_equal(@goalWellPlayer2.seeds, 0) | |
#well01 should only have one seed after sowing since goalWellPlayer2 should not have accepted a seed | |
assert_equal(@well01.seeds, 1) | |
#well02 should have 2 seeds, one from the initial sowing, then another from the passing of goalWellPlayer2 | |
assert_equal(@well02.seeds, 2) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment