Visual Basic Racing Game Adapted from An Introduction to Programming in Visual Basic by Beth Brown and Bruce Presley This is a fun game programming project. The idea is to make a race between two cars. Both of the cars are controlled by timers with random values assigned to their speed. The first car that gets to the other side of the form wins! First of all take a look at the following two graphics. The first shows the layout of the form and the second shows which the property changes you will need to make. Next, do your coding for the project. The instructions are in red. Put the following in the general part of the form. Option Explicit Private Sub cmdGo_Click() tmrGo.Enabled = True End Sub Double click on the Timer for car one and enter this code: Private Sub tmrCar1_Timer() picCar1.Move picCar1.Left + Int(41 * Rnd + 20) If picCar1.Left >= (frmRacing.Width - picCar1.Width) Then Call EndRace MsgBox "Car 1 wins!" End If End Sub Double click on the Timer for car two and enter this code: Private Sub tmrCar2_Timer() picCar2.Move picCar2.Left + Int(41 * Rnd + 20) If picCar2.Left >= (frmRacing.Width - picCar2.Width) Then Call EndRace MsgBox "Car 2 wins!" End If End Sub Double click on the Timer for the Go! button and enter this code: Private Sub tmrGo_Timer() Static blnRed As Boolean, blnYellow As Boolean, blnGreen As Boolean If Not blnRed Then Call DrawRed(blnRed) ElseIf Not blnYellow Then Call DrawYellow(blnYellow) ElseIf Not blnGreen Then Call DrawGreen(blnGreen) Else tmrGo.Enabled = False picSignalLight.Cls blnRed = False blnYellow = False blnGreen = False cmdGo.Visible = False picCar1.Left = 350 picCar2.Left = 350 Note: you will need to make these two images (or use two from the Internet). picCar1.Picture = LoadPicture("car1.jpg") picCar2.Picture = LoadPicture("car2.jpg") tmrCar1.Enabled = True tmrCar2.Enabled = True End If End Sub Put the following in the general part of the form. Sub DrawRed(ByRef blnRed As Boolean) picSignalLight.FillColor = vbRed picSignalLight.FillStyle = vbFSSolid picSignalLight.Circle (200, 200), 200, vbRed blnRed = True End Sub Sub DrawYellow(ByRef blnYellow As Boolean) picSignalLight.FillColor = vbYellow picSignalLight.Circle (200, 200), 200, vbYellow blnYellow = True End Sub Sub DrawGreen(ByRef blnGreen As Boolean) picSignalLight.FillColor = vbGreen picSignalLight.Circle (200, 200), 200, vbGreen blnGreen = True End Sub Sub EndRace() tmrCar2.Enabled = False tmrCar1.Enabled = False cmdGo.Visible = True picCar1.Picture = LoadPicture picCar2.Picture = LoadPicture End Sub Now you can go ahead and run the game! Debug as necessary. |