所以我想做一个迷你游戏,当一个图像与另一个图像相交时,他们会得分。这是我的一切。我试图使一个图像(又名飞贼)移动到一个随机的位置,每次picplayer拦截与飞贼。有人也可以帮我修复我的代码,因为我的玩家随机传送出于某种原因。谢谢你
public partial class Form1 : Form
{
int x, y;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
x = 0;
y = 0;
}
private void button1_Click(object sender, EventArgs e)
{
//enable the timer when the start button is clicked
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
//create a random x and y coordinate
Random r = new Random();
x = r.Next(1, 500);
y = r.Next(1, 500);
//Creates the picturebox on your form
PictureBox villain = new PictureBox();
villain.Location = new Point(x, y);
villain.Height = 150;
villain.Width = 150;
villain.SizeMode = PictureBoxSizeMode.Zoom;
villain.Image = Properties.Resources.snitch;
this.Controls.Add(villain);
if (picPlayer.Bounds.IntersectsWith(villain.Bounds))
{
MessageBox.Show("You won");
villain.Dispose();
}
}
//Moves harry potter according to the keys pressed
private void textBox1_Keydown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
y -= 10;
}
if (e.KeyCode == Keys.Down)
{
y += 10;
}
if (e.KeyCode == Keys.Left)
{
x -= 10;
}
if (e.KeyCode == Keys.Right)
{
x += 10;
}
picPlayer.Location = new Point(x, y);
正如其他人所说,没有必要每次都为您的反派创建新的PictureBox。下面我将你的随机实例和反派PictureBox移到Form级别(与你现有的x和y变量相同的地方)。接下来,我们在Load()
事件中设置反派角色,因为这些属性不会改变。最后,我们为恶棍的随机位置使用不同的变量,这样玩家就不会被改变:
int x, y;
Random r = new Random();
PictureBox villain = new PictureBox();
private void Form1_Load(object sender, EventArgs e)
{
x = 0;
y = 0;
villain.Height = 150;
villain.Width = 150;
villain.SizeMode = PictureBoxSizeMode.Zoom;
villain.Image = Properties.Resources.snitch;
this.Controls.Add(villain);
villain.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
//enable the timer when the start button is clicked
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
//create a random x and y coordinate
int villX = r.Next(1, 500);
int villY = r.Next(1, 500);
villain.Location = new Point(villX, villY);
villain.Show();
if (picPlayer.Bounds.IntersectsWith(villain.Bounds))
{
MessageBox.Show("You won");
villain.Hide();
}
}