【发布时间】:2011-09-16 15:53:12
【问题描述】:
我想实现一个程序,在控制台上显示一些随机移动的字符,每个字符都有不同的速度。
我创建了一种递归方法,可以在控制台上随机移动一个字母。当我想移动两个字母时,我使用两个线程调用相同的方法。
该程序在最初的几分钟内运行良好,但过了一段时间后,这些字母开始在控制台上到处出现!
我真的很确定我的递归方法没问题(我什至尝试创建另一种方法,这次只是使用 while(i
非常感谢。
编辑:对不起,这是一个示例代码(不要考虑如果字母处于相同位置会发生什么)。字母在“体育场”上移动,它们在 x 轴上移动 20 - 51,在 y 轴上移动 5 - 26。
public void WriteAt(string s, int x, int y)
{
try
{
Console.SetCursorPosition(x, y);
Console.Write(s);
}
catch (ArgumentOutOfRangeException e)
{
Console.Clear();
Console.WriteLine(e.Message);
}
}
public void impresion()
{
int x = random.Next(20, 51);
int y = random.Next(5, 26);
WriteAt("A", x, y);
imprimir("A", x, y, 80);
}
public void impresion2()
{
int x = random.Next(20, 51);
int y = random.Next(5, 26);
WriteAt("E", x, y);
imprimir2("E", x, y, 20);
}
public void go()
{
Thread th1 = new Thread(impresion);
Thread th2 = new Thread(impresion2);
th1.Start(); //creates an 'A' that will move randomly on console
th2.Start(); //creates an 'E' that will move randomly on console
}
public void imprimir(string s, int x, int y, int sleep)
{
Thread.Sleep(sleep);
WriteAt(" ", x, y);
int n = random.Next(1, 5);
if (n == 1)
{
if ((x + 1) > 50)
{
WriteAt(s, x, y);
imprimir(s, x, y, sleep);
}
else
{
WriteAt(s, x + 1, y);
imprimir(s, x + 1, y, sleep);
}
}
else if (n == 2)
{
if ((y - 1) < 5)
{
WriteAt(s, x, y);
imprimir(s, x, y, sleep);
}
else
{
WriteAt(s, x, y - 1);
imprimir(s, x, y - 1, sleep);
}
}
else if (n == 3)
{
if ((x - 1) < 20)
{
WriteAt(s, x, y);
imprimir(s, x, y, sleep);
}
else
{
WriteAt(s, x - 1, y);
imprimir(s, x - 1, y, sleep);
}
}
else
{
if ((y + 1) > 25)
{
WriteAt(s, x, y);
imprimir(s, x, y, sleep);
}
else
{
WriteAt(s, x, y + 1);
imprimir(s, x, y + 1, sleep);
}
}
}
【问题讨论】:
-
您忘记包含代码
-
不清楚为什么每个字符都需要递归方法。随着角色移动,该堆栈将快速增长。正如@orn 所说,发布一些代码
标签: c# multithreading recursion console