【发布时间】:2016-01-08 04:42:51
【问题描述】:
扩展我之前的帖子,我仍在写河内塔。在解释了如何在钉子上画戒指的绝妙解决方案之后,我仍然有一个问题我已经摆弄了很长一段时间了。
这是我的 PegClass:
namespace Towers_Of_Hanoi
{
class PegClass
{
private int pegheight;
private int y = 3;
int[] rings = new int[0];
public PegClass()
{
//this is the default constructor
}
public PegClass(int height)
{
pegheight = height;
}
// other user defined functions
public void AddRing(int size)
{
Array.Resize (ref rings, rings.Length + 2);
rings[rings.Length - 1] = size;
}
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 of the peg
Console.WriteLine("----------------");
}
}
}
这是我的主要方法。
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.WriteLine ("\t\t\nWelcome to kTowers!");
while (true)
{
string input = "\nWhat peg do you want to move to commander?";
Console.WriteLine (input);
if (input == "2")
{
myPeg.DrawPeg (2);
}
Console.ReadLine ();
}
}
public static void DrawBoard(PegClass peg1,PegClass peg2,PegClass peg3)
{
Console.Clear();
peg1.DrawPeg(20,1);
peg2.DrawPeg(40,2);
peg3.DrawPeg(60,4);
}
}
}
这是当前的输出:
| | |
| | |
| | |
| | |
| | -|-
| | --|--
| -|- ---|---
-|- --|-- ----|----
---------------- ---------------- ----------------
我的问题仍然存在,当被要求提示时,如何将“-”字符从一个钉子移到另一个钉子。我已经尝试调整它几个小时,但仍然无法弄清楚。
提前谢谢你,youmeoutside
【问题讨论】:
-
欢迎堆栈溢出!请,下次您发布问题时,您可以正确缩进吗?它不仅可以帮助人们阅读和理解您的代码,还可以让您和其他阅读代码的人更整洁。
-
为了更好地理解您的问题,您要移动控制台原始输出上的钉子吗?或者您想在每次输入后重新绘制一个新的挂钩系统?
-
您必须将环创建为单独的对象。正如它现在显示的那样,您有 3 个宽度相同的环,这不是河内的塔,这是不同的东西。因此,钉子的“高度”取决于你有多少个环,但你需要将环实例化为具有宽度的具体对象。
-
@Rob,对于给 Rob 带来的轻微不便,我们深表歉意,感谢您的帮助。
-
@Ruskin,我希望能够移动控制台原始输出上的钉子。因此,例如,第一个钉子有 3 个环,那么您必须将这些环相应地移动到其他钉子上。