Time to Add Sticks –
This method allows you to add one stick at a time to the board.
public bool addStick(int position)
{
if (position < 0) return false;
if (position > 11) return false;
if (board[position]) return false;
board[position] = true;
return true;
}
There are three conditions.
- You can't add a stick to a position less than 0.
- You can't add a stick to a position greater than 11.
- You can't add a stick to a position that already has a stick.
In each of these three cases, the method returns FALSE, but doesn't change anything.
Coding this was where I was getting a little uncomfortable with my design. After all, if I want to make a bigger board, I have to deal with a lot of hard-coded values.
But, for now, I'm going to charge ahead.
I wrote tests for the three conditions.
$testAdd = new Sticks
if ($testAdd.addStick(-1)) {"FAIL: Should not be able to add stick to position -1."}
if ($testAdd.addStick(12)) {"FAIL: Should not be able to add stick to position 12."}
if !($testAdd.addStick(9)) {"FAIL: Should be able to add stick to position 9."}
if ($testAdd.addStick(9)) {"FAIL: Should not be able to add stick to position 9 (which is already filled)."}
One of the other features of the problem, as I described it, was to have a maximum number of sticks in the board. I could have implemented this before, but there was no way for that to have an effect before I had an addStick method.
Here's some code:
private int max;
// CONSTRUCTORS
public Sticks(int maximum)
{
max = maximum;
}
public Sticks() : this(12)
{
}
There's a private field for this and (since the number of sticks is established at instantiation) I need to define the constructor (including a default constructor, so I don't have to throw away my existing testing code.)
Oh, and here's the code added to addStick to prevent an additional stick from being added.
if (this.Value == max) return false;
New testing code:
$testMax = new Sticks(4);
if ($testMax.getType().Name -ne "Sticks") {"FAIL: test object is not a Sticks object."}
if (!($testMax.addStick(0))) {"FAIL: Should be able to add stick to position 0."}
if (!($testMax.addStick(1))) {"FAIL: Should be able to add stick to position 1."}
if (!($testMax.addStick(2))) {"FAIL: Should be able to add stick to position 2."}
if (!($testMax.addStick(3))) {"FAIL: Should be able to add stick to position 3."}
if ($testMax.addStick(4)) {"FAIL: Should not be able to add fifth stick."}
And it seems to work.
Well, the next big hurdle is moving sticks. We'll start that tomorrow.
No comments:
Post a Comment