排名第一,第二和第三的赛车游戏

时间:2019-07-06 20:46:03

标签: vb.net winforms

我在youtube上找到了有关赛车游戏的代码。代码非常简单,将图片框向左移动,直到其到达表单上的某个位置。第一个越过指定位置的人被宣布为获胜者。我想扩展此代码,以便可以声明第二和第三名。经过几周的尝试,除了使用一堆If-Then语句外,我无法完成此任务。

我已经尝试了If-Then语句来完成此任务,但是这太麻烦了,如果要添加更多的汽车,它就不能很好地工作。

这是我当前的代码:

Private Sub btnGo_Click(sender As System.Object, e As System.EventArgs) Handles btnGo.Click
    timRace.Enabled = True
End Sub

Private Sub timRace_Tick(sender As System.Object, e As System.EventArgs) Handles timRace.Tick
    Randomize()

    picCar1.Left += Rnd() * 6
    picCar2.Left += Rnd() * 6
    picCar3.Left += Rnd() * 6
    picCar4.Left += Rnd() * 6

    If picCar1.Left > 600 Then
        timRace.Enabled = False
        MsgBox("Car 1 Wins")
    End If

    If picCar2.Left > 600 Then
        timRace.Enabled = False
        MsgBox("Car 2 Wins")
    End If

    If picCar3.Left > 600 Then
        timRace.Enabled = False
        MsgBox("Car 3 Wins")
    End If

    If picCar4.Left > 600 Then
        timRace.Enabled = False
        MsgBox("Car 4 Wins")
    End If
End Sub

1 个答案:

答案 0 :(得分:3)

您可以做的一件事是将所有“汽车”添加到一个数组中,并对该数组进行迭代以“移动汽车”,并获得第二和第三名。

以下是使用与当前使用的相同技术的示例:

ancestry

结果:

Race result

但是,我鼓励您学习如何使用Random class而不是传统方式(即Private Cars As PictureBox() Private Finishers As List(Of PictureBox) Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click ' We use the `Tag` property to store the name of the car. picCar1.Tag = "Car 1" picCar2.Tag = "Car 2" picCar3.Tag = "Car 3" picCar4.Tag = "Car 4" ' Add all the four cars into the array. Cars = {picCar1, picCar2, picCar3, picCar4} Finishers = New List(Of PictureBox) timRace.Enabled = True End Sub Private Sub timRace_Tick(sender As Object, e As EventArgs) Handles timRace.Tick Dim remainingCars = Cars.Except(Finishers).ToArray() If remainingCars.Count > 0 Then For Each car As PictureBox In remainingCars Randomize() car.Left += Rnd() * 6 If car.Left > 600 Then Finishers.Add(car) Next Else timRace.Enabled = False MsgBox($"{Finishers(0).Tag} Wins" & vbNewLine & $"{Finishers(1).Tag} finished second." & vbNewLine & $"{Finishers(2).Tag} finished third.") End If End Sub Randomize)。

在这种情况下,代码将如下所示:

Rnd()