Finance

Charts

Statistics

Macros

Search

Starting the Snake Game in Excel VBA

In Module1, you will find two module-wide variables and the procedure Start(). These are used to initialize the game and manage the game state.

Variables:

Public Direction As Integer 
Dim Started As Boolean

Explanation:

  • The variable Direction is declared with workbook-wide scope because it is accessed by multiple procedures across modules or multiple calls to the same procedure.
  • The Boolean variable Started is scoped to this module and prevents the game from being started more than once if it is already running.
  • Direction holds the snake’s current movement direction as an integer value.

Procedure Start():

Sub Start()
    Dim StartTime As Single
    Dim WaitTime As Single
    Dim RowSnake As Integer, ColSnake As Integer  ' Snake position (row, column)
    Dim RowPrey As Integer, ColPrey As Integer    ' Prey position (row, column)
    Dim GameOver As Boolean
    ' Prevent multiple starts
    If Started Then Exit Sub
    Started = True
    ' Clear game board colors
    Range("B2:K11").Interior.Color = xlNone
    ' Reset score counter
    Range("N8").Value = 0
    ' Initial wait time between moves (in seconds)
    WaitTime = 0.5
    ' Game not over yet
    GameOver = False
    ' Set snake start position and color
    RowSnake = 10
    ColSnake = 6
    Cells(RowSnake, ColSnake).Interior.Color = vbGreen
    ' Initial movement direction: up (0)
    Direction = 0
    ' Set prey start position and color
    RowPrey = 3
    ColPrey = 9
    Cells(RowPrey, ColPrey).Interior.Color = vbRed
    ' Initialize random number generator
    Randomize
    ' Main game loop runs until collision ends the game
    Do While Not GameOver
        ' Start timer for delay
        StartTime = Timer
        ' Wait for the duration of WaitTime
        Do While Timer < StartTime + WaitTime
            DoEvents ' Allow user interaction during wait
        Loop
        ' Clear old snake cell color
        Cells(RowSnake, ColSnake).Interior.Color = xlNone
        ' Move snake according to direction
        If Direction = 0 Then ' Up
            If RowSnake >= 3 Then
                RowSnake = RowSnake - 1
            Else
                GameOver = True
            End If
        ElseIf Direction = 1 Then ' Right
            If ColSnake <= 10 Then
                ColSnake = ColSnake + 1
            Else
                GameOver = True
            End If
        ElseIf Direction = 2 Then ' Down
            If RowSnake <= 10 Then
                RowSnake = RowSnake + 1
            Else
                GameOver = True
            End If
        Else ' Left (3)
            If ColSnake >= 3 Then
                ColSnake = ColSnake - 1
            Else
                GameOver = True
            End If
        End If
        ' Color new snake cell
        Cells(RowSnake, ColSnake).Interior.Color = vbGreen
        ' Check if snake "eats" the prey
        If RowSnake = RowPrey And ColSnake = ColPrey Then
            ' Increase score by 1
            Range("N8").Value = Range("N8").Value + 1
            ' Set prey to new random position
            RowPrey = Int(Rnd * 10 + 2)
            ColPrey = Int(Rnd * 10 + 2)
            Cells(RowPrey, ColPrey).Interior.Color = vbRed
            ' Decrease wait time by 10% to speed up snake
            WaitTime = WaitTime * 0.9
        End If
    Loop
    ' Game over message
    MsgBox "End of the game", , "Game Over"
    ' Reset started flag for next game
    Started = False
End Sub

Detailed Explanation:

  • StartTime and WaitTime control a timing loop to manage the delay between snake movements. StartTime records the current time when the loop starts, and WaitTime determines how long to wait before the snake moves again. This wait time decreases after each prey eaten, making the snake move faster.
  • RowSnake and ColSnake represent the current row and column of the snake on the board. RowPrey and ColPrey represent the row and column of the prey.
  • The Boolean GameOver flags the end of the game when set to True, such as when the snake collides with the board boundary.
  • The Boolean Started prevents multiple game starts.
  • Upon the first start, the game board’s interior cells are cleared of any color, the counter reset to 0, and the snake and prey placed at initial “safe” positions (snake colored green, prey colored red).
  • The snake initially moves upward (Direction = 0).
  • The Randomize statement prepares the random number generator to position the prey randomly.
  • The main game loop runs until GameOver becomes True. Inside this loop, a timer-based delay lets the user interact, changing the snake’s direction if desired.
  • After waiting, the snake’s old cell is cleared, and a new position is calculated based on the current direction.
  • If the snake reaches the prey’s position, the counter increments, the prey moves randomly, and the snake’s speed increases.
  • When the snake hits the boundary, the game ends with a message box.
  • Finally, the Started flag resets to allow restarting.
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