Reputation: 125
I'll keep this succinct. I am learning C# and exploring the possibilities of the language. Being a python programmer by heart, I am fairly new to the .NET realm.
I am currently writing a Towers of Hanoi console application. I already understand the recursion part of the code as that is not challenging.
Here is my current code for my peg class.
namespace Tower_of_hanoi
{
class PegClass
{
private int pegheight;
private int y = 3;
int[] rings = new int[0];
public PegClass()
{
// default constructor
}
public PegClass(int height)
{
pegheight = height;
}
// other functions
public void AddRing(int size)
{
Array.Resize(ref rings, rings.Length + 1);
rings[rings.Length - 1] = size;
}
public void DrawPeg(int x)
{
for (int i = 1; i <= pegheight; i++)
{
Console.SetCursorPosition(x, y);
Console.WriteLine("|");
y++;
}
if (x < 7)
{
x = 7;
}
Console.SetCursorPosition(x - 7, y); // print the base
Console.WriteLine("----------------");
}
}
}
And this is my code for the main class to display the pegs. I have facilitated the printing of the pegs by putting them in a method.
namespace Tower_of_hanoi
{
class Program
{
static void Main(string[] args)
{
PegClass myPeg = new PegClass(8);
PegClass myPeg2 = new PegClass(8);
PegClass myPeg3 = new PegClass(8);
DrawBoard(myPeg, myPeg2, myPeg3);
Console.ReadLine();
}
public static void DrawBoard(PegClass peg1,PegClass peg2,PegClass peg3)
{
Console.Clear();
peg1.DrawPeg(20);
peg2.DrawPeg(40);
peg3.DrawPeg(60);
}
}
}
My question remains,
How does one move "rings" over to "pegs" in a console application? I understand how this would work in WinForms, but I want a challenge.
Thank you everyone in advance,
youmeoutside
Upvotes: 3
Views: 1549
Reputation: 7618
All you have to do ,is modify the DrawPeg method to accept the number of current "rings"
public void DrawPeg(int x, int numberOfRings = 0)
{
for (int i = pegheight; i >= 1; i--)
{
string halfRing = new string(' ', i);
if (numberOfRings > 0)
{
if (i <= numberOfRings)
halfRing = new string('-', numberOfRings - i + 1);
}
Console.SetCursorPosition(x - halfRing.Length * 2 + i + (halfRing.Contains("-") ? (-i + halfRing.Length) : 0), y);
Console.WriteLine(halfRing + "|" + halfRing);
y++;
}
if (x < 7)
{
x = 7;
}
Console.SetCursorPosition(x - 7, y); // print the base
Console.WriteLine("----------------");
}
Then ,you can call your DrawBoard method with your current values (Now they are hard-coded)
public static void DrawBoard(PegClass peg1, PegClass peg2, PegClass peg3)
{
Console.Clear();
peg1.DrawPeg(20, 1);
peg2.DrawPeg(40, 2);
peg3.DrawPeg(60, 4);
}
Now all you have to do ,is call the methods with different numbers of rings every time your player makes a move
Upvotes: 1