[英]How to do looping in C# programming?
I have to allow 20 balls to move around the screen. 我必须让20个球在屏幕上移动。 I would like to know how do I use a loop so I would not have to type the codes out long.
我想知道如何使用循环,这样我就不必长时间输入代码。 Currently, the codes I have are
目前,我拥有的代码是
for (int i = 0; i < ballSpeedXAxis.Length; i++)
{
ballSpeedXAxis[i] = 1;
}
for (int i = 0; i < ballSpeedYAxis.Length; i++)
{
ballSpeedYAxis[i] = 1;
}
private void OnUpdate(object sender, object e)
{
Canvas.SetLeft(this.ball1, this.ballSpeedXAxis[1] + Canvas.GetLeft(this.ball1));
Canvas.SetTop(this.ball1, this.ballSpeedYAxis[1] + Canvas.GetTop(this.ball1));
Canvas.SetLeft(this.ball2, this.ballSpeedXAxis[2] + Canvas.GetLeft(this.ball2));
Canvas.SetTop(this.ball2, this.ballSpeedXAxis[2] + Canvas.GetTop(this.ball2));
...
Canvas.SetLeft(this.ball20, this.ballSpeedXAxis[20] + Canvas.GetLeft(this.ball20));
Canvas.SetTop(this.ball20, this.ballSpeedXAxis[20] + Canvas.GetTop(this.ball20));
}
ball1, ball2 ... ball3 are images name. ball1,ball2 ... ball3是图像名称。
There are varying ways.. the most obvious being instead of this: 有多种方法..最明显的替代方法是:
Image ball1;
Image ball2;
Image ball3;
// .. etc ...
You would put those in an array also: 您还可以将它们放在数组中:
Image[] balls = new Image[20];
..same with your speeds. ..与您的速度相同。 Then you can change your update method to this:
然后,您可以将更新方法更改为此:
private void OnUpdate(object sender, object e) {
for (int i = 0; i < balls.Length; i++) {
Canvas.SetLeft(balls[i], ballSpeedXAxis[i] + Canvas.GetLeft(balls[i]));
Canvas.SetTop(balls[i], ballSpeedYAxis[i] + Canvas.GetTop(balls[i]));
}
}
Others include putting the already created images into a List<Image>
.. but that's a bit yuck. 其他包括将已经创建的图像放入
List<Image>
..但这有点麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.