[我想使用可以在不影响其运动的情况下随机漫游的PictureBox制作AI,例如:PictureBox必须执行向右移动的动作,如果计时器用尽,则下一个动作将向下移动,就像它漫游的随机度一样。
我以为可以对它进行硬编码。但是可能要花很长时间,而且一旦计时器停止,就不会再次重启。 idk为什么。
Here's a Picture of my Game so you would have some ideas about it.
这里也是代码
private void Game_Load(object sender, EventArgs e)
{
E_Right.Start();
if(Upcount == 0)
{
E_Right.Start();
}
}
private void E_Right_Tick(object sender, EventArgs e)
{
if(Rightcount > 0)
{
EnemyTank.Left += 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_RIGHT_v_2;
Rightcount = Rightcount - 1;
}
if (Rightcount == 0)
{
E_Right.Stop();
E_Down.Start();
}
}
private void E_Up_Tick(object sender, EventArgs e)
{
if (Upcount > 0)
{
EnemyTank.Top -= 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_TOP_v_1;
Upcount = Upcount - 1;
}
if (Upcount == 0)
{
E_Up.Stop();
E_Right.Start();
}
}
private void E_Down_Tick(object sender, EventArgs e)
{
if (Downcount > 0)
{
EnemyTank.Top += 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_DOWN_v_1;
Downcount = Downcount - 1;
}
if (Downcount == 0)
{
E_Down.Stop();
E_Left.Start();
}
}
private void E_Left_Tick(object sender, EventArgs e)
{
if (Leftcount > 0)
{
EnemyTank.Left -= 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_LEFT_v_1;
Leftcount = Leftcount - 1;
}
if (Leftcount == 0)
{
E_Left.Stop();
E_Up.Start();
}
}
假设PictureBox位于Location(0,0)。如果您看到一个PictureBox,则坦克的图像就没关系了。这将用于用户的MainTank。
您只需一个计时器就可以完成:
int moveToX = 0;
int moveToY = 0;
int speed = 5;
Random rand = new Random();
void ChooseNextPosition() {
// Move vertical or horizontal?
if (r.Next(2) % 2 == 0) {
moveToX = r.Next(-5, 5);
}
else {
moveToY = r.Next(-5, 5);
}
}
private void Game_Load(object sender, EventArgs e) {
ChooseNextPosition();
timer1.Start();
}
private void timer1Tick(object sender, EventArgs e) {
if (moveToX != 0) {
EnemyTank.Left += moveToX * speed;
moveToX += moveToX > 0 ? -1 : 1;
}
if (moveToY != 0) {
EnemyTank.Top += moveToY * speed;
moveToY += moveToY > 0 ? -1 : 1;
}
if (moveToX == 0 && moveToY == 0) {
ChooseNextPosition();
}
}