Finance

Charts

Statistics

Macros

Search

Controlling the Snake Game in Excel VBA

In the class module for Sheet1, you will find the procedure Worksheet_SelectionChange(). This procedure is responsible for handling user input during the game.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Address = "$M$2:$O$2" Then
        Starten
    ElseIf Target.Address = "$M$11:$O$11" Then
        MsgBox "The green snake must eat the red prey to earn points." & vbCrLf & _
               "After eating, the snake speeds up." & vbCrLf & _
               "You can steer the snake, but you cannot immediately reverse its direction." & vbCrLf & _
               "The game ends when the snake hits the wall.", , "Game Instructions"
    ElseIf Target.Address = "$N$4" Then
        If Richtung <> 2 Then Richtung = 0
    ElseIf Target.Address = "$O$5" Then
        If Richtung <> 3 Then Richtung = 1
    ElseIf Target.Address = "$N$6" Then
        If Richtung <> 0 Then Richtung = 2
    ElseIf Target.Address = "$M$5" Then
        If Richtung <> 1 Then Richtung = 3
    End If
    ' Reactivate center cell to ensure SelectionChange event fires next time
    Range("N5").Activate
End Sub

Explanation:

  • The Worksheet_SelectionChange() event is triggered whenever the user selects a new cell.
  • The selected cell or merged range is passed as the Target object. Its .Address property returns the address as a string.
  • If the START button cells (address $M$2:$O$2) are selected, the Starten procedure in Module1 is called to start the game.
  • If the INFO button cells (address $M$11:$O$11) are selected, a message box displays the game instructions.
  • The four cells N4, O5, N6, and M5 correspond to controls for changing the snake’s movement direction:
    • N4 sets direction up (0), unless the current direction is down (2), which would be an immediate reversal and is disallowed.
    • O5 sets direction right (1), unless the current direction is left (3).
    • N6 sets direction down (2), unless current direction is up (0).
    • M5 sets direction left (3), unless current direction is right (1).
  • The directions 0, 1, 2, 3 correspond to up, right, down, and left, respectively — arranged clockwise.
  • Finally, the cell N5 (center of the four direction controls) is reactivated. This is important because the SelectionChange event only fires when the active cell changes. Without this step, clicking the same directional cell repeatedly would not trigger the event.
0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx