Monday, March 14, 2011

Y10 Programming Lesson 5 - Polished coding

Cutting down the code from 240 lines to just 68!
Line 2 and 3 are still just:
Dim turn As String
Dim win As Boolean
Line 4 onwards is this code:
Sub butPressed(ByVal butnum As Integer)
        Me.Controls("Button" & butnum).Text = turn
        Me.Controls("Button" & butnum).Enabled = False
        If Button1.Text = turn And Button2.Text = turn And Button3.Text = turn Or _
             Button4.Text = turn And Button5.Text = turn And Button6.Text = turn Or _
             Button7.Text = turn And Button8.Text = turn And Button9.Text = turn Or _
             Button1.Text = turn And Button5.Text = turn And Button9.Text = turn Or _
             Button3.Text = turn And Button5.Text = turn And Button7.Text = turn Or _
             Button1.Text = turn And Button4.Text = turn And Button7.Text = turn Or _
             Button2.Text = turn And Button5.Text = turn And Button8.Text = turn Or _
             Button3.Text = turn And Button6.Text = turn And Button9.Text = turn Then
            win = True
        End If
        If win = True Then
            MsgBox(turn & " has won")
        End If
        If turn = "X" Then
            turn = "O"
        Else : turn = "X"
        End If
End Sub

Sub ResetGame()
        Dim buttonnumber As Integer
        For buttonnumber = 1 To 9
            Me.Controls("button" & buttonnumber).Text = ""
            Me.Controls("button" & buttonnumber).Enabled = True
        Next
        Button10.Text = "Reset"
        turn = "X"
        win = False
End Sub
FORM_LOAD and BUTTON10 now just have:
Call ResetGame()
Buttons 1 to 9 now just have (with the button number in brackets)
Call butPressed(1)

1 comment:

  1. “Knock, knock.”
    “Who’s there?”
    very long pause….
    “Java.”

    ReplyDelete