Saturday, April 30, 2011

Warm up Project: Odometer Again

I usually don't do blog posts on weekend, but I just can't keep myself from getting started.

I'm going to start with my Odometer side project again, fitting it into the new methodology. See the March 19 post for this project.

In the short time since I wrote the last post, I've managed to forget the name of the function that I created to create new folders. I could look it up on my blog, but PowerShell is much easier than that:

prompt> Get-ChildItem function:*


It's called “newProject”.


newproject C:\Programming\PowerShellProg odometer


Then I copied all the stub programs into the relevant directories and now I need to change a little code here and there.

Now I can copy the existing code into the stub. The new file looks like this:


Add-Type @'

#define DEBUG



public class Wheel

{

// FIELDS

private int state = 0;

private Wheel next = null;

// CONSTRUCTORS

// PROPERTIES

public int Value

{

get

{

int temp = 0;

if (next != null)

{

temp = (next.Value * 10);

}

temp = temp + state;

return temp;

}

}

// METHODS - public

public int addOne()

{

click();

return Value;

}

// METHODS - private

private void click()

{

state++;

if (state > 9)

{

if (next != null)

{

next.click();

}

else

{

next = new Wheel();

next.click();

}

state = 0;

}

}


#if DEBUG

// TESTING CODE

#endif

// OVERRIDES

}

'@

My tests for this version of the project were pretty rudimentary. I'll put them in a script called legacy.ps1 and see if things run.

With a little work, everything did run. That is, the main script, in the odometer directory, loaded and ran the code and the tests.

I'm going to close out PowerShellISE and start it again, make sure it's working.

Sweet.

But this project never had that many tests and no documentation, so let's spend a little more time.


First of all, the tests I need to write are for the following:

  • Value
  • addOne()
  • click()

Click is private, so I’ll write a public wrapper for it in the testing code.

Here are my tests:

# Testing Value property

#


$testWheel = new Wheel


for ($i = 1; $i -lt 100; $i++)

{

$temp = $testWheel.addOne()

if ($testWheel.Value -ne $i) {"FAIL: Value should be $i."}

}




# END Testing Value property


# Testing click private method

#

$testWheel = new Wheel


for ($i = 1; $i -lt 1000; $i++)

{

$testWheel.test_click()

if ($testWheel.Value -ne $i) {"FAIL: Value should be $i."}

}


# END Testing click private method


# Testing addOne Method

#

$testWheel = new Wheel


for ($i = 1; $i -lt 1000; $i++)

{


if ($testWheel.addOne() -ne $i) {"FAIL: Method addOne should return $i."}

}


# END Testing addOne Method


I'm not sure how to get more failures. This code does not pass a lot of parameters around. It makes for a tight design, but boring tests.

Well, let's do the method signature documentation while we're here.


Here's the signature level documentation I wrote, using the PowerShell code documentation function I wrote in the April 28 post.


START DESCRIPTION

This class models an odometer.


Each instance of the class models a single wheel on an odometer

such that it can be incremented from 0 to 9. Once it reaches 9,

the wheel returns to 0 and increments the next wheel in the odometer.


The first wheel is the only one the user accessess directly. The first

wheel provides an interface to the user, creates the next wheel,

when necessary, and polls the next wheel for its value.


The recursive design creates as many new wheels as necessary, each 10

times larger than the wheel creating it.

END DESCRIPTION

public class Wheel

START DESCRIPTION

The value of the odometer. This is compiled by polling all the wheels

created for their values and adding them together.

END DESCRIPTION

public int Value

// METHODS - public

START DESCRIPTION

Clicks the current wheel object and returns the value of the

odometer.

END DESCRIPTION

public int addOne()

START DESCRIPTION

Changes the state of the current wheel and, if necessary,

creates or calls the next wheel in the progression to change its state.

END DESCRIPTION

public void test_click() // Wraps click()


And the verdict is:

All my prep work behaves as expected. That is, when I run the odometer.ps1 script, it loads the class and runs the tests, as expected.

Friday, April 29, 2011

Project and Class Design

I'm going to do a wind-up clock.

Here's how watches work: there's a spring with tension which is unwound in a regulated way, using a balance wheel. The balance wheel serves the same purpose as a pendulum in a pendulum clock.

My watch will have a second hand, a minute hand, an hour hand, and a day hand (a.m. v. p.m.)

I'm not going to follow my odometer design – which used the value of one wheel to drive another wheel. All the wheels on this watch will be driven off the same spring, progressing at different rates.

OK, I'm probably going to need two classes: a hand class for each of the displays and a spring class that drives the watch. Here's the division that jumps out at me:


Hand:

  • Constructor for the different types of hands
  • State for the hand
  • Methods for changing the state
  • Method for displaying or polling the state.


Spring:

  • Constructor that registers hands with the spring
  • Tick method that moves all the hands forward.
  • Wind method that tightens the spring
  • Set methods to set the value of the hands
  • Display method to show the time.
  • A main method, such that this project could be compiled as a stand-alone console app.

I'd like to set up some kind of a handshake between the two classes such that a tick is verified as having succeeded.

OK, time to start putting together the infrastructure:

  • Create a new folder, called watch, for this stuff to live in.
  • Create subfolders: Test, Code, Backup, Docs.


Actually, instead of just doing this, I'm going to capture this in a function. After some playing around, here's what I came up with:

function newProject ($rootdir, $newDir)

{

pushd $rootdir

mkdir $newDir

cd $newDir

mkdir "Test"

mkdir “Code”

mkdir “Backup”

mkdir “Docs”

popd


}

OK, now I need to populate this with stubs.

Wait, wait, wait – I am never going to remember all this, next month or next year. I'm going to document this function before I go on:

function newProject ($rootdir, $newDir)

{

LESS THAN SYMBOL#

.SYNOPSIS

Creates a directory stucture for a C# in PowerShell project.


.DESCRIPTION

Creates a directory with the specified name and the following subdirectories:

Test, Code, Backup, Docs.


.PARAMETER rootdir

The directory which will host the top level directory of the project.

.PARAMETER newDir

The name of the new top-level project directory.

#GREATER THAN SYMBOL

pushd $rootdir

mkdir $newDir

cd $newDir

mkdir "Test"

mkdir "Code"

mkdir "Backup"

mkdir "Docs"

popd


}

Now, if you type the following:

get-help newProject


You get the following:


NAME

newProject

SYNOPSIS

Creates a directory stucture for a C# in PowerShell project.

SYNTAX

newProject [[-rootdir] LESS THAN SYMBOLObjectGREATER THAN SYMBOL] [[-newDir] LESS THAN SYMBOLObjectGREATER THAN SYMBOL] [LESS THAN SYMBOLCommonParametersGREATER THAN SYMBOL]

DESCRIPTION

Creates a directory with the specified name and the following subdirectories:

Test, Code, Backup, Docs.


RELATED LINKS


REMARKS

To see the examples, type: "get-help newProject -examples".

For more information, type: "get-help newProject -detailed".

For technical information, type: "get-help newProject -full".


Or if you type:

get-help newProject -full

You get this:


NAME

newProject

SYNOPSIS

Creates a directory stucture for a C# in PowerShell project.

SYNTAX

newProject [[-rootdir] LESS THAN SYMBOLObjectGREATER THAN SYMBOL] [[-newDir] LESS THAN SYMBOLObjectGREATER THAN SYMBOL] [LESS THAN SYMBOLCommonParametersGREATER THAN SYMBOL]

DESCRIPTION

Creates a directory with the specified name and the following subdirectories:

Test, Code, Backup, Docs.


PARAMETERS

-rootdir LESS THAN SYMBOLObjectGREATER THAN SYMBOL

The directory which will host the top level directory of the project.

Required? false

Position? 1

Default value

Accept pipeline input? false

Accept wildcard characters?

-newDir LESS THAN SYMBOLObjectGREATER THAN SYMBOL

The name of the new top-level project directory.

Required? false

Position? 2

Default value

Accept pipeline input? false

Accept wildcard characters?

LESS THAN SYMBOLCommonParametersGREATER THAN SYMBOL

This cmdlet supports the common parameters: Verbose, Debug,

ErrorAction, ErrorVariable, WarningAction, WarningVariable,

OutBuffer and OutVariable. For more information, type,

"get-help about_commonparameters".

INPUTS

OUTPUTS

RELATED LINKS


Next up will be creating stubs for all the files I'll need. I did this on an ad hoc basis for the last project, so I'm just cutting and pasting and re-organizing. This is what I came up with:


stub.ps1:


pushd C:\Programming\PowerShellProg\stub

foreach ($a in dir .\Code) {

"CODE SCRIPT: $a"

invoke-expression "Code\$a" }

foreach ($a in dir .\Test) {

"TEST SCRIPT: $a"

invoke-expression "Test\$a" }

popd


CodeStub.ps1:

Add-Type @'

#define DEBUG



public class

{

// FIELDS

// CONSTRUCTORS

// PROPERTIES

// METHODS

#if DEBUG

// TESTING CODE

#endif

// OVERRIDES

}

'@

testStub.ps1:


# Testing TOPIC

#

#

#

#

#

#

#

#

# FUNCTIONS

#

#

#

#

#

# TEST DATA

#

#

#

#

#

#

# TESTS

#

#

#

#

#

# END Testing TOPIC


And I think that'll do for today.

On Monday, I'll start creating classes.

Thursday, April 28, 2011

Next Project: Goals

I've been thinking about the next project for this blog.

The point of all this has never been to write a program that allowed me to drop sticks on a non-existent board. I wanted to practice with a programming methodology that allowed me to create code in a reliable way. This is what I came up with:

  • Class code, wrapped in Add-Type, existing in separate files.

  • Code signatures documented.

  • Some comment-level documentation.

  • Testing code wrapped in #if #endif preprocessor commands.

  • Testing scripts that live in a directory and give output only when they fail.

I should be able to leverage PowerShell's string-based scripting should be useful for something. Hey, let's try something.

The Get-Content cmdlet will let us look at the file contents:

blog>get-content matchcode.ps1


This displays the whole file contents.


So, suppose I want to pull out all the lines with comments – I could do this:

get-content matchcode.ps1 | select-string "//"

Here's the last few lines in the output:

// METHODS -- PRIVATE

if (candidate < 1) return false; // checks for -1, which is used for non-location positions in the nodes

if (x.currentNode(candidate)) return true; // Checks all the nodes to see if a candidate exists.

// TESTING CODE

// Clone method: for now, just used in testing

// Just used in testing

return new Stick(false); // Return to this later


Of course, these aren't the javadoc-like comments I added for the method signatures. Those started with “/*”:

get-content matchcode.ps1 | select-string "/*"

I was really beating my head against the wall (figuratively) about why this wasn't working. It was returning all the lines. The asterisk is being used as a wild card.

I went through the documentation for select-string to see about PowerShell's regular expressions. After futzing around with it for a while, I came up with the following function:


function doc ($x) {


if (select-string -inputobject $x "/\*" -quiet)

{

$global:b = (1 -eq 1)


}

if (select-string -inputobject $x "\*/" -quiet)

{

$global:b = (1 -eq 0)


}

if ($b) {$x}

}


This is pretty good – pulls out all the stuff. Let me play with this a little longer.

OK, I moved things around a little:

function doc ($x) {


if (select-string -inputobject $x "\*/" -quiet)

{

$global:b = (1 -eq 0)


}


if ($b) {$x}


if (select-string -inputobject $x "/\*" -quiet)

{

$global:b = (1 -eq 1)


}

}


The way that I had it originally meant that lines with “*\” printed. With a little reordering, I got it to display only lines without either “/*” or “*?”. Thanks Grimm Brothers! (No joke. The Grimm brothers described the ordering of the first and second Germanic sound shifts in order based on the effect the sound shifts had in the language.)

After adding some lines with seperators, this is the output:

START METHOD DESCRIPTION:

Gets the stick object at a specified board location.

loc: Location.

returns: Stick at loc.

TESTING CODE: DO NOT CALL EXCEPT FOR TEST

This code refers directly to the grid array. As such, it is subject to out-of-bounds errors.

The private method getStick is not subject to such errors.

END METHOD DESCRIPTION:

START METHOD DESCRIPTION:

Gets the node object specified by 0-based index.

loc: Node to be returned

returns: Node at specified index.

TESTING CODE: DO NOT CALL EXCEPT FOR TEST

END METHOD DESCRIPTION:


And then I added this line, in the middle:

if (select-string -inputobject $x -quiet "public") {" "; $x; " "}

Here's the last few lines using the script as is:


START METHOD DESCRIPTION:

Causes a stick to fall from the specified location to a lower location.

location: Stick to fall.

Returns true if a stick can fall. False if the stick is stopped

for any reason.

END METHOD DESCRIPTION:

public bool test_dropStick(int location)

START METHOD DESCRIPTION:

Gets the stick object at a specified board location.

loc: Location.

returns: Stick at loc.

TESTING CODE: DO NOT CALL EXCEPT FOR TEST

This code refers directly to the grid array. As such, it is subject to out-of-bounds errors.

The private method getStick is not subject to such errors.

END METHOD DESCRIPTION:

public Stick test_getStick(int loc)

START METHOD DESCRIPTION:

Gets the node object specified by 0-based index.

loc: Node to be returned

returns: Node at specified index.

TESTING CODE: DO NOT CALL EXCEPT FOR TEST

END METHOD DESCRIPTION:

public Node test_getNode(int loc)

public bool test_isValid(int candidate)

That was all fun.

To get back to the goal of this post, I was thing of doing another small project using this methodology from the ground up. Something simple, like my odometer example from a few weeks back. Include a main() method, so I can compile it outside PowerShell if I really want to. Maybe try to do it over the course of a week or so.

So, tomorrow, project design.

Wednesday, April 27, 2011

Some Tests for the Stick Class

I decided to post some of my test scripts. I didn't want to post all of them – that's a little much to dig through. I'm going to include the tests for the Stick class. This is the smallest of the classes.

Here's one of the constructors:


# Testing Stick Class Constructor bool


# Test True:

$testStick = new Stick(1 -eq 1)

if (!($testSTick.Value)) { "FAIL: Stick should be able to take value of True." }


# Test False:

$testStick = new Stick(1 -eq 2)

if ($testSTick.Value) {"FAIL: Stick should be able to take value of False." }



#

# END Testing Stick Class Constructor bool


I didn't see much to test, here. It takes a Boolean and there are only two values, both of which are acceptable.


Here's the other constructor:

# Testing Stick Class Constructor INT



# Test normal values (1 to 60):


for ($location = 1; $location -lt 61; $location++)

{

$testStick = new Stick($location)

if (!($testStick.Location -eq $location)) { "FAIL: Stick should be able to take value of $location" }


}


$testStick = new Stick(-1)

if (!($testStick.Location -eq -1)) {"FAIL: Stick is not validated to prohibit a value of -1." }

$testStick = new Stick(0)

if (!($testStick.Location -eq 0)) {"FAIL: Stick is not validated to prohibit a value of 0." }

$testStick = new Stick(61)

if (!($testStick.Location -eq 61)) {"FAIL: Stick is not validated to prohibit a value of 61." }

#

# END Testing Stick Class Constructor INT


There's no validation of locations going in to this constructor. Validation is done somewhere else. I wanted to leave this out of the Stick class, if I could, in anticipation of changing the board, making it bigger, in the future.

This did lead me to a little confusion, however, over tests for the Location property:

# Testing Location Property


$testLocationStick = new Stick(0)


for ($a = 0; $a -lt 1000; $a++)

{

$testLocationStick.Location = $a

if (!($testLocationStick.Location -eq $a)) {"FAIL: Location not set correctly."}

}


try

{

$testLocationStick.Location = -1

{"FAIL: -1 is not valid value for Location."}

}

catch {}

# END Testing Location Property


Again, this test simply tries a bunch of values that won't fail, but look at the last test. That one tries to assign a value of -1 to this property and fails. In the previous test script, the value of -1 was assigned without error.

The reason for this in the code is that there is validation on the Location property. The constructor sets the value directly, not though this property.

A value of -1 is used for locations that don't exist in individual nodes. That is, a node might be associated with position 1 and position 6 (as node 0 is) but no other positions. The other positions in that node's position array have their values set to -1.

Those aren't stick values, though.

Ideally, if an object can't have a value, it shouldn’t be able to get that value. That's almost tautological. This design can accommodate that, simply by using a call to the Location property in the constructor.

But will that break anything? I can try it and run the tests.

That change only caused the FAIL in the constructor test. As long as the tests cover all the expected behavior of the system, I can re-write that test as follows:


try {

$testStick = new Stick(-1)

{"FAIL: -1 is not valid value for Location."}

}

catch {}

Finally, here's the test script for the Value property:

# Testing Value Property



$testLocationStick = new Stick(1 -eq 1)

if (!($testLocationStick.Value)) {"FAIL: Stick should have a value of True."}


$testLocationStick = new Stick(1 -ne 1)

if ($testLocationStick.Value) {"FAIL: Stick should have a value of False."}


# END Testing Value Property

There's only two values, both of them acceptable.

Now that I think about it, I could just use the isValid method to validate the Location property. It works by polling the node array. That wouldn't require hard-coding any values into Stick.

Tuesday, April 26, 2011

C# Code as of April 26

As usual, you can copy this into PowerShell and run it. See the March 18 post for more information.

Tomorrow, I'll include a couple of test scripts.

Add-Type @'
#define DEBUG

using System;
using System.Collections.Generic;
using System.Text;

public class Node
{
// FIELDS
// Array of the four locations around this node.
private int[] position = new int[4];
// The board object associated with this node.
private Board board;

// CONSTRUCTORS

/*
Assigns position numbers to the specified node.

temp: The number associated with this node. Not use elsewhere, even by Board.
currentBoard: The board object associated with this node.
*/
public Node(int temp, Board currentBoard)
{
board = currentBoard; // set for current board.
// GENERAL CASE

position[0] = temp + (((temp / 6) - 1) * 5);
position[1] = position[0] + 6;
position[2] = position[0] + 11;
position[3] = position[0] + 5;

// EDGE CASES: TOP EDGE


if (position[0] < 1) position[0] = -1;

// BOTTOM EDGE
if (position[2] > 60) position[2] = -1;

//LEFT EDGE
if (temp % 6 == 0) position[3] = -1;

//RIGHT EDGE
if ((temp + 1) % 6 == 0) position[1] = -1;

}

// PROPERTIES

// PUBLIC METHODS
/*
Implments the move. If move is valid, makes the
origin have a value of false and the destination have a value of true.

origin: Starting location for move.
destination: Ending location for move.

returns: True if move suceeds, false if it fails for any reason.
*/
public bool doMove(int origin, int destination)
{
// Do the origin and destination belong to the same node?
if (!currentNode(origin)) return false;
if (!currentNode(destination)) return false;

// Are they offset by 90 degrees?
if (!offset90(origin, destination)) return false;

// Is origin filled?
if (!isFilled(origin, board)) return false;

// Is the destination empty?
if (isFilled(destination, board)) return false;

// Do the move and return true.
board.getStick(origin).Location = destination;
return true;

}


/*
Implements the fall. If the stick can fall, it falls a single level down:
from position 0 to position 1 or 3, from position 1 to position 2, or from
position 3 to position 2.
Returns a value of false if the stick cannot fall. Otherwise, returns a value of true.

location: Location of stick to fall. Passed by reference to pass back current
location of stick for future falls.

returns: True if stick can fall. Otherwise, false.
*/
public bool fall(ref int location)
{
// Does this location belong to this node?
if (!(currentNode(location))) return false;
// Does this location have a stick?
if (!isFilled(location, board)) return false;

switch (nodePosition(location))
{
case 0:
// Can it fall to position 1?
if (!isFilled(position[1], board))
{
doMove(position[0], position[1]);
location = position[1]; // set location to the new position
return true;
}

// Can it fall to position 3?

else if (!isFilled(position[3], board))
{
doMove(position[0], position[3]);
location = position[3]; // set location to the new position
return true;
}
break;

case 1:
if (!isFilled(position[2], board))
{
doMove(position[1], position[2]);
location = position[2]; //// set location to the new position
return true;
}

break;

case 2:

break;

case 3:
if (!isFilled(position[2], board))
{
doMove(position[3], position[2]);
location = position[2]; //// set location to the new position
return true;
}
break;

default:
break;
}
return false; // No fall could happen.

}

/*
Whether a specified location is associated with the current node.

possible: location to be checked.
returns: true if the location is associated with this node, false otherwise.
*/
public bool currentNode(int location)
{
foreach (int x in position) { // check each of the locations associated with this node.
if (x == location) return true;
}
return false;
}


// PRIVATE METHODS

/*
Whether a location has a stick with a value of true.

location: The location to be checked.
board: The board to check against.

returns: The value (true or false) of a stick at the location.
*/
private bool isFilled(int location, Board board)
{
return board.getPositionValue(location);
}

/*
Whether two locations are offset by 90 degrees around this node.

origin: One of the two locations.
destination: One of the two locations.

returns: true if and only if the two locations are 90 degrees offset.
*/
private bool offset90(int origin, int destination)
{
if ((nodePosition(origin) == 0) && (nodePosition(destination) == 1)) return true; // Check for 90 offset
if ((nodePosition(origin) == 0) && (nodePosition(destination) == 3)) return true;
if ((nodePosition(origin) == 1) && (nodePosition(destination) == 0)) return true;
if ((nodePosition(origin) == 1) && (nodePosition(destination) == 2)) return true;
if ((nodePosition(origin) == 2) && (nodePosition(destination) == 1)) return true;
if ((nodePosition(origin) == 2) && (nodePosition(destination) == 3)) return true;
if ((nodePosition(origin) == 3) && (nodePosition(destination) == 2)) return true;
if ((nodePosition(origin) == 3) && (nodePosition(destination) == 0)) return true;
return false;
}

/*
Gets the node position of a location with respect to this node.

This only makes sense internal to this node.

returns: Node position (0 to 3) or 77 as an error code.
*/
private int nodePosition (int location)
{
for (int x = 0; x < 4; x++)
{
if (position[x] == location) return x; // check for the position that corresponds to that location.
}
return 77; // error code, somewhat hacky.
}


# if DEBUG

// TESTING CODE
/* WRAPS nodePosition FOR TESTING */
public int test_nodePosition (int location)
{
return nodePosition(location);
}

/* WRAPS offset90 FOR TESTING */
public bool test_offset90(int origin, int destination)
{
return offset90(origin, destination);
}

/*
Gets the location associated with a specified element of a node.

This concept is meaningless within the program design.

DO NOT USE, EXCEPT IN TESTS
*/
public int test_getLocation (int temp)
{
if (temp < 0) return -1; // Validate
if (temp > 3) return -1;
return position[temp]; // Get the value
}

/*
Returns a null node for testing purposes.
DO NOT USE, EXCEPT IN TESTS
*/
public Node test_getNull() // I think this is a hack.
{
return null;
}


#endif



}


public class Stick {
// FIELDS
// Value of a stick (true or false).
private bool stickValue = true;
// Location of a stick.
private int location = 0;

// CONSTRUCTORS
/*
Sets the value of a stick location to the specified value.

The default value of a stick is the invalid value 0.

*/
public Stick (int temp)
{
location = temp; // Set location to specified value.

}

/*
Creates a stick instance with a stickValue as provided.

Default value is true.

temp: Value for this stick.
*/
public Stick (bool temp)
{
stickValue = temp; // Set stickValue to provided value.
}

// PROPERTIES
/*
Integer location of a stick.
*/
public int Location
{
get {
return location;
}
set {
if (value < 0) throw new Exception();
location = value;
}
}
/*
The value of an individual stick, either true or false.
*/
public bool Value
{
get {
return stickValue;
}
}
// METHODS


// TESTING CODE



// OVERRIDES
}


public class Board
{

// FIELDS
// The sticks associated with a board, referred to as 1 to 60.
ListstickList = new List();
// The nodes of the board.
private Node[] nodes = new Node[36];
// Maximum number of sticks possible on the board.
private int max = 60;

// CONSTRUCTORS

/*
Sets the maximum value for the board object and initializes nodes array.

maximum: Maximum number of sticks allowed to be added to board.
*/

public Board(int maximum)
{
if (maximum < 0) { throw new Exception(); } // Validate possible maximum.
if (maximum > 60) { throw new Exception(); }
max = maximum; // Set max.
for (int i = 0; i < 36; i++)
{
nodes[i] = new Node(i, this); // Create nodes.
}


}



// PROPERTIES
/* Returns the number of sticks (value of true) on the board. */
public int Value
{
get // It's possible this could be redone just taking the length of the list - only if no false sticks are used for anything.
{
int temp = 0;
foreach (Stick i in stickList) // go through the sticks and count up the ones that are TRUE
{
if (i.Value) temp++;
}
return temp;
}
}


// METHODS -- PUBLIC
/*
Moves a stick according the established rules: A stick must exist (value of true) and can
be moved into a valid open space (value of false) 90 degrees offset.

if the move is not valid for any reason, the method changes nothing.

origin: Starting location of stick.
destination: Final location for stick.
returns: True if the move is accomplished. False if the move is not accomplished for any reason.
*/

public bool moveStick(int origin, int destination)
{
if (!(isValid(origin))) return false; // Check whether origin is a valid location
if (!(isValid(destination))) return false; // Check whether destinatin is a valid location

// origin and destination must share a node
foreach (Node x in nodes) {
if (x.doMove(origin, destination)) return true; // Attempt a move for every node.
} // Because every stick belongs to 2 nodes, must check every node to see if sticks belong.

return false;

}


/*
Causes a stick to fall from the specified location to the lowest possible location.

location: Stick to fall.

Returns true if the specified stick falls. False if the stick cannot fall.
*/
public bool dropStickRecurse(int location)
{
bool temp = true; // Controls the while-loop.
bool result = false; // Needs to return true only if there was movement.
if (!(isValid(location))) return false; // false if the stick location isn't valid in teh first place.
while (temp) {
temp = false;
foreach (Node x in nodes) // Go through all nodes
{
if (x.fall(ref location)) // If a stick can fall, it does and
{
temp = true; // temp is set to true, so the while loop can start again
result = true; // result to true. Cannot be changed back, so if stick moves then will be true.
break; // Break out of foreach loop and go back to the while loop.
}
}
}
return result;
}


/*
Gets the value of a stick at the specified location.

location: The location to be queried.
returns: True if the location is valid and the stick has a value of true.
False otherwise, including if the location is invalid for this board.
*/

public bool getPositionValue(int location)
{
if (!(isValid(location))) return true; // check for valid location and return true -- Keeps something else from breaking.
return getStick(location).Value; // Return the value.
}

/*
Sets the value of a stick at the specified location to true.


location: The stick to be changed.
returns: True on success. False if the location is not valid or if the value
of the stick is already true.
*/
public bool addStick(int location)
{
if (!(isValid(location))) return false; // Verify location is valid.
if (getStick(location).Value) return false; // Verify location is currently false.
if (this.Value >= max) return false; // Verify that adding a stick will not exceed the stick limit for this board instance.
stickList.Add(new Stick(location)); // Add stick object to stickList
return true; // NOTE FOR FUTURE: does Add return a true for success? If so, can this be merged with next line?
} // true for an added stick.

/*
Sets the value of a stick at the specified location to false.

location: The stick to be changed.
returns: True on sucess. False if the location is not valid or if the value
of the stick is already false.
*/

public bool removeStick(int location)
{
if (!(isValid(location))) return false; // Verify location is valid.
if (!getStick(location).Value) return false; // Verify that location value is true.
stickList.Remove(getStick(location)); // Remove stick from stickList.
return true; // Return true for success.
}


public override string ToString()
{
StringBuilder display = new StringBuilder(144);

display.Append(displayOddRow(1));
display.Append(displayEvenRow(6));
display.Append(displayOddRow(12));
display.Append(displayEvenRow(17));
display.Append(displayOddRow(23));
display.Append(displayEvenRow(28));
display.Append(displayOddRow(34));
display.Append(displayEvenRow(39));
display.Append(displayOddRow(45));
display.Append(displayEvenRow(50));
display.Append(displayOddRow(56));

return display.ToString();

}



/* Gets the stick object associated with a location.
Works by testing the location against all the locations in the board.
This approach does not depend on the number of positions available in the board.

location: Location of stick to get.
returns: Stick at specified location.
*/

public Stick getStick(int location)
{
if (isValid(location)) { // Check for validity

foreach (Stick x in stickList) {
if (x.Location == location) return x; // look for a stick with the specified location.
}

}
return new Stick(false); // return a new false stick. Used as an error code.
}



// METHODS -- PRIVATE

private string displayOddRow(int start)
{
StringBuilder displayOdd = new StringBuilder("o");

for (int i = start; i < start + 5; i++)
{
if (getPositionValue(i)) {displayOdd.Append("-");}
else {displayOdd.Append(" ");}
displayOdd.Append("o");
}

displayOdd.Append("\r\n");
return displayOdd.ToString();
}

private string displayEvenRow(int start)
{
StringBuilder displayEven = new StringBuilder();
for (int i = start; i < start + 5; i++)
{
if (getPositionValue(i)) {displayEven.Append("|");}
else {displayEven.Append(" ");}
displayEven.Append(" ");
}

if (getPositionValue(start + 5)) {displayEven.Append("|");}
else {displayEven.Append(" ");}


displayEven.Append("\r\n");



return displayEven.ToString();
}

/* Checks whether a location is a valid location in this board.

Works by testing the location against all the locations in the board.
This approach does not depend on the number of positions available in the board.

candidate: The integer being tested.
returns: True if the candidate value is a valid position on the board. False otherwise.
*/

private bool isValid(int candidate)
{
if (candidate < 1) return false; // checks for -1, which is used for non-location positions in the nodes
foreach (Node x in nodes)
{
if (x.currentNode(candidate)) return true; // Checks all the nodes to see if a candidate exists.
}
return false;
}

# if DEBUG
// TESTING CODE

// Clone method: for now, just used in testing
public Board Clone()
{
Board newBoard = new Board(max);
foreach (Stick stick in stickList)
{
newBoard.addStick(stick.Location);
}
return newBoard;
}

// Just used in testing
public bool isEqualTo(Board x)
{

foreach (Stick stick in stickList)
{
foreach (Stick otherStick in x.stickList)
{
if (stick.Location == otherStick.Location) {goto start;}
}
return false;
start: continue;

}


foreach (Stick otherStick in x.stickList)
{
foreach (Stick stick in stickList)
{
if (otherStick.Location == stick.Location) {goto start2;}
}
return false;
start2: continue;

}
return true;

}


/*
Causes a stick to fall from the specified location to a lower location.

location: Stick to fall.

Returns true if a stick can fall. False if the stick is stopped
for any reason.
*/
public bool test_dropStick(int location)
{
if (!(isValid(location))) return false;
foreach (Node x in nodes)
{
if (x.fall(ref location)) return true;
}
return false;
}
/*
Gets the stick object at a specified board location.

loc: Location.
returns: Stick at loc.

TESTING CODE: DO NOT CALL EXCEPT FOR TEST

This code refers directly to the grid array. As such, it is subject to out-of-bounds errors.
The private method getStick is not subject to such errors.
*/
public Stick test_getStick(int loc)
{
if (isValid(loc)) {
return getStick(loc);
}
return new Stick(false); // Return to this later
}


/*
Gets the node object specified by 0-based index.

loc: Node to be returned
returns: Node at specified index.

TESTING CODE: DO NOT CALL EXCEPT FOR TEST
*/
public Node test_getNode(int loc)
{
return nodes[loc];
}

public bool test_isValid(int candidate)
{
return isValid(candidate);
}

#endif
}

'@