Functions and Procedures
I need to take my code for a shell game and divide it into functions and procedures. The program works as it should but I am having difficulty dividing the code up further. I also have a feeling that some of my procedures should be functions. Any help would be appreciated. Thanks.
Here is the code:
Public Class frmShellGame
Private Sub picShell_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles picShell1.Click, picShell2.Click, picShell3.Click
'Determine which shell contains the pearl
Dim shellWithPearl = randomizeNumber()
'Determine which shell was clicked by user
Dim picShellClicked As PictureBox = sender
Dim shellClicked As Integer = Val(picShellClicked.Tag)
'Sets a shell to be removed on guess
Dim junkShell = randomizeNumber()
Dim alternateChoice As Integer
'Ensures that junkShell is not shellWithPearl and is not alternateChoice
Call pickJunkShell(junkShell, shellWithPearl, shellClicked)
Call pickAlternateChoice(alternateChoice, junkShell, shellClicked)
'Removes junkShell
Call removeJunkShell(junkShell)
'Asks for confirmation and switches choice.
Dim confirmChoice As String
confirmChoice = InputBox("Do you want to keep your answer? (Yes/No)" & vbCrLf & "If not, then your guess will automatically switch to the other remaining shell.", "Confirm Guess")
If confirmChoice = "No" Then
shellClicked = alternateChoice
End If
'Shows Pearl
Call showPearl(shellWithPearl)
'Display message to player
If shellClicked = shellWithPearl Then
MsgBox("You won!")
Else
MsgBox("Sorry, you lose.")
End If
'Reset images
Me.picShell1.Visible = True
Me.picShell2.Visible = True
Me.picShell3.Visible = True
Me.picPearl1.Visible = False
Me.picPearl2.Visible = False
Me.picPearl3.Visible = False
End Sub
Function randomizeNumber() As Integer
Randomize()
Return Int(3 * Rnd()) + 1
End Function
Sub pickJunkShell(ByRef junkShell As Integer, ByRef shellWithPearl As Integer, ByRef shellClicked As Integer)
While (junkShell = shellWithPearl) Or (junkShell = shellClicked)
junkShell = randomizeNumber()
End While
End Sub
Sub pickAlternateChoice(ByRef alternateChoice As Integer, ByVal junkShell As Integer, ByVal shellClicked As Integer)
alternateChoice = 6 - junkShell - shellClicked
End Sub
Sub removeJunkShell(ByVal junkShell As Integer)
Select Case junkShell
Case 1
Me.picShell1.Visible = False
Case 2
Me.picShell2.Visible = False
Case 3
Me.picShell3.Visible = False
End Select
End Sub
Sub showPearl(ByVal shellWithPearl As Integer)
Select Case shellWithPearl
Case 1
Me.picPearl1.Visible = True
Case 2
Me.picPearl2.Visible = True
Case 3
Me.picPearl3.Visible = True
End Select
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit()
End Sub
End Class
|