【发布时间】:2011-11-30 05:02:38
【问题描述】:
我正在创建一个丢鸡蛋的接球游戏。在我的 Panel 子类中,我有这个代码
public void startGame()
{
Thread t = new Thread(new ThreadStart(game));
t.Start();
}
private void game()
{
bool run = true;
int level = 1;
while (run)
{
Egg egg = dropper.selectEgg();
int speed = dropper.getSpeed(level);
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate {
this.Controls.Add(egg);
egg.setInitialLocation(dropper.selectPosition());
int x = egg.Location.X;
int y = egg.Location.Y;
while (y <= 1000)
{
egg.setCurrentLocation(x, dropper.drop(egg, speed));
y = egg.Location.Y;
}
}));
}
else
{
this.Controls.Add(egg);
egg.setInitialLocation(dropper.selectPosition());
int x = egg.Location.X;
int y = egg.Location.Y;
while (y <= 1000)
{
egg.setCurrentLocation(x, dropper.drop(egg, speed));
y = egg.Location.Y;
}
}
Thread.Sleep(3000);
}
}
Egg 是 PictureBox 的子类,我想在循环中更改它的位置,以便看起来鸡蛋正在掉落。我使用 EggDropper 子类和这个方法:
public int drop(Egg egg, int speed)
{
int y = egg.Location.Y;
y += speed;
return y;
}
但不知何故,我没有看到任何 Egg 对象掉落。我猜这是线程访问 PictureBox 子类的问题?但我似乎无法在网上找到任何解决方案。
非常感谢您。
【问题讨论】:
标签: c# multithreading visual-studio panel picturebox