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
}

'@

No comments:

Post a Comment