【发布时间】:2014-01-19 11:30:57
【问题描述】:
我正在研究 headfirst C# 的第一个实验室。我在我的程序中遇到了一个问题,即狗以相同的速度行驶。我不知道他们为什么这样做,因为在我看来,每个对象实例都会在其 X 位置添加一个随机的 1 到 5 个像素。这种随机性应该足以产生影响。
因此,因为我不想发布我的实验室 1 的全部课程,所以我重新创建了一个小型且独立的版本,只有两只狗赛跑,没有投注方面。
Form1.Designer 包含: - 两个装着猎犬的画框。 -a 开始按钮
Greyhound.cs 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace test
{
public class Greyhound
{
public int DogID;
public PictureBox myPictureBox;
public Point StartingPosition;
public Point CurrentPosition;
public Random Randomizer;
public bool Run()
{
int AddDistance = Randomizer.Next(1, 7);
CurrentPosition.X += AddDistance;
myPictureBox.Location = CurrentPosition;
if (CurrentPosition.X > 600)
{
return true;
}
else
{
return false;
}
}
public void ReturnToStart()
{
CurrentPosition = StartingPosition;
myPictureBox.Location = StartingPosition;
}
}
}
Form1.cs 类:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
Greyhound One = new Greyhound() { DogID = 1, myPictureBox = pictureBox1, StartingPosition = pictureBox1.Location, CurrentPosition = pictureBox1.Location, Randomizer = new Random() };
Greyhound Two = new Greyhound() { DogID = 2, myPictureBox = pictureBox2, StartingPosition = pictureBox1.Location, CurrentPosition = pictureBox2.Location, Randomizer = new Random() };
if (One.Run())
{
timer1.Enabled = false;
MessageBox.Show("Dog One WON!");
}
else if (Two.Run())
{
timer1.Enabled = false;
MessageBox.Show("Dog Two WON!");
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
}
}
有人能看出它的创建方式有什么问题吗?这就是为什么狗会以相同的速度跑,而不是每次随机跑 1 到 5 个像素的原因。
【问题讨论】:
-
+1 表示创建了一个简化版本来显示问题
标签: c# performance random