This program simulates a pinball machine as illustrated in the Figure below. The ball is dropped at the top of the machine. When the ball rolls down, it strikes fixed pins and bounces to the left or to the right in a random fashion. At the end, the ball lands in one of the seven pockets. In this example, we’ll write a program to find the probability of landing in each pocket. We’ll drop the ball 1000 times and count how many times it lands in each pocket.
We’ll use a variable, named pos, to refer to the ball’s position as it rolls down. The ball starts in the middle with pos=4 (i.e., above pocket 4). In its way down, the ball will hit six levels of pins. At each level, the ball hits a pin and bounces left or right with equal probability. If the ball bounces to the right, its position will increase by 0.5, otherwise its position will decrease by 0.5. The complete program is shown in the Listing below.
1 ' PinBall.sb
2 ' Simulates a pinball machine
4 For N = 1 To 7 ' seven pockets
5 count[N]=0 ' zero balls in each pocket
8 For ball = 1 To 10000 ' Drops 10,000 balls. For each ball,
9 pos = 4 ' Starts in the middle
10 For level = 1 To 6 ' Drops six levels
11 If (Math.GetRandomNumber(2) = 1) Then
12 pos = pos - 0.5
14 pos = pos + 0.5
18 pos = Math.Floor(pos) ' Makes it an integer
19 count[pos] = count[pos] + 1 ' Adds ball to pocket
22 For N=1 To 7 ' Displays result
23 TextWindow.WriteLine("Pocket" + N + ": " + count[N])
As you can see most of the balls landed in pocket 3.
TRY IT OUT!
Modify the pin-ball simulation program to have 15 pockets and 20 levels. Run the simulation to see what you get!
Do you have any questions? Ask us! We're full of answers and other fine things!
Head to the Small Basic forum to get the most answers to your questions:
And go to http://blogs.msdn.com/SmallBasic to download Small Basic and learn all about it!
Small and Basically yours
- Ninja Ed & Majed Marji