Cat On A Spreadsheet

Building an RPG in Excel, Part 5: Giving Our World a Sense of Time

In the previous instalment of our Excel RPG series, we finally introduced some company for our adventurer. Old Fort Approach became home to two goblins and a wolf, each represented by an independent character object with its own position, health and damage statistics - and this was an important development. Rather than treating creatures as symbols painted onto worksheet cells, we established a character system that distinguishes between reusable definitions and individual instances. Our monsters now exist independently of the terrain beneath them, and the player can no longer casually walk through their occupied tiles.

 

Unfortunately, the inhabitants of our little world have been remarkably unambitious. They don't move, attack, explore or otherwise interfere with our adventurer's activities. The goblins appear perfectly content to stand in the same places indefinitely, and our wolf seems to have developed an extraordinary talent for remaining motionless.

 

Before we can introduce meaningful combat or monster behaviour, we need to give our game something it doesn't yet possess: time. Today, we're going to implement a central game clock and a scheduling system that determines when individual creatures can act. Faster creatures will perform actions more frequently than slower ones, and our monsters will begin wandering around the map independently of the player. We'll also improve our message system so that multiple events occurring between player decisions are reported together, rather than each new message replacing the previous one. And finally, we'll introduce a small in-game Options menu, allowing the player to return to the main menu without reopening the workbook or entering the VBA editor. These changes will transform our prototype from a static map containing movable symbols into the beginning of a genuinely turn-based game world.

 

What does a turn actually mean?

 

Many simple turn-based games are organised around a straightforward rule: the player performs one action, then every monster performs one action. This approach is easy to understand and implement, but it becomes increasingly restrictive when we want characters with different speeds. Should a wolf be able to act twice as frequently as a goblin? What happens when the player becomes temporarily faster through magic? Could a particularly slow creature take one action for every three performed by the adventurer? We could introduce special rules for each situation, but that would quickly make our game logic complicated.

 

Instead, we're going to separate the concept of a player decision from the passage of game time. Our RPG will maintain a clock that begins at zero. Every action requires a certain amount of work, and each character's speed determines how long that work takes. To illustrate that, we will use 1,000 time units as the standard action cost and 100 as our reference speed. A character with speed 100 takes 1,000 time units to complete a standard action. A creature with speed 200 takes only 500. A slow creature with speed 50 would require 2,000.

 

We calculate the delay using:

 

Action delay = Action cost Ă— 100 Ă· Effective speed

 

The advantage is that we can support many different speeds without giving individual creatures special scheduling rules.

 

For our first implementation, the adventurer and goblins will have speed 100, while the wolf will have speed 200. This means the wolf can perform twice as many standard actions over the same amount of game time.

 

The clock is not connected to real-world seconds. A player might spend several minutes deciding where to move next, but no game time passes while they're thinking. This distinction is fundamental to our design.

 

Scheduling events instead of counting seconds

 

We could simulate time by repeatedly incrementing a counter from zero to one, then two, then three, checking at every increment whether something should happen. That would work, but it would be unnecessarily inefficient. Suppose the current game time is 1,000, and the next scheduled event occurs at 1,500. We already know nothing needs to happen during the intervening 499 units. Rather than process every intermediate value, we can advance directly to the next event.

 

This approach is called discrete-event scheduling. Every character will maintain a value named NextActionTime, identifying the earliest game time at which that character can act again. The scheduler finds whichever character is due to act first, advances the clock to that time, allows the character to act and calculates when it will next become eligible.

 

There is one important exception: the player. When the scheduler reaches the player's next action time, it stops. Excel waits for the player to click a movement or Wait button. After that action has been submitted, the scheduler processes any intervening monster events until the player becomes eligible again.

 

This is a particularly suitable approach for our Excel game because it doesn't require a continuously running loop, a Windows timer or Excel's Application.OnTime mechanism. The game advances through ordinary VBA procedure calls triggered by our existing interface.

 

Introducing character speed

 

Let's begin by updating our actor definitions. Open GameData and add a column named Speed to the existing tblActorTypes table. Our adventurer should have speed 100, both goblins inherit speed 100 from their shared GOBLIN definition, and the wolf should have speed 200. We're storing speed in the definition table because it's a characteristic shared by creatures of the same type. Individual instances will receive their initial speed from this definition, just as they receive their starting HP and damage.

 

We now need somewhere to store both speed and scheduling information. Open the clsActor class module and append these declarations:

' Natural speed inherited from the actor's definition.
Public BaseSpeed As Double

' Earliest game time when this individual may act again.
Public NextActionTime As Double

 

Notice that the two fields represent different kinds of information. BaseSpeed describes the creature's natural action speed. NextActionTime is part of its current gameplay state and changes whenever the creature acts.

 

We use Double because action delays won't always be whole numbers. For example, a character with speed 150 requires approximately 666.67 time units for a standard action. Retaining fractional values helps us avoid gradually distorting the relative action frequencies of different creatures.

 

Next, open modActors and locate LoadActorDefinitions. Declare an additional column index:

Dim speedCol As Long

 

After retrieving the existing field positions, add:

' Locate the new base-speed field.
speedCol = tbl.ListColumns("Speed").Index

 

Then replace the existing statement that adds each definition to mActorDefinitions:

' Store the reusable character properties, including base speed.
mActorDefinitions.Add typeID, Array( _
     CStr(data(r, nameCol)), _
     CStr(data(r, glyphCol)), _
     CLng(data(r, hpCol)), _
     CLng(data(r, damageCol)), _
     ColorFromHex(CStr(data(r, colorCol))), _
     CDbl(data(r, speedCol)))

 

Our definition array now contains six values, with base speed at index 5.

 

Finally, locate the CreateActor function and add the following instructions inside its existing With actor block, after the appearance and other statistics have been assigned:

' Initialise the actor's natural speed from its definition.
.BaseSpeed = CDbl(definition(5))

' Speed must always be positive for scheduling calculations.
If .BaseSpeed <= 0 Then
     Err.Raise vbObjectError + 205, , _
          "Actor speed must be greater than zero: " & typeID
End If

' The turn engine will establish the starting schedule.
.NextActionTime = 0

 

Every actor now has the information required by our future turn scheduler. We haven't added haste or slowing effects yet. However, we'll make an important architectural decision when implementing the engine: scheduling calculations will use a dedicated EffectiveSpeed function rather than accessing BaseSpeed directly. Initially, those values will be identical but eventually the function will incorporate temporary speed modifiers. This allows us to introduce effects without rewriting the basic timing formula throughout the application.

 

A proper message log for a world where many things happen

 

Before writing the scheduler, we need to address another limitation of our current interface. Until now, we have displayed messages by placing text directly into a particular worksheet cell and that worked when the only character capable of acting was the player. A movement command generated one message, and the next movement command replaced it. However, once monsters begin performing independent actions, this behaviour is no longer adequate.

 

Imagine that our adventurer attacks a wolf. The wolf is twice as fast, so it might attack twice before the player has another opportunity to respond. If every event simply overwrites the message cell, the player will only see the second attack. The first attack—and possibly an important amount of lost health—would disappear from the interface before the player could read it.

 

Instead, we'll introduce a message batch associated with each successful player action. When the player performs an action, a new batch begins. The player's own action can generate a message, and every relevant monster event occurring before the next player decision can append another. When the player becomes ready again, the entire sequence remains visible.

 

For example, once combat is implemented, the panel might show: "You attack the wolf for 4 damage.The wolf attacks you for 3 damage.The wolf attacks you for 2 damage."

 

We'll implement this through a new standard module named modMessages.

 

Preparing the message area

 

Our message currently begins at K23, but we need more space for multiple lines so we'll reserve K23:X26 as one multi-line display panel. Add the following constant to modGlobals:

' Complete worksheet region reserved for game messages.
Public Const MESSAGE_PANEL_ADDRESS As String = "K23:X26"

 

We'll retain MESSAGE_CELL_ADDRESS = "K23" because that is where Excel stores the content of the merged range. The important difference is that the entire area will now be merged and formatted to display wrapped text.

 

Creating modMessages

 

Insert a new standard module and name it modMessages. Enter the following complete code:

Option Explicit

' Messages generated during the current player-action cycle.
Private mTurnMessages As Collection

Public Sub PrepareMessagePanel()

     Dim panel As Range

     ' Retrieve the full message display region.
     Set panel = GameScreen().Range(MESSAGE_PANEL_ADDRESS)

     ' Prepare a single multi-line message area.
     With panel

          If Not .MergeCells Then .Merge

          .WrapText = True
          .VerticalAlignment = xlVAlignTop
          .Font.Size = 10

     End With

End Sub

Public Sub StartMessageBatch()

     ' Create an empty collection for the new player-action cycle.
     Set mTurnMessages = New Collection

     ' Clear the complete merged message panel.
     GameScreen().Range(MESSAGE_PANEL_ADDRESS).ClearContents

End Sub

Public Sub LogGameMessage(ByVal message As String)

     ' Empty messages are not recorded.
     If Len(Trim$(message)) = 0 Then Exit Sub

     ' Initialise the collection if necessary.
     If mTurnMessages Is Nothing Then
          Set mTurnMessages = New Collection
     End If

     ' Preserve the event in the current message batch.
     mTurnMessages.Add message

     ' Refresh the worksheet display.
     RefreshMessagePanel

End Sub

Private Sub RefreshMessagePanel()

     Dim i As Long
     Dim messageText As String

     If mTurnMessages Is Nothing Then Exit Sub

     ' Combine messages in the order they were generated.
     For i = 1 To mTurnMessages.Count

          If i > 1 Then
               messageText = messageText & vbLf
          End If

          messageText = messageText & CStr(mTurnMessages(i))

     Next i

     ' Display the batch in the top-left cell of the merged panel.
     GameScreen().Range(MESSAGE_CELL_ADDRESS).Value2 = messageText

End Sub

Public Sub ClearGameMessages()

     ' Discard messages from the previous game session.
     Set mTurnMessages = Nothing

     ' Clear the complete merged message area.
     GameScreen().Range(MESSAGE_PANEL_ADDRESS).ClearContents

End Sub

 

The module uses a Collection to preserve messages in the order they occur. Every call to LogGameMessage adds a new entry. The private RefreshMessagePanel procedure combines those entries into a single string, placing a line feed between messages, and the result is displayed in the worksheet's merged message area. Because messages are retained in a collection rather than being immediately overwritten, several monsters can report their actions during the same player-action cycle. The next successful player action calls StartMessageBatch, which clears the collection and starts again.

 

This message system will eventually serve combat, traps, inventory operations, environmental events and anything else that needs to communicate with the player. For now, it also gives our wandering monsters a way to report nearby activity.

 

Teaching monsters to move

 

Our monsters already have positions and occupy map tiles independently of the terrain, so the next step is to let them change those positions - although we won't introduce complex AI immediately. At this stage, monsters don't have line of sight, awareness, hostility rules or pathfinding. Making them deliberately pursue the player would require us to answer questions about how they detect and remember targets. Instead, we'll start with simple wandering behaviour.

 

However, there's an important distinction between random behaviour and randomly attempting invalid actions. We don't want a monster repeatedly choosing directions that lead into walls, trees or occupied tiles, thereby wasting its turns on impossible movement. Instead, each monster will examine its eight neighbouring tiles and identify which destinations are actually legal. It will then choose randomly from the valid destinations. If no legal movement exists, it will wait. This gives us sensible basic movement while keeping decision-making separate from the scheduler.

 

Preparing modActors for scheduling

 

First, add two functions to modActors that will allow our turn engine to initialise character readiness and identify the next monster due to act.

Public Sub SetActorReadiness(ByVal readyTime As Double)

     Dim actor As clsActor

     ' Initialise the player's scheduled action time.
     If Not mPlayer Is Nothing Then
          mPlayer.NextActionTime = readyTime
     End If

     If mMonsters Is Nothing Then Exit Sub

     ' Give every monster its initial scheduled time.
     For Each actor In mMonsters
          actor.NextActionTime = readyTime
     Next actor

End Sub

Public Function NextScheduledMonster() As clsActor

     Dim actor As clsActor
     Dim candidate As clsActor

     If mMonsters Is Nothing Then Exit Function

     ' Search for the living monster due to act earliest.
     For Each actor In mMonsters

          If actor.HP > 0 Then

               If candidate Is Nothing Then

                    Set candidate = actor

               ElseIf actor.NextActionTime < candidate.NextActionTime Then

                    Set candidate = actor

               End If

          End If

     Next actor

     Set NextScheduledMonster = candidate

End Function

 

SetActorReadiness establishes the initial scheduled time for every actor. We'll use it to make all creatures ready at time zero when a new game begins. NextScheduledMonster searches the collection for the living monster with the smallest NextActionTime. This is a straightforward linear search. Given the small number of monsters in our current test map, it's entirely sufficient. Later, if the game regularly contains hundreds of active creatures and timed effects, we may want a more efficient scheduling structure. For now, a simple search keeps the implementation easy to understand and debug.

 

Implementing valid monster movement

 

Next, add the following complete procedure to modActors:

Public Sub PerformMonsterAction(ByVal actor As clsActor)

     Dim player As clsActor
     Dim otherMonster As clsActor

     Dim validMoves As Collection
     Dim chosenMove As Variant

     Dim direction As Long
     Dim deltaX As Long
     Dim deltaY As Long

     Dim testX As Long
     Dim testY As Long
     Dim oldX As Long
     Dim oldY As Long

     Dim canMove As Boolean

     ' Only living actors can perform actions.
     If actor Is Nothing Then Exit Sub
     If actor.HP <= 0 Then Exit Sub

     Set player = PlayerActor()
     If player Is Nothing Then Exit Sub

     ' Prepare a list containing only legal movement choices.
     Set validMoves = New Collection

     ' Examine all positions in the surrounding 3 x 3 grid.
     For direction = 0 To 8

          deltaX = (direction Mod 3) - 1
          deltaY = (direction \ 3) - 1

          ' Exclude the centre, which represents the current tile.
          If deltaX <> 0 Or deltaY <> 0 Then

               testX = actor.X + deltaX
               testY = actor.Y + deltaY

               ' Check the destination terrain.
               canMove = IsTileWalkable(testX, testY)

               ' Apply the existing diagonal corner-blocking rule.
               If canMove And deltaX <> 0 And deltaY <> 0 Then

                    If Not IsTileWalkable(actor.X + deltaX, actor.Y) _
                           And Not IsTileWalkable(actor.X, actor.Y + deltaY) Then

                       canMove = False

                    End If

               End If

               ' The player and monsters cannot share a tile.
               If canMove Then
                    If testX = player.X And testY = player.Y Then
                          canMove = False
                    End If
               End If

               ' Reject tiles occupied by another living monster.
               If canMove Then

                    Set otherMonster = MonsterAt(testX, testY)

                    If Not otherMonster Is Nothing Then
                         canMove = False
                    End If

               End If

               ' Remember only valid destinations.
               If canMove Then
                    validMoves.Add Array(deltaX, deltaY)
               End If

          End If

     Next direction

     ' Waiting is the fallback when no legal movement exists.
     If validMoves.Count = 0 Then Exit Sub

     ' Select randomly from the valid movement choices.
     chosenMove = validMoves( _
          Int(Rnd() * validMoves.Count) + 1)

     deltaX = CLng(chosenMove(0))
     deltaY = CLng(chosenMove(1))

     ' Preserve the old coordinates for redrawing.
     oldX = actor.X
     oldY = actor.Y

     ' Move the actor to the chosen destination.
     actor.X = oldX + deltaX
     actor.Y = oldY + deltaY

     ' Restore the old tile and redraw the new one.
     RedrawWorldTile oldX, oldY
     RedrawWorldTile actor.X, actor.Y

     ' Report movement occurring near the player.
     If Abs(actor.X - player.X) <= 4 _
          And Abs(actor.Y - player.Y) <= 4 Then

          LogGameMessage "The " & LCase$(actor.ActorName) & _
               " moves nearby."

     End If

End Sub

 

The first part of this procedure examines the eight neighbouring positions. For each one, we check the terrain, apply the diagonal corner rule and verify that neither the player nor another monster occupies the destination. Only legal movements are added to validMoves. After examining every possibility, we choose one of those valid movements at random. Every valid direction has an equal chance of being selected. If no legal destination exists, the monster waits.

 

This is deliberately different from choosing one of eight directions at random and then discovering that the destination is blocked. Our monsters shouldn't waste scheduled actions repeatedly attempting to enter impassable terrain when they have perfectly reasonable alternative routes available.

 

We still permit waiting when a monster genuinely has nowhere legal to go. Later, more sophisticated AI may also choose waiting deliberately, perhaps while guarding a position or preparing an attack.

 

Once the movement is selected, we update the actor's coordinates and call RedrawWorldTile for both the old and new locations. This uses the layered renderer introduced in Part 4. Terrain remains independent of the creatures standing above it, and moving a monster doesn't permanently overwrite its previous tile.

 

At the end, we report movement occurring within a four-tile neighbourhood of the player. We're using a simple proximity test for now because our field-of-vision system hasn't been implemented. Eventually, we'll replace it with a proper visibility check so that messages reflect what the player can reasonably perceive.

 

The important point is that monster decision-making doesn't manage the game clock. It simply selects and performs a legal action when requested by the scheduler - and now we're ready to build that scheduler.

 

Introducing modTurnEngine

 

Create a new standard VBA module named modTurnEngine. This module will maintain the current game time, calculate action delays and coordinate scheduled actor actions. It will also distinguish between the player being ready to act and the scheduler processing monster events.

 

The turn engine mustn't become responsible for deciding how goblins move or what happens during combat. Those responsibilities belong to other systems. Its job is to determine when actions take place.

 

Enter the following complete code:

Option Explicit

' A standard action requires 1,000 units of work.
Public Const STANDARD_ACTION_COST As Double = 1000

' Speed 100 represents normal action speed.
Public Const BASELINE_SPEED As Double = 100

' Current simulated game time.
Private mGameTime As Double

' Indicates whether the scheduler is waiting for player input.
Private mWaitingForPlayer As Boolean

Public Function CurrentGameTime() As Double

     ' Expose the current game clock without allowing direct modification.
     CurrentGameTime = mGameTime

End Function

Public Function EffectiveSpeed(ByVal actor As clsActor) As Double

     ' Future haste and slowing modifiers will be applied here.
     EffectiveSpeed = actor.BaseSpeed

     ' A zero or negative speed cannot be scheduled.
     If EffectiveSpeed <= 0 Then

          Err.Raise vbObjectError + 301, , _
               "Actor speed must be greater than zero."

     End If

End Function

Private Function ActionDelay( _
     ByVal actor As clsActor, _
     ByVal actionCost As Double) As Double

     ' Convert action work and effective speed into elapsed time.
     ActionDelay = actionCost * BASELINE_SPEED / _
          EffectiveSpeed(actor)

     ' Prevent extremely fast actors from receiving zero delay.
     If ActionDelay < 1 Then ActionDelay = 1

End Function

Public Sub ResetTurnSession()

     ' Clear the game clock and player-readiness state.
     mGameTime = 0
     mWaitingForPlayer = False

End Sub

Public Sub StartTurnSession()

     Dim player As clsActor

     Set player = PlayerActor()

     ' A turn session requires an initialised player.
     If player Is Nothing Then
          Err.Raise vbObjectError + 302, , _
               "Cannot start the turn engine without a player."
     End If

     ' Begin a new game at time zero.
     ResetTurnSession
     SetActorReadiness 0

     ' Initialise randomness for wandering monsters.
     Randomize

     ' The player acts first when everyone starts at time zero.
     mWaitingForPlayer = True

     ' Prepare the first message batch and status display.
     StartMessageBatch
     LogGameMessage "The adventure begins."

     UpdatePlayerStatus

End Sub

Public Function CanPlayerAct() As Boolean

     Dim player As clsActor

     Set player = PlayerActor()

     If player Is Nothing Then Exit Function

     ' The player may act only when the scheduler is waiting.
     If Not mWaitingForPlayer Then Exit Function

     ' Opening Options temporarily disables gameplay input.
     If IsOptionsOpen() Then Exit Function

     ' Dead characters cannot submit ordinary actions.
     If player.HP <= 0 Then Exit Function

     CanPlayerAct = True

End Function

Public Function BeginPlayerAction() As Boolean

     ' Reject input outside the player's scheduled action.
     If Not CanPlayerAct() Then Exit Function

     ' Begin processing the accepted action.
     mWaitingForPlayer = False

     ' Every accepted action begins a new message batch.
     StartMessageBatch

     BeginPlayerAction = True

End Function

Public Sub CompletePlayerAction(ByVal actionCost As Double)

     Dim player As clsActor

     Set player = PlayerActor()

     If player Is Nothing Then Exit Sub

     ' Schedule the player's next available action.
     player.NextActionTime = mGameTime + _
          ActionDelay(player, actionCost)

     ' Process intervening events until the player is ready.
     AdvanceToPlayerTurn

End Sub

Private Sub AdvanceToPlayerTurn()

     Dim player As clsActor
     Dim monster As clsActor

     Set player = PlayerActor()
     If player Is Nothing Then Exit Sub

     Do

          ' Find the monster with the earliest scheduled action.
          Set monster = NextScheduledMonster()

          ' If no monsters remain, advance to the player's turn.
          If monster Is Nothing Then

               mGameTime = player.NextActionTime
               Exit Do

          End If

          ' The player wins ties with monsters.
          If player.NextActionTime <= monster.NextActionTime Then

               mGameTime = player.NextActionTime
               Exit Do

          End If

          ' Jump directly to the monster's next event.
          mGameTime = monster.NextActionTime

          ' Allow the monster to choose and perform an action.
          PerformMonsterAction monster

          ' Print a diagnostic event trace for testing.
          Debug.Print "Time " & Format$(mGameTime, "0.##"), _
               monster.InstanceID & " acts"

          ' Schedule the monster's next standard action.
          monster.NextActionTime = mGameTime + _
               ActionDelay(monster, STANDARD_ACTION_COST)

     Loop

     ' The scheduler now waits for another player decision.
     mWaitingForPlayer = True

     ' Display the updated status after all intervening events.
     UpdatePlayerStatus

End Sub

 

This is the central component of the milestone. Let's examine how it behaves.

 

When a new game begins, StartTurnSession resets the clock to zero and assigns the same initial readiness time to the player and all monsters, and then the player is allowed to act first. Once the player submits a valid action, CompletePlayerAction calculates when the player can next act. For our speed-100 adventurer performing a standard action, that will normally be 1,000 time units later. The scheduler then looks for the next monster event.

 

At the start of the game, all three monsters are scheduled at time zero. They therefore act immediately after the player's first action. Once the goblins have acted, their next action times become 1,000; the wolf, with speed 200, becomes ready again at time 500. The scheduler advances directly to time 500 and allows the wolf to act again. It then finds that the player's next action time is 1,000, equal to the next monster event. Because we've decided that the player takes priority when scheduled times are equal, processing stops and control returns to the player.

 

The result is exactly the relationship we wanted: over equal amounts of game time, a speed-200 wolf gets twice as many standard actions as a speed-100 adventurer.

 

An important detail is that this doesn't depend on the player physically clicking buttons at any particular rate. The clock advances only when a valid timed action is submitted. The mWaitingForPlayer flag helps enforce this. While the scheduler is processing monsters, the player is not eligible to submit another action. Once processing reaches the next player turn, the flag becomes True again.

 

We also use CanPlayerAct to check whether the game is currently displaying its Options menu. That prevents movement or waiting while the player is interacting with the menu.

 

Finally, notice that ActionDelay uses EffectiveSpeed, not BaseSpeed directly. When we implement haste and slowing, this will become an important extension point.

 

There is one future detail we'll need to handle carefully: a speed change that occurs while a character is already waiting for its next action. We want to preserve the progress already made rather than restart the action from the beginning.

 

The present scheduler establishes the required timing model. We'll implement rescheduling for changing speed modifiers when those effects become part of gameplay.

 

Connecting player actions to the scheduler

 

We now need to modify modPlayer. Until this milestone, movement directly updated the player's coordinates and wrote the resulting message to the worksheet. There was no game clock involved. Now a successful movement must trigger several operations: it must confirm that the player is eligible to act, validate the destination, begin a new message batch, update the player position, record any resulting messages and notify the scheduler that the action is complete. The scheduler can then process monster events and return control when the player becomes ready again.

 

Invalid movement remains different. Attempting to walk into a wall or another impassable object will display an appropriate message, but it won't advance game time.

 

Updating the player's status

 

First, replace the existing UpdatePlayerStatus procedure in modPlayer with this version:

Public Sub UpdatePlayerStatus()

     Dim player As clsActor
     Dim ws As Worksheet

     ' Retrieve the current player object.
     Set player = PlayerActor()

     If player Is Nothing Then Exit Sub

     Set ws = GameScreen()

     ' Display statistics, coordinates and simulated game time.
     ' Game messages are maintained separately by modMessages.
     ws.Range(STATUS_CELL_ADDRESS).Value2 = _
          "HP " & player.HP & "/" & player.MaxHP & _
          " D" & player.Damage & _
          " (" & player.X & "," & player.Y & ")" & _
          " T" & Format$(CurrentGameTime(), "0.##")

End Sub

 

The status and message systems are now independent. UpdatePlayerStatus only displays character information and game time, while LogGameMessage is responsible for reporting events. We've also made UpdatePlayerStatus public because the turn engine needs to refresh the display after processing all intervening actions.

 

Next, replace InitialisePlayer with:

Public Sub InitialisePlayer( _
     ByVal startX As Long, _
     ByVal startY As Long)

     ' Create the active character instances.
     InitialiseActorSession START_MAP_ID, startX, startY

     ' Display the new player's initial statistics.
     UpdatePlayerStatus

End Sub

 

The initial adventure message will now come from StartTurnSession, which is called after the character session has been created.

 

Updating movement

 

Replace the existing private MovePlayer procedure with the following:

Private Sub MovePlayer( _
     ByVal deltaX As Long, _
     ByVal deltaY As Long)

     Dim player As clsActor
     Dim monster As clsActor

     Dim oldX As Long
     Dim oldY As Long
     Dim newX As Long
     Dim newY As Long

     ' Movement is allowed only during the player's scheduled action.
     If Not CanPlayerAct() Then Exit Sub

     Set player = PlayerActor()

     ' Calculate the requested destination.
     newX = player.X + deltaX
     newY = player.Y + deltaY

     ' Invalid terrain movement does not consume time.
     If Not IsTileWalkable(newX, newY) Then

          LogGameMessage GetTerrainMessage(newX, newY, True)
          Exit Sub

     End If

     ' Prevent diagonal squeezing between two blocked neighbours.
     If deltaX <> 0 And deltaY <> 0 Then

          If Not IsTileWalkable(player.X + deltaX, player.Y) _
               And Not IsTileWalkable(player.X, player.Y + deltaY) Then

               LogGameMessage "You cannot squeeze through that gap."
               Exit Sub

          End If

     End If

     ' Monster-occupied tiles remain blocked until combat is added.
     Set monster = MonsterAt(newX, newY)

     If Not monster Is Nothing Then

          LogGameMessage "A " & LCase$(monster.ActorName) & _
               " blocks your way."
          Exit Sub

     End If

     ' A legal movement begins a new timed player action.
     If Not BeginPlayerAction() Then Exit Sub

     ' Remember the old position before moving.
     oldX = player.X
     oldY = player.Y

     ' Update the actor's actual coordinates.
     player.X = newX
     player.Y = newY

     ' Refresh both affected map cells.
     RedrawWorldTile oldX, oldY
     RedrawWorldTile newX, newY

     ' Record any message associated with entering the tile.
     LogGameMessage GetTerrainMessage(newX, newY, False)

     ' Advance the scheduler through all intervening monster events.
     CompletePlayerAction STANDARD_ACTION_COST

End Sub

 

The movement rules themselves haven't changed substantially. We still use the terrain engine to decide whether a tile can be entered, preserve our existing diagonal collision rules and prevent the player from entering a monster's occupied position. The major difference is how accepted movement interacts with the turn engine.

 

Notice that we call BeginPlayerAction only after determining that the movement is valid. This means invalid movement doesn't accidentally consume time or discard the existing message batch. Once the action has begun, we move the player and report any message associated with the destination. Then CompletePlayerAction schedules the player's next eligible action and processes all intervening monster events. By the time the procedure returns, those monsters have moved or waited, the game clock has advanced, and the player can make another decision.

 

The existing eight public movement procedures—MoveNorth, MoveSW and the others—can remain exactly as they were, and their button assignments also remain unchanged.

 

Updating Wait

 

The Wait action now has an important role because it allows us to advance game time without moving the player. Replace WaitTurn with:

Public Sub WaitTurn()

     ' Waiting is a valid action that consumes normal game time.
     If Not BeginPlayerAction() Then Exit Sub

     LogGameMessage "You wait."

     ' Let scheduled monster events occur before the next player turn.
     CompletePlayerAction STANDARD_ACTION_COST

End Sub

 

Waiting consumes the same 1,000-unit action cost as ordinary movement. During that time, monsters continue acting according to their own schedules. This makes Wait especially useful for testing our engine as we can remain in one place while observing how the surrounding creatures behave.

 

Adding a small in-game Options menu

 

So far, the easiest way to return to our main menu has been to run ShowMainMenu manually or reopen the workbook. That's acceptable during early development, but now that we're beginning to build an actual gameplay loop, the player needs an in-game way to leave the current session. We'll add a small Options button in the upper-right corner of the Screen worksheet. Clicking it will reveal a simple menu containing Main Menu. Eventually, this panel may contain settings, help, saving and other options, but we don't need to design those systems yet.

 

We'll reuse the shape-management functions created in Part 3, so there's no need for a separate worksheet or UserForm.

 

Defining the menu locations

 

Add two new constants to modGlobals:

' Small gameplay Options button in the upper-right corner.
Public Const OPTIONS_BUTTON_ADDRESS As String = "AC2:AG3"

' Expandable Options entry, positioned over the top of the map.
Public Const OPTIONS_DROPDOWN_ADDRESS As String = "AB4:AG5"

 

These areas are deliberately small. The Options button sits above the map, while its expandable entry temporarily overlays a small portion of the game world. As with our other interface components, keeping the ranges in modGlobals means we can reposition them without searching through the interface procedures.

 

Adding menu state to modInterface

 

Open modInterface and add the following declaration immediately beneath Option Explicit:

' True while the expandable Options menu is displayed.
Private mOptionsOpen As Boolean

 

This flag belongs to the interface because it describes the state of a user-interface component. The turn engine doesn't need to know how the menu is drawn. It only needs to ask whether the menu is currently open before accepting gameplay actions.

 

Creating the Options controls

 

Inside BuildGameInterface, add these declarations alongside the existing local variables:

Dim optionsArea As Range
Dim dropdownArea As Range

 

Then, after the existing New Game button has been created and assigned its StartNewGame macro, add the following code:

' Create the small Options button at the top-right of the screen.
Set optionsArea = ws.Range(OPTIONS_BUTTON_ADDRESS)

Set btn = GetOrCreateButton(ws, "btnOptions")

With btn
     .Left = optionsArea.Left
     .Top = optionsArea.Top
     .Width = optionsArea.Width
     .Height = optionsArea.Height
End With

FormatButton btn, "OPTIONS", RGB(39, 70, 84)
btn.OnAction = MacroReference("ToggleOptionsMenu")

' Create the expandable Main Menu entry.
Set dropdownArea = ws.Range(OPTIONS_DROPDOWN_ADDRESS)

Set btn = GetOrCreateButton(ws, "btnOptionsMainMenu")

With btn
     .Left = dropdownArea.Left
     .Top = dropdownArea.Top
     .Width = dropdownArea.Width
     .Height = dropdownArea.Height
End With

FormatButton btn, "MAIN MENU", RGB(48, 76, 91)
btn.OnAction = MacroReference("ReturnToMainMenu")

 

These shapes use the same reusable helpers as the navigation controls. GetOrCreateButton prevents duplicate shapes from appearing during repeated initialisation. FormatButton gives the controls a consistent appearance, and MacroReference assigns the appropriate procedures within our workbook.

 

Now locate SetGameplayControlsVisible. Keep its existing logic for New Game and the nine navigation controls, but add this section immediately before the procedure's final End Sub:

' Collapse Options whenever the main interface changes state.
mOptionsOpen = False

ws.Shapes("btnOptionsMainMenu").Visible = msoFalse

' The Options button is available only while playing.
If playing Then
     ws.Shapes("btnOptions").Visible = msoTrue
Else
     ws.Shapes("btnOptions").Visible = msoFalse
End If

 

This prevents the expanded menu from remaining on screen when the player returns to the main menu or starts another adventure.

 

Opening and closing Options

 

Add the following procedures to modInterface:

Public Function IsOptionsOpen() As Boolean

     ' Report the current Options panel state.
     IsOptionsOpen = mOptionsOpen

End Function

Public Sub ToggleOptionsMenu()

     Dim ws As Worksheet

     ' Opening Options requires an active player turn.
     ' Closing an already-open panel must always remain possible.
     If Not mOptionsOpen Then
          If Not CanPlayerAct() Then Exit Sub
     End If

     Set ws = GameScreen()

     ' Switch between expanded and collapsed menu states.
     mOptionsOpen = Not mOptionsOpen

     If mOptionsOpen Then

          ' Reveal the menu entry above the map and other shapes.
          ws.Shapes("btnOptionsMainMenu").Visible = msoTrue
          ws.Shapes("btnOptionsMainMenu").ZOrder msoBringToFront

     Else

          ' Return to the normal gameplay interface.
          ws.Shapes("btnOptionsMainMenu").Visible = msoFalse

     End If

End Sub

 

Notice that opening and closing the menu does not call BeginPlayerAction or CompletePlayerAction - it's not an in-world action and it therefore consumes no game time.

 

The CanPlayerAct function in our turn engine also checks IsOptionsOpen, so movement and waiting are disabled while the panel is expanded. This is different from pausing a continuously running timer. Our game clock doesn't advance on its own in the first place. Opening Options simply prevents gameplay commands from being accepted until the menu closes.

 

Returning to the main menu

 

In modGame, add the following procedure:

Public Sub ReturnToMainMenu()

     Dim answer As VbMsgBoxResult

     ' Confirm that the player intends to abandon the current run.
     answer = MsgBox( _
          "Return to the main menu?" & vbCrLf & _
          "Your current adventure will be lost.", _
          vbYesNo + vbQuestion, _
          "Excel RPG")

     If answer = vbYes Then
          ShowMainMenu
     End If

End Sub

 

Because we haven't introduced a save system, returning to the main menu discards the current adventure. We therefore display a confirmation before doing so. Choosing No leaves the current game intact, with the Options menu still open, and choosing Yes returns the player to the familiar New Game screen. Later, when we implement persistent saves, we can revisit this behaviour.

 

Updating the game startup sequence

 

Our final integration step is to update modGame. We need to prepare the message panel when the main menu appears, reset the turn engine when leaving gameplay and start the scheduler when New Game creates the actor session. The existing Auto_Open procedure can remain unchanged.

 

Replace ShowMainMenu with:

Public Sub ShowMainMenu()

     Dim ws As Worksheet

     Set ws = GameScreen()

     ' Stop game time and discard the active character session.
     ResetTurnSession
     ResetPlayer

     ' Create or update the complete interface.
     BuildGameInterface

     ' Prepare and clear the multi-line message panel.
     PrepareMessagePanel
     ClearGameMessages

     ' Clear the previous terrain display.
     With MapArea()
          .ClearContents
          .Interior.Color = RGB(23, 35, 43)
          .Font.Bold = False
     End With

     ' Display the main-menu title and instructions.
     ws.Range("B2").Value2 = "EXCEL RPG"
     ws.Range(STATUS_CELL_ADDRESS).Value2 = "MAIN MENU"
     ws.Range(MESSAGE_CELL_ADDRESS).Value2 = _
          "Click New Game to begin."

     ws.Range("Y23").ClearContents

     ' Reveal New Game and hide all gameplay controls.
     SetGameplayControlsVisible False

     ws.Activate

End Sub

 

Then replace StartNewGame with:

Public Sub StartNewGame()

     Dim player As clsActor

     ' Remove any previous session state.
     ResetTurnSession
     ResetPlayer

     ' Load the starting location and initialise all characters.
     ShowMap

     ' Only start scheduling once a player has been created.
     Set player = PlayerActor()
     If player Is Nothing Then Exit Sub

     ' Initialise the clock and the first message batch.
     StartTurnSession

     ' Display navigation and the new Options control.
     SetGameplayControlsVisible True

End Sub

 

The startup sequence now coordinates more systems than it did in Part 3, but its structure remains straightforward. Opening the workbook displays the main menu. Starting a new game loads terrain and actors, initialises the clock and reveals the gameplay controls. Returning to the main menu discards the current actor and timing state.

 

We haven't needed to rewrite the map engine or the automated navigation buttons. This is a useful demonstration of the benefits of modular design. As the game grows, the controller can coordinate new systems without becoming responsible for their internal implementation.

 

Testing the new game clock

 

With all the changes in place, compile the VBA project, save the workbook and reopen it. The main menu should appear automatically, just as it did in the previous milestone. Click New Game, and our adventurer, two goblins and wolf should appear on Old Fort Approach. The character status should now include a time value, initially T0. The message area should display the initial adventure message.

 

Now click Wait once. Because the player has speed 100 and waiting costs 1,000 time units, the clock should advance to T1000. During that interval, the goblins should each receive an action at time zero and the wolf should act at time zero and again at time 500. You should be able to see them changing position on the screen - although there is the possibility that the wolf might return to the same spot with the second action.

 

We can confirm the scheduler's behaviour by opening the VBA Immediate Window with Ctrl+G. The diagnostic messages generated by AdvanceToPlayerTurn should show events equivalent to:

Time 0       GOB01 acts
Time 0 GOB02 acts
Time 0 WOLF01 acts
Time 500 WOLF01 acts

 

The exact order of monsters sharing the same scheduled time follows their order in the collection. The important observation is that the wolf receives two scheduled actions while each goblin receives one.

 

Click Wait again. The player clock should advance to T2000. The goblins should act at time 1,000, while the wolf acts at times 1,000 and 1,500. This demonstrates that our scheduling system is using individual readiness times, rather than simply allowing every monster one action after each player command.

 

We should also test actual movement. The monsters should wander around the map, selecting only valid destinations. They shouldn't move through impassable terrain, squeeze diagonally through blocked corners or overlap with one another. If a monster has no legal adjacent destination, it will wait until its next scheduled opportunity. You can test this by amending the underlying map so that a goblin is surrounded by walls or water in the four cardinal directions and thus forced to wait.

 

Similarly, our player should continue obeying the collision rules introduced in Part 2, and attempts to enter an occupied monster tile should still be blocked. The clock should not advance when the player attempts an invalid movement.

 

Testing accumulated messages

 

Our new logging system deserves its own test because it will become central to combat. We don't yet have attacks or damage, but we can simulate the messages they will eventually generate.

 

During an active game, open the Immediate Window and run the following procedures in sequence. (You do that by inserting each line in the Immediate Window followed by hitting Enter)

StartMessageBatch
LogGameMessage "Test: The wolf attacks for 3 damage."
LogGameMessage "Test: The wolf attacks for 2 damage."

 

Both messages should remain visible together in the message panel, neither message should replace the other.

 

Now return to the game and click Wait. The test messages should disappear because the accepted Wait action begins a new message batch. The new batch should contain "You wait.", followed by any relevant monster movement messages generated before the next player decision. This demonstrates the behaviour we'll rely on during combat. If several monsters act before the player can respond, each relevant attack, damage result or other event can be recorded in sequence.

 

The message system also handles invalid player movement differently from successful actions. Attempting to walk into a wall produces a message, but doesn't begin a new batch or consume time.

 

For now, the visible message panel has a fixed size. We're retaining all generated messages in memory for the current action cycle, but unusually long batches may exceed the space available on the screen. When we introduce a more sophisticated interface, we may add a scrollable message history or a dedicated log viewer. That isn't necessary for our current three-monster test, and we'd rather keep the interface simple until gameplay demands more.

 

Testing Options and returning to the main menu

 

The final part of the milestone concerns the interface. During gameplay, the new Options button should appear in the upper-right corner - click it. The expandable Main Menu entry should appear, and the game clock should remain unchanged. While the Options panel is open, clicking the movement or Wait buttons should not advance gameplay. Click Options again - the panel should close and normal movement should resume.

 

Next, open Options and select Main Menu. The game should ask whether you want to abandon the current adventure. Choosing No should leave the game intact, while choosing Yes should return to the main menu, clear the active session and display New Game. Starting another game should reset the clock to zero and recreate the original monsters at their starting locations, without leaving behind duplicate character instances or interface controls.

 

Finally, save and reopen the workbook once more to confirm that automatic startup continues working correctly. Our implementation passed these checks, including the scheduler's action frequencies, valid monster movement, accumulated messages and interface transitions.

 

What this milestone changes about our game

 

It may not be immediately obvious how significant these additions are. On the surface, Old Fort Approach still looks much the same. The player can move around, three monsters occupy the map, and the interface consists mainly of worksheet cells and a few buttons, but the underlying game model has changed substantially. Until now, the world changed only when the player directly moved their character, but now we have an independent concept of game time.  Every active creature has its own scheduled action, and its speed determines how frequently it acts. The player is no longer the only character capable of changing the world, our monsters can wander while the player waits or moves. Their positions are updated independently, and the renderer reconstructs the affected tiles without altering the underlying terrain.

 

We've also established a foundation for more complex actions. Movement and waiting both have standard time costs, but the scheduler is designed to accept other costs. Later, attacking, drinking a potion, casting a spell or performing a special ability might consume different amounts of game time. Faster creatures will be able to perform those actions more frequently, without requiring separate rules for every possible speed.

 

The message system is also prepared for the consequences of multiple actors acting between player decisions. Rather than presenting only the latest event, it retains a chronological batch of relevant messages. This will become particularly important when several monsters can attack, status effects can apply damage, or the player performs an action that triggers several consequences.

 

There are also deliberate limitations. Our monsters still wander randomly rather than pursuing the player. They don't yet have perception, line of sight or sophisticated decision-making; they can't attack, and their HP and damage statistics remain unused during gameplay. We haven't implemented temporary speed modifiers, although the scheduler has an EffectiveSpeed function ready for their introduction. Nor do inactive maps advance in the background. The current scheduler processes only characters belonging to the active location, consistent with our decision that areas without the player should not continue simulating independently. These are not oversights. They're features we'll introduce when the necessary foundations are available.

 

Next: making encounters dangerous

 

Our adventurer can now encounter moving monsters, but those encounters remain rather peaceful. A goblin that approaches the player simply finds another legal destination. A wolf can act twice as frequently as the adventurer, but it has no ability to use that advantage aggressively. The next development milestone will change that - in Part 6, we'll introduce combat. We already have most of the essential ingredients: character HP, attack damage, individual actor instances, occupancy detection, a central scheduler and a message system capable of reporting multiple events during the same player-action cycle. The obvious next step is to make attacking an actual game action.

 

We'll need to determine what happens when the player attempts to move into a hostile creature, how monsters select targets, how damage is applied and what happens when a character reaches zero HP. We'll also need to handle the disappearance of dead monsters from the map and ensure that the time required for combat actions is consistent with our scheduler. For our speed-200 wolf, that means the relationship we've established today will finally have consequences. It may be able to attack twice between normal player actions, and both attacks will appear in the message log.

 

We'll keep the first combat implementation relatively simple, avoiding an elaborate system of armour, accuracy, critical hits and character attributes until the basic mechanics are working correctly. Our goal remains the same as it has been throughout this series: build a capable RPG through small, understandable, independently tested milestones. For now, though, our once-motionless goblins have begun exploring the fort, our wolf has discovered that it can move rather quickly, and our adventurer has gained the ability to wait while the world changes around them. Excel has become a little less like a spreadsheet and a little more like a living game world. Unfortunately for our adventurer, the next milestone is where that world begins to fight back.

 

This article is Part 5 of the Building an RPG in Excel series. The accompanying development workbook and VBA source modules found here allow readers to follow the implementation themselves. A complete, ready-to-play workbook containing the implementation of the code as described and contained in the source modules can also be downloaded here, but keep in mind it will require enabling macros before it will work.

27 November 2026

Full Service Consulting

Reporting

Automation

Cat On A Spreadsheet

Cat On A Spreadsheet