【问题标题】:C# Towers of Hanoi console application.C# Towers of Hanoi 控制台应用程序。
【发布时间】:2016-01-03 18:18:17
【问题描述】:

我会保持简洁。我正在学习 C# 并探索该语言的可能性。作为一名 Python 程序员,我对 .NET 领域还很陌生。

我目前正在编写一个 Towers of Hanoi 控制台应用程序。我已经理解了代码的递归部分,因为这并不具有挑战性。

这是我当前的 peg 类代码。

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("----------------");
}


}
}

这是我用于显示钉子的主类的代码。我通过将它们放入方法中来促进钉子的打印。

    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);

}

}

}

我的问题仍然存在,

如何在控制台应用程序中将“环”移动到“钉”?我了解这在 WinForms 中是如何工作的,但我想要一个挑战。

提前谢谢大家,

你在外面

【问题讨论】:

  • 将“环”移到“钉”上是什么意思?如何绘制环?

标签: c# .net windows console


【解决方案1】:

您所要做的就是修改 DrawPeg 方法以接受当前“环”的数量

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("----------------");
}

然后,您可以使用当前值调用 DrawBoard 方法(现在它们是硬编码的)

public static void DrawBoard(PegClass peg1, PegClass peg2, PegClass peg3)
{
        Console.Clear();
        peg1.DrawPeg(20, 1);
        peg2.DrawPeg(40, 2);
        peg3.DrawPeg(60, 4);
}

现在你要做的就是在你的玩家每次移动时调用具有不同环数的方法

【讨论】:

  • 伙计,我一直在寻找这样的解决方案。非常感谢您的解决方案和耐心!绝对给你声望奖励!
  • 你做了大部分工作......我只是修改了一种方法
  • 还是谢谢你。你能回答我的问题真是太好了。
猜你喜欢
  • 2018-08-20
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
  • 2021-11-14
  • 2011-08-16
  • 1970-01-01
相关资源
最近更新 更多