我正在做《Headfirst C#》的第一个实验,遇到了一个问题:我的程序中的狗以相同的速度行动。我不明白为什么会这样,因为在我的眼中每个对象实例都会随机添加1到5像素的X坐标。这种特性的随机性应该足够产生足够的差异。
因此,由于我不想发布整个实验一的类集合,我重新创建了一个小而独立的版本,其中只有两条赛狗,没有博彩方面的内容。
Form1.Designer包含: - 两个带有猎犬图片的图片框。 - 一个开始按钮。
Greyhound.cs类:
因此,由于我不想发布整个实验一的类集合,我重新创建了一个小而独立的版本,其中只有两条赛狗,没有博彩方面的内容。
Form1.Designer包含: - 两个带有猎犬图片的图片框。 - 一个开始按钮。
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个像素。