Cat On A Spreadsheet

Building an RPG in Excel, Part 6: Combat, Damage and Death

Our Excel RPG has come a long way since we first drew a map onto a worksheet. We now have a structured world, a movable adventurer, independent monster objects and a game clock that determines when each creature can act. The inhabitants of Old Fort Approach have even started moving around on their own. Goblins wander through the ruins, and our wolf moves twice as quickly as a normal-speed adventurer. There is, however, one rather conspicuous limitation: none of these creatures can actually hurt anybody. A goblin can approach the player, but it cannot attack. Our adventurer has health and damage statistics, but those numbers don't affect the game. The wolf can act twice as frequently as the player, yet its speed offers little practical advantage beyond giving it more opportunities to wander around.

 

Today, we're going to change that. We'll introduce melee combat, allow creatures to inflict and receive damage, handle monster deaths and end the adventure when the player dies. We'll also expand our message system into a searchable, time-stamped event history, making it possible to follow what happened during a fight rather than seeing only the most recent attack. By the end of this instalment, our game will have its first complete combat loop. Monsters will be able to kill the player, the player will be able to kill monsters, and our turn scheduler will determine exactly when each attack takes place. We'll keep the actual combat calculations deliberately simple, as our focus is on establishing reliable relationships between character state, action scheduling, world rendering and the interface. More elaborate mechanics—armour, accuracy, critical hits, equipment and special abilities—can be introduced once that foundation is working.

 

The previous instalment also marked a change in how we're distributing the project. Alongside the instructional workbook and exported VBA modules, we are now providing a complete, playable macro-enabled version of the game at the end of each development milestone. Readers can therefore follow the implementation themselves or simply open the current build and see what we've created.

 

Combat is an action, not a separate game mode

 

One of the most useful decisions we made in Part 5 was separating action scheduling from the actions themselves. Our turn engine doesn't need to know how a goblin decides where to move - it only needs to determine when the goblin may act and when it becomes eligible again. We'll follow the same principle for combat.

 

An attack is another action performed by an actor. It has a cost, changes the state of the world and may generate messages. Once the action is complete, the same turn engine calculates when the attacker may act again. This means a wolf with speed 200 can attack twice as frequently as an adventurer with speed 100, just as it can move twice as frequently. We don't need a special combat timer.

 

For our first implementation, every melee attack has the standard action cost of 1,000, and an actor's effective speed determines the delay before its next action. Our original creature statistics remain unchanged. The adventurer begins with 24 HP and deals four damage. A goblin has eight HP and deals two damage, while the wolf has eleven HP and deals three damage. Attacks will always hit for now, and damage will be fixed. A character with four damage therefore subtracts four HP from its target, unless the target has fewer than four HP remaining.

 

These are temporary combat-balance values, but they make the system particularly easy to test. We can predict the result of every attack and verify that the correct character's HP changes.

 

Movement and melee use eight directions

 

Our game already supports movement in eight directions, including diagonals. We'll use the same neighbourhood for melee combat. Any living creature in one of the eight tiles immediately surrounding an attacker can be targeted. We won't impose diagonal corner restrictions and, as a matter of fact, we are removing this restriction from the previous code. If two walls meet at a corner but the diagonal destination is otherwise traversable, a walking actor can pass between them. An actor can likewise attack a diagonally adjacent creature, regardless of the terrain forming that corner.

 

There is another important distinction: the terrain beneath a target does not determine whether it can be attacked. A bat flying above a river might occupy a tile that the adventurer cannot enter. A water-dwelling creature might inhabit a lake. Neither should automatically be protected from a melee attack merely because the player cannot walk onto its tile. We therefore keep movement permissions and attack permissions separate.

 

For ordinary movement, the destination must be traversable by the moving actor and must not be occupied by another living creature. For melee combat, the target must be a different, living actor in an adjacent tile.

 

Our initial walking monsters still use the ordinary IsTileWalkable rule when wandering. We'll extend movement permissions when we introduce creatures that can fly, swim or move through other kinds of terrain. For now, the combat engine itself is ready to attack such creatures regardless of their location's terrain.

 

Introducing modCombat

 

We'll create a new standard VBA module named modCombat. Its purpose is to determine whether a melee attack is legal, apply damage and report the result. The module won't decide when the attacker acts, how monsters choose targets or how the game interface is displayed. Those responsibilities remain with the turn engine, actor system and interface modules we've already developed. This separation will become increasingly useful as we add combat mechanics.

 

First, add a function named CanMeleeAttack.

Public Function CanMeleeAttack( _
     ByVal attacker As clsActor, _
     ByVal defender As clsActor) As Boolean

     Dim deltaX As Long
     Dim deltaY As Long

     ' Both actors must exist.
     If attacker Is Nothing Then Exit Function
     If defender Is Nothing Then Exit Function

     ' An actor cannot attack itself.
     If attacker Is defender Then Exit Function

     ' Only living actors can attack or be attacked.
     If attacker.HP <= 0 Then Exit Function
     If defender.HP <= 0 Then Exit Function

     ' Determine the defender's position relative to the attacker.
     deltaX = defender.X - attacker.X
     deltaY = defender.Y - attacker.Y

     ' Melee attacks are permitted in all eight neighbouring tiles.
     If Abs(deltaX) > 1 Then Exit Function
     If Abs(deltaY) > 1 Then Exit Function

     ' Two actors on the same tile are not valid melee opponents.
     If deltaX = 0 And deltaY = 0 Then Exit Function

     ' Neither destination terrain nor diagonal corners restrict melee.
     CanMeleeAttack = True

End Function

 

The function is intentionally uncomplicated. It first confirms that both actor objects exist, that neither has died and that the attacker and defender are not the same object, and then it calculates the relative X and Y distances between them. For a melee attack to be valid, neither distance may exceed one tile. The two actors must also occupy different positions. This is equivalent to checking whether the defender lies within the eight-cell neighbourhood surrounding the attacker.

 

Notice that we don't call IsTileWalkable, nor do we examine BlocksVision. Those properties belong to terrain traversal and perception, not this basic melee-distance calculation. We'll eventually introduce ranged attacks and other abilities, each with its own range and targeting requirements. Keeping the rules in a dedicated function means other modules won't have to reproduce those calculations.

 

Resolving an attack

 

Knowing that an attack is possible is only half the problem; we also need to calculate its effect. Add the following procedure to modCombat, beneath CanMeleeAttack.

Public Sub ResolveMeleeAttack( _
     ByVal attacker As clsActor, _
     ByVal defender As clsActor)

     Dim player As clsActor
     Dim damageDone As Long
     Dim message As String

     ' Check attack legality at the moment of resolution.
     If Not CanMeleeAttack(attacker, defender) Then Exit Sub

     Set player = PlayerActor()

     ' This milestone uses non-negative, fixed damage values.
     If attacker.Damage < 0 Then
          Err.Raise vbObjectError + 401, , _
               "Attack damage cannot be negative."
     End If

     damageDone = attacker.Damage

     ' Never subtract more HP than the defender has remaining.
     If damageDone > defender.HP Then
          damageDone = defender.HP
     End If

     ' Apply damage to this individual defender.
     defender.HP = defender.HP - damageDone

     ' Construct the message appropriate to the participants.
     If attacker Is player Then

          message = "You attack the " & _
               LCase$(defender.ActorName) & _
               " for " & damageDone & " damage."

     ElseIf defender Is player Then

          message = "The " & _
               LCase$(attacker.ActorName) & _
               " attacks you for " & damageDone & " damage."

     Else

          message = "The " & _
               LCase$(attacker.ActorName) & _
               " attacks the " & _
               LCase$(defender.ActorName) & _
               " for " & damageDone & " damage."

     End If

     ' Always record combat involving the player.
     If attacker Is player Or defender Is player Then

          LogGameMessage message

     Else

          ' Report other fights occurring near the player.
          If IsEventNearPlayer(attacker.X, attacker.Y) _
               Or IsEventNearPlayer(defender.X, defender.Y) Then

               LogGameMessage message

          End If

     End If

     ' A surviving defender requires no death processing.
     If defender.HP > 0 Then Exit Sub

     ' Reveal the terrain or remaining occupant beneath a dead actor.
     RedrawWorldTile defender.X, defender.Y

     If defender Is player Then

          LogGameMessage "You die."

     Else

          If attacker Is player Then

               LogGameMessage "The " & _
                   LCase$(defender.ActorName) & " dies."

          Else

               LogWorldEvent defender.X, defender.Y, _
                   "The " & LCase$(defender.ActorName) & " dies."

          End If

     End If

End Sub

 

The first meaningful operation is another call to CanMeleeAttack. Even if the calling procedure has already checked the attack, it's sensible to validate it again at the point where damage is actually applied. This makes the combat module usable by future AI, scripts and special actions without depending on every caller performing its own checks.

 

We then retrieve the attacker's damage and cap the amount actually inflicted at the defender's remaining HP. Suppose a goblin has only two HP remaining and the adventurer attacks for four damage. The goblin loses its remaining two HP, reaching zero. We record two HP lost rather than reporting damage beyond the creature's remaining health. The defender's current HP belongs to its individual clsActor instance. Attacking one goblin therefore doesn't change the HP of another goblin created from the same definition.

 

Next, the procedure constructs a message appropriate to the participants. When the player attacks, the message begins with "You attack". When a monster attacks the player, the message identifies the monster and says that it attacks "you". When two non-player creatures fight, both are named. This last case is important for our longer-term design. Our initial monsters will attack the adventurer rather than one another, but the combat resolver itself shouldn't assume that every fight must involve the player.

 

We also need to distinguish between resolving an event and reporting it. Any combat involving the player is always recorded. Combat between other actors is recorded when it occurs within the area the player can currently observe. For the moment, we'll approximate observability using the four-tile neighbourhood introduced in the previous milestone. Once we build our field-of-vision system, the reporting function will be able to use actual visibility instead.

 

Finally, if the defender reaches zero HP, the procedure calls RedrawWorldTile. That function already knows how to reconstruct a displayed tile from the underlying terrain and living actors. Since our renderer ignores actors with zero HP, a dead monster disappears and the terrain beneath it becomes visible again. We don't need to replace the cell manually with a floor character or remember what symbol used to appear there. That separation between the displayed worksheet and the underlying world state is paying off again.

 

Turning movement into an attack

 

Traditional roguelikes often use a convenient interaction known as bump-to-attack. Rather than requiring a separate attack button and target-selection interface, the player attacks a creature by attempting to move into its occupied tile. We'll use the same behaviour. If the player clicks East and the tile to the east contains a living goblin, the movement command becomes a melee attack against that goblin. The player doesn't actually enter the goblin's tile - attacking and moving remain distinct actions, each with its own time cost. Even if an attack kills the goblin, the player stays in their original position. Moving onto the newly unoccupied tile requires another command.

 

We'll implement this in modPlayer, reusing the existing movement controls from Part 2. Replace the current private MovePlayer procedure with the following complete version.

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

     ' Accept gameplay commands only during the player's turn.
     If Not CanPlayerAct() Then Exit Sub

     Set player = PlayerActor()

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

     ' Examine occupancy before checking terrain walkability.
     ' A monster on impassable terrain may still be attacked.
     Set monster = MonsterAt(newX, newY)

     If Not monster Is Nothing Then

          ' Attacks may target any of the eight adjacent tiles.
          If Not CanMeleeAttack(player, monster) Then

               LogGameMessage "You cannot reach that creature."
               Exit Sub

          End If

          ' Begin a timed attack action.
          If Not BeginPlayerAction() Then Exit Sub

          ' Resolve damage and any resulting monster death.
          ResolveMeleeAttack player, monster

          ' An attack does not change the player's position.
          CompletePlayerAction STANDARD_ACTION_COST

          Exit Sub

     End If

     ' Ordinary movement requires a walkable destination.
     If Not IsTileWalkable(newX, newY) Then

          LogGameMessage GetTerrainMessage(newX, newY, True)
          Exit Sub

     End If

     ' No diagonal corner restriction is imposed.
     ' Only the destination's terrain and occupancy matter.

     ' Begin a timed movement action.
     If Not BeginPlayerAction() Then Exit Sub

     ' Remember the previous coordinates for redrawing.
     oldX = player.X
     oldY = player.Y

     ' Move the actor to the new position.
     player.X = newX
     player.Y = newY

     ' Reconstruct the two affected world tiles.
     RedrawWorldTile oldX, oldY
     RedrawWorldTile newX, newY

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

     ' Schedule the next player turn and process monster events.
     CompletePlayerAction STANDARD_ACTION_COST

End Sub

 

The order of checks deserves attention. We first ask whether a monster occupies the requested destination. If it does, we consider combat immediately. Only when the destination contains no living monster do we check the terrain's walkability. This allows us to attack a creature occupying a non-walkable tile without permitting the player to enter that tile.

 

For ordinary movement, we still require a walkable destination. There is no additional restriction on moving diagonally between two obstructed orthogonal neighbours, which keeps the rule consistent with our eight-direction combat system.

 

A legal attack calls BeginPlayerAction, resolves the attack and then calls CompletePlayerAction. These are the same scheduler functions used for movement and waiting. Consequently, melee attacks participate naturally in the timing system introduced in Part 5. If the player has normal speed, an attack delays their next action by 1,000 time units. If their effective speed changes later, the scheduler can calculate the corresponding delay without changing MovePlayer. The eight public directional procedures, their button assignments and our existing WaitTurn procedure remain unchanged.

 

Giving monsters the ability to fight back

 

Our monsters already have a simple decision-making procedure named PerformMonsterAction. In Part 5, it examined the surrounding tiles, identified legal movements and selected randomly from those available destinations. If no movement was possible, the creature waited. We'll retain that behaviour for monsters that aren't currently able to attack, but when the player enters melee range, attacking will take priority over wandering.

 

Open modActors and replace PerformMonsterAction with the following implementation.

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 monsters can act.
     If actor Is Nothing Then Exit Sub
     If actor.HP <= 0 Then Exit Sub

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

     ' Attack whenever the player is within legal melee range.
     If CanMeleeAttack(actor, player) Then

          ResolveMeleeAttack actor, player
          Exit Sub

     End If

     ' Otherwise, construct a list of legal movement choices.
     Set validMoves = New Collection

     For direction = 0 To 8

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

          ' Exclude the centre of the 3 x 3 neighbourhood.
          If deltaX <> 0 Or deltaY <> 0 Then

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

               ' Only the destination must be traversable.
               canMove = IsTileWalkable(testX, testY)

               ' The player cannot share the destination tile.
               If canMove Then

                    If testX = player.X And testY = player.Y Then
                          canMove = False
                    End If
               End If

               ' Other living monsters also occupy their own tiles.
               If canMove Then

                    Set otherMonster = MonsterAt(testX, testY)

                    If Not otherMonster Is Nothing Then
                           canMove = False
                    End If
               End If

               ' Store only legal movement directions.
               If canMove Then
                    validMoves.Add Array(deltaX, deltaY)
               End If

          End If

     Next direction

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

     ' Select one legal destination at random.
     chosenMove = validMoves( _
          Int(Rnd() * validMoves.Count) + 1)

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

     ' Preserve the old position before moving.
     oldX = actor.X
     oldY = actor.Y

     actor.X = oldX + deltaX
     actor.Y = oldY + deltaY

     ' Restore terrain and visible actors at both positions.
     RedrawWorldTile oldX, oldY
     RedrawWorldTile actor.X, actor.Y

     ' Record a nearby world event through the shared logger.
     LogWorldEvent actor.X, actor.Y, _
          "The " & LCase$(actor.ActorName) & " moves nearby."

End Sub

 

The first new decision occurs near the beginning of the procedure. When CanMeleeAttack(actor, player) returns True, the monster attacks and the procedure ends; otherwise, it proceeds with its usual wandering behaviour. That makes attacking deterministic when the player is adjacent, even though wandering remains random. It also means the same melee-range rules apply to monsters and the player. Diagonal attacks are permitted, terrain doesn't grant accidental immunity, and movement into occupied cells remains prohibited.

 

There is no direct manipulation of the game clock in this procedure. The turn engine invokes PerformMonsterAction when the monster is ready, and the monster's action is scheduled again afterwards. Our wolf's speed advantage therefore applies automatically to combat.

 

At this stage, monsters won't deliberately pursue the player across the map. They wander until the player enters their immediate melee range, at which point they attack. Proper pursuit will come later, when monsters have perception and awareness rules. Similarly, we haven't introduced faction hostility between monsters. Our combat module is capable of resolving non-player fights, but the present AI doesn't select other monsters as targets. These are intentional limits on monster intelligence, not limits on the combat system itself.

 

Monster death and the state of the world

 

When a monster dies, we need more than a message. It must stop appearing on the screen, stop blocking movement and stop receiving scheduled actions. At the same time, we don't want to corrupt the terrain array or interfere with references held by the turn engine. Fortunately, much of this behaviour is already supported by our actor system. MonsterAt searches for living monsters, ignoring instances whose HP is zero or below. NextScheduledMonster likewise selects only living actors, and our rendering procedures don't draw dead actors. Consequently, when ResolveMeleeAttack reduces a monster to zero HP, calling RedrawWorldTile is enough to make it disappear from the display. The map engine restores the underlying terrain, and the actor renderer no longer overlays that monster.

 

The object itself remains in the active monster collection. This is useful because other parts of the game may still hold a reference to it during the current action. We don't need to remove elements from a collection while other procedures are iterating over it. Later, those retained objects might also help with corpses, death effects, dropped possessions or resurrection mechanics, although we haven't implemented any of those features yet. For this milestone, zero HP represents death, and dead actors are inactive. The same basic HP rule applies to the player, but player death has much broader consequences.

 

Ending the adventure when the player dies

 

Our game is intended to be a roguelike with permadeath, which means that when the adventurer reaches zero HP, the current run ends. This needs to happen immediately.

 

Suppose several monsters have actions scheduled before the player's next turn. If the first monster kills the adventurer, the remaining monsters must not continue attacking or moving as though the player were still alive. The turn scheduler is the appropriate place to enforce this. We'll add a separate session-ended state, ensuring that no further gameplay actions are accepted after death. We'll also preserve the final game time and message history so the player can review the events leading to their defeat.

 

Tracking the end of a game session

 

Open modTurnEngine. Alongside its existing module-level declarations, add:

' True after the player's current adventure has ended.
Private mSessionEnded As Boolean

 

Then replace ResetTurnSession with:

Public Sub ResetTurnSession()

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

     ' Make a new adventure eligible for gameplay.
     mSessionEnded = False

     ' Reset the count of accepted player actions.
     mPlayerActionCount = 0

End Sub

 

We'll explain mPlayerActionCount shortly, when we develop the expanded message history. It is a separate count of player actions rather than simulated game time. The existing StartTurnSession procedure can continue calling ResetTurnSession when a new game begins.

 

We also need to prevent commands from being accepted outside the active gameplay screen. Our new history viewer will live on another worksheet, and opening that viewer must not accidentally allow the game to advance.

 

Replace CanPlayerAct with:

Public Function CanPlayerAct() As Boolean

     Dim player As clsActor

     Set player = PlayerActor()

     If player Is Nothing Then Exit Function

     ' A finished adventure cannot accept gameplay commands.
     If mSessionEnded Then Exit Function

     ' Commands are accepted only from the active game screen.
     If Not (ActiveSheet Is GameScreen()) Then Exit Function

     ' The scheduler must be waiting for player input.
     If Not mWaitingForPlayer Then Exit Function

     ' The Options menu temporarily disables gameplay controls.
     If IsOptionsOpen() Then Exit Function

     ' A dead character cannot take ordinary actions.
     If player.HP <= 0 Then Exit Function

     CanPlayerAct = True

End Function

 

This becomes our central check for whether the player may submit an action. It checks that a player exists, that the game session is active, that the correct worksheet is displayed, that the scheduler is awaiting input and that the player is alive. This is more reliable than letting individual movement procedures independently determine whether a game is currently playable.

 

Stopping the scheduler immediately

 

Now replace the existing private AdvanceToPlayerTurn procedure in modTurnEngine with the following version:

Private Sub AdvanceToPlayerTurn()

     Dim player As clsActor
     Dim monster As clsActor

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

     Do

          ' Find the next living monster scheduled to act.
          Set monster = NextScheduledMonster()

          ' With no monsters remaining, advance to the player.
          If monster Is Nothing Then

               mGameTime = player.NextActionTime
               Exit Do

          End If

          ' The player has priority when readiness times are equal.
          If player.NextActionTime <= monster.NextActionTime Then

               mGameTime = player.NextActionTime
               Exit Do

          End If

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

          ' Allow the monster to move, wait or attack.
          PerformMonsterAction monster

          ' Record a scheduling trace for development and testing.
          Debug.Print "Time " & Format$(mGameTime, "0.##"), _
               monster.InstanceID & " acts"

          ' Stop immediately if this action has killed the player.
          If player.HP <= 0 Then

               mSessionEnded = True
               mWaitingForPlayer = False

               ' Preserve final statistics and the time of death.
               UpdatePlayerStatus

               ' Display Game Over without clearing the event history.
               ShowGameOverScreen

               Exit Sub

          End If

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

     Loop

     ' The next player action is now ready.
     mWaitingForPlayer = True

     ' Refresh the status after all intervening events.
     UpdatePlayerStatus

End Sub

 

Most of the scheduler remains the same as in Part 5. It continues finding the earliest scheduled monster, jumping to that monster's action time and processing the event. The significant addition comes immediately after PerformMonsterAction: we check the player's HP before scheduling any further monster activity. If the player is dead, we terminate the session, update the final status and display the Game Over interface. The procedure then exits.

This preserves the exact simulated time at which the fatal attack occurred. It also ensures that a wolf with another action pending doesn't continue attacking a corpse, and that other monsters don't continue wandering while the game is supposed to be over.

 

If the player survives, the scheduler continues normally.

 

The player still has priority when action times are equal. This means an adventurer ready at exactly the same time as a wolf gets to act first, which can be important when a single attack might decide the fight.

 

Creating the Game Over screen

 

We already have a central interface module, modInterface, that creates and manages the game's navigation buttons using Excel shapes. We'll use the same approach for the Game Over screen. Rather than switching to a separate worksheet or deleting the map, we'll overlay a few shapes over the visible game area. This allows the player to see the location where the adventure ended, while clearly indicating that ordinary gameplay is no longer available.

 

The Game Over display will contain a large "YOU DIED" title and two buttons: New Game and Main Menu. New Game will immediately initialise a fresh run, while Main Menu will return to the startup screen introduced in Part 3. Both options will discard the dead session, but only when the player actually selects one of them.

 

Creating the Game Over controls

 

In BuildGameInterface, add this local variable to the existing declarations:

Dim deathArea As Range

 

Then, after the existing interface buttons have been created, add:

' Retrieve the central map area for positioning the death overlay.
Set deathArea = MapArea()

' Create the Game Over title.
Set btn = GetOrCreateButton(ws, "btnGameOverTitle")

With btn
     .Width = 260
     .Height = 70
     .Left = deathArea.Left + (deathArea.Width - .Width) / 2
     .Top = deathArea.Top + (deathArea.Height - .Height) / 2 - 55
End With

FormatButton btn, "YOU DIED", RGB(82, 42, 49)
btn.TextFrame.Characters.Font.Size = 24

' Create the New Game button.
Set btn = GetOrCreateButton(ws, "btnGameOverNewGame")

With btn
     .Width = 115
     .Height = 34
     .Left = deathArea.Left + deathArea.Width / 2 - 120
     .Top = deathArea.Top + deathArea.Height / 2 + 30
End With

FormatButton btn, "NEW GAME", RGB(39, 115, 83)
btn.OnAction = MacroReference("StartNewGame")

' Create the Main Menu button.
Set btn = GetOrCreateButton(ws, "btnGameOverMainMenu")

With btn
     .Width = 115
     .Height = 34
     .Left = deathArea.Left + deathArea.Width / 2 + 5
     .Top = deathArea.Top + deathArea.Height / 2 + 30
End With

FormatButton btn, "MAIN MENU", RGB(39, 70, 84)
btn.OnAction = MacroReference("ShowMainMenu")

 

We're reusing the existing GetOrCreateButton, FormatButton and MacroReference helpers. This means repeated initialisation doesn't create duplicate controls, and the shapes retain the visual style we've already established for the interface.

 

The controls are positioned relative to MapArea(), so their placement remains independent of the exact worksheet coordinates.

 

At the end of SetGameplayControlsVisible, add the following instructions to keep the Game Over overlay hidden during normal gameplay and on the main menu:

' Game Over controls remain hidden until the player dies.
ws.Shapes("btnGameOverTitle").Visible = msoFalse
ws.Shapes("btnGameOverNewGame").Visible = msoFalse
ws.Shapes("btnGameOverMainMenu").Visible = msoFalse

 

Next, add a public procedure to modInterface that reveals the overlay when the player's HP reaches zero.

Public Sub ShowGameOverScreen()

     Dim ws As Worksheet
     Dim buttonNames As Variant
     Dim i As Long

     Set ws = GameScreen()
     buttonNames = NavigationNames()

     ' Close the in-game Options panel.
     mOptionsOpen = False

     ' Hide the ordinary gameplay and menu controls.
     ws.Shapes("btnNewGame").Visible = msoFalse
     ws.Shapes("btnOptions").Visible = msoFalse
     ws.Shapes("btnOptionsMainMenu").Visible = msoFalse

     For i = LBound(buttonNames) To UBound(buttonNames)
          ws.Shapes(CStr(buttonNames(i))).Visible = msoFalse
     Next i

     ' Reveal the title and the two Game Over choices.
     ws.Shapes("btnGameOverTitle").Visible = msoTrue
     ws.Shapes("btnGameOverNewGame").Visible = msoTrue
     ws.Shapes("btnGameOverMainMenu").Visible = msoTrue

     ' Keep the adventure's message history accessible.
     ws.Shapes("btnLogHistory").Visible = msoTrue

     ' Bring the Game Over controls above the map.
     ws.Shapes("btnGameOverTitle").ZOrder msoBringToFront
     ws.Shapes("btnGameOverNewGame").ZOrder msoBringToFront
     ws.Shapes("btnGameOverMainMenu").ZOrder msoBringToFront

     ws.Activate

End Sub

 

The procedure hides normal gameplay controls and reveals the Game Over interface. Notice that it doesn't reset the player, clear the monsters or discard the message log. The current run has ended, but we deliberately preserve its final state until the player chooses what to do next. This is particularly important for the event history we're about to introduce.

 

Keeping a history of what happens

 

Combat introduces a new challenge for our user interface: a single player action can now trigger several consequences. For example, the adventurer might attack a wolf. The wolf could retaliate immediately, attack again at its next scheduled time, and another nearby goblin might move towards the player. If every event simply replaced the previous message, the player would have no way to reconstruct what happened.

 

We already introduced accumulated messages in Part 5. We'll now extend that system to maintain a broader event history across the adventure: there will be two separate views of the same information. The ordinary message panel will show recent events belonging to the current player-action cycle. It remains compact enough to fit beneath the map, while a dedicated GameLog worksheet will display the retained history, including the player turn, exact game time and event description. Players will be able to scroll through it, filter individual turns and review the final attacks after death.

 

We'll retain the most recent 100 player turns, with all messages generated during each of those turns. This is different from retaining 100 individual messages. A single turn might generate several attacks, movement messages and trap events. We want to keep those events together.

 

Separating player turns from game time

 

In Part 5, we introduced a game clock measured in simulated time units. That clock is useful for scheduling, but it isn't the same thing as a count of player decisions. A normal-speed player might perform one action every 1,000 game-time units, but that relationship won't always hold. Different action costs and speed modifiers will eventually affect how much time passes between decisions.

 

We'll therefore track the number of accepted player actions separately. In modTurnEngine, add:

' Counts accepted player actions independently of simulated game time.
Private mPlayerActionCount As Long

Public Function CurrentTurnNumber() As Long

     CurrentTurnNumber = mPlayerActionCount

End Function

 

We already included the reset of this counter in ResetTurnSession.

 

Now replace BeginPlayerAction with:

Public Function BeginPlayerAction() As Boolean

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

     ' Prevent another action while this one is being processed.
     mWaitingForPlayer = False

     ' Count movement, attacks and waiting as player turns.
     mPlayerActionCount = mPlayerActionCount + 1

     ' Begin a new batch for this action and subsequent events.
     StartMessageBatch

     BeginPlayerAction = True

End Function

 

The counter increases only when the player submits a valid timed action. Movement, attacking and waiting each count as one turn. Attempting to enter an impassable empty tile doesn't count, and neither does opening Options or viewing the event history.

 

The distinction gives us two useful measurements: the number of actions the player has taken and the amount of simulated time that has passed. We'll display both in the status panel and record both in the detailed log.

 

Extending modMessages

 

Open modMessages, which we introduced in Part 5. We'll keep the current-action message collection and add a second collection that stores the adventure's retained event history. Each history entry will contain the player-turn number, the simulated game time and the event text. The module will also provide a common way for other game systems to report events occurring near the player.

 

That last detail matters beyond combat. When we introduce traps, environmental effects or monsters fighting one another, those events should use the same reporting system.

 

Add the following declarations near the top of modMessages, retaining the existing mTurnMessages declaration:

' Complete retained history of the current adventure.
Private mSessionMessages As Collection

' Number of text lines reserved in the compact message display.
Private Const MAX_PANEL_LINES As Long = 4

 

We'll also define the temporary observation range centrally. In modGlobals, add:

' Event-reporting radius until field of vision is implemented.
Public Const EVENT_AWARENESS_RADIUS As Long = 4

 

Reporting observable events

 

Add these two procedures to modMessages:

Public Function IsEventNearPlayer( _
     ByVal x As Long, _
     ByVal y As Long) As Boolean

     Dim player As clsActor

     Set player = PlayerActor()

     If player Is Nothing Then Exit Function

     ' Use a temporary square observation neighbourhood.
     IsEventNearPlayer = _
          Abs(x - player.X) <= EVENT_AWARENESS_RADIUS _
          And Abs(y - player.Y) <= EVENT_AWARENESS_RADIUS

End Function

Public Sub LogWorldEvent( _
     ByVal x As Long, _
     ByVal y As Long, _
     ByVal message As String)

     ' Report events that occur within the observable neighbourhood.
     If IsEventNearPlayer(x, y) Then
          LogGameMessage message
     End If

End Sub

 

The current observation rule uses a square neighbourhood extending four tiles in each direction. This is only an approximation; it doesn't yet consider intervening walls or other opaque terrain. When we implement field of vision, we'll replace the internal logic of IsEventNearPlayer with a genuine visibility check.

 

The useful architectural point is that other modules won't need to change. They can continue calling LogWorldEvent with the location and message. For example, a future trap system might use:

LogWorldEvent trapX, trapY, "A concealed trap snaps shut."

 

The trap system will be responsible for triggering the trap and applying its effects. The message module will decide whether the event should be reported to the player. Likewise, our combat resolver can report fighting between two monsters when it occurs in the observable area, even though the player isn't one of the participants.

 

We haven't implemented traps or monster factions yet; we're establishing a common interface that those future systems can use.

 

Recording messages in both collections

 

Replace LogGameMessage with:

Public Sub LogGameMessage(ByVal message As String)

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

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

     ' Initialise the session-history collection if necessary.
     If mSessionMessages Is Nothing Then
          Set mSessionMessages = New Collection
     End If

     ' Preserve the event in the current player-action cycle.
     mTurnMessages.Add message

     ' Also preserve turn number, game time and event text.
     mSessionMessages.Add Array( _
          CurrentTurnNumber(), CurrentGameTime(), message)

     ' Update the compact on-screen message display.
     RefreshMessagePanel

End Sub

 

Every recorded event is now stored in two places. The current-action collection determines what the player sees beneath the map, while the session-history collection preserves the event with its turn number and timestamp. The collections serve different purposes, but both are maintained through one procedure. This means combat code doesn't need to understand how the log is stored or displayed - it simply submits a message.

 

Retaining the latest 100 turns

 

Replace StartMessageBatch with:

Public Sub StartMessageBatch()

     Dim oldestEntry As Variant
     Dim firstRetainedTurn As Long

     ' Begin a new batch for the current player action.
     Set mTurnMessages = New Collection

     ' Retain the current turn and the preceding 99 turns.
     firstRetainedTurn = CurrentTurnNumber() - 99

     If Not mSessionMessages Is Nothing Then

          ' The collection is stored in chronological order.
          Do While mSessionMessages.Count > 0

               oldestEntry = mSessionMessages(1)

               If CLng(oldestEntry(0)) >= firstRetainedTurn Then
                    Exit Do
               End If

               mSessionMessages.Remove 1

          Loop

     End If

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

End Sub

 

The history is pruned whenever a new player-action cycle begins. Suppose the player begins turn 250. The retained history will cover turns 151 through 250, including every event generated within those turns.

 

We don't impose an arbitrary maximum number of messages per turn. If a particularly eventful action generates several attacks or environmental effects, all of them can remain together. This makes the log more useful than a fixed limit of 100 individual messages; it also ensures that memory usage doesn't grow indefinitely during a long adventure.

 

Displaying recent messages beneath the map

 

The full history may contain many events, but we don't want the ordinary game interface to become dominated by text. We'll keep the compact message panel at K23:X26.

 

Replace RefreshMessagePanel with:

Private Sub RefreshMessagePanel()

     Dim i As Long
     Dim firstMessage As Long
     Dim messageText As String
     Dim hiddenCount As Long

     If mTurnMessages Is Nothing Then Exit Sub
     If mTurnMessages.Count = 0 Then Exit Sub

     ' Normally show the whole current message batch.
     firstMessage = 1

     ' Reserve room for an overflow indicator when necessary.
     If mTurnMessages.Count > MAX_PANEL_LINES Then

          firstMessage = mTurnMessages.Count - _
               (MAX_PANEL_LINES - 2)

          hiddenCount = firstMessage - 1

          messageText = "(" & hiddenCount & _
               " earlier events - open LOG)"

     End If

     ' Append the visible messages in chronological order.
     For i = firstMessage To mTurnMessages.Count

          If Len(messageText) > 0 Then
               messageText = messageText & vbLf
          End If

          messageText = messageText & CStr(mTurnMessages(i))

     Next i

     ' Write the result to the top-left cell of the merged panel.
     GameScreen().Range(MESSAGE_CELL_ADDRESS).Value2 = messageText

End Sub

 

For short message batches, all events are displayed. If the batch becomes too long for the compact panel, the function displays the most recent three messages and indicates that earlier events can be found through LOG. The complete session history remains available separately.

 

We'll retain the PrepareMessagePanel procedure from Part 5, which merges and formats the message region. Similarly, ClearGameMessages continues clearing the message collections and the full MESSAGE_PANEL_ADDRESS range. Its updated implementation is:

Public Sub ClearGameMessages()

     ' Discard current messages and the retained adventure history.
     Set mTurnMessages = Nothing
     Set mSessionMessages = Nothing

     ' Clear the complete multi-line display region.
     GameScreen().Range(MESSAGE_PANEL_ADDRESS).ClearContents

End Sub

 

The message system is now independent of the individual game mechanics generating its content. Combat can produce attack and death message, monster movement can report nearby activity, future traps can report triggering and damage, and spells can report their effects. All of those systems can use the same logging interface.

 

Building the detailed event-history viewer

 

A compact message panel works well during ordinary movement, but it's not particularly suitable for reviewing a long fight. We want to be able to inspect exactly what happened, identify which player action produced a sequence of events and see the game-time interval between those events.

 

We'll create a dedicated worksheet named GameLog. The worksheet will be generated when the player first opens the history, and it will display a three-column table containing player turn, game time and event description. We'll also make the history practical to navigate. The headings will remain visible while scrolling, Excel's AutoFilter will allow events to be filtered, and opening the log will automatically position the view at the newest entry. A Back to Game button will return to the current game screen without consuming any simulated time.

 

Centralising the log worksheet name

 

Add the following constant to modGlobals:

Public Const SHEET_LOG As String = "GameLog"

 

Creating and populating the history worksheet

 

Add this procedure to modMessages:

Public Sub ShowMessageHistory()

     Dim ws As Worksheet
     Dim btn As Shape

     Dim eventData() As Variant
     Dim entry As Variant

     Dim i As Long
     Dim eventCount As Long
     Dim lastRow As Long

     ' Locate the existing log worksheet, if available.
     On Error Resume Next
     Set ws = ThisWorkbook.Worksheets(SHEET_LOG)
     On Error GoTo 0

     ' Create the worksheet on its first use.
     If ws Is Nothing Then

          Set ws = ThisWorkbook.Worksheets.Add(After:=GameScreen())
          ws.Name = SHEET_LOG

     End If

     ws.Visible = xlSheetVisible

     ' Remove previous filters before refreshing the display.
     If ws.AutoFilterMode Then ws.AutoFilterMode = False

     ws.Cells.ClearContents

     ' Create a readable heading and three-column log.
     With ws

          .Range("A1").Value2 = "EXCEL RPG - EVENT HISTORY"
          .Range("A1").Font.Bold = True
          .Range("A1").Font.Size = 16

          .Range("A2").Value2 = "Last 100 player turns"

          .Range("A4").Value2 = "Turn"
          .Range("B4").Value2 = "Game time"
          .Range("C4").Value2 = "Event"

          With .Range("A4:C4")

               .Font.Bold = True
               .Interior.Color = RGB(39, 70, 84)
               .Font.Color = RGB(245, 250, 252)

          End With

          .Columns("A").ColumnWidth = 10
          .Columns("B").ColumnWidth = 15
          .Columns("C").ColumnWidth = 85

          .Rows(2).RowHeight = 34

     End With

     ' Count the retained events in the current adventure.
     If Not mSessionMessages Is Nothing Then
          eventCount = mSessionMessages.Count
     End If

     If eventCount > 0 Then

          ' Prepare a two-dimensional array for bulk writing.
          ReDim eventData(1 To eventCount, 1 To 3)

          For i = 1 To eventCount

               entry = mSessionMessages(i)

               eventData(i, 1) = CLng(entry(0))
               eventData(i, 2) = CDbl(entry(1))
               eventData(i, 3) = CStr(entry(2))

          Next i

          ' Write the complete retained history in one operation.
          ws.Range("A5").Resize(eventCount, 3).Value2 = eventData

          lastRow = eventCount + 4

          ws.Range("A5:A" & lastRow).NumberFormat = "0"
          ws.Range("B5:B" & lastRow).NumberFormat = "0.##"
          ws.Range("C5:C" & lastRow).WrapText = True

          ws.Range("A5:C" & lastRow).Rows.AutoFit

     Else

          lastRow = 5
          ws.Range("C5").Value2 = "No events recorded."

     End If

     ' Allow the player to filter by turn, time or event.
     ws.Range("A4:C" & lastRow).AutoFilter

     ' Find the existing Back to Game shape, if present.
     On Error Resume Next
     Set btn = ws.Shapes("btnBackToGame")
     On Error GoTo 0

     ' Create the button only when necessary.
     If btn Is Nothing Then

          Set btn = ws.Shapes.AddShape( _
               msoShapeRoundedRectangle, _
               ws.Range("C2").Left, _
               ws.Range("C2").Top, _
               135, 28)

          btn.Name = "btnBackToGame"

     End If

     ' Position, format and assign the return control.
     With btn

          .Left = ws.Range("C2").Left
          .Top = ws.Range("C2").Top
          .Width = 135
          .Height = 28

          .Placement = xlFreeFloating
          .Fill.ForeColor.RGB = RGB(39, 70, 84)
          .Line.ForeColor.RGB = RGB(85, 120, 135)

          With .TextFrame

               .Characters.Text = "BACK TO GAME"
               .HorizontalAlignment = xlHAlignCenter
               .VerticalAlignment = xlVAlignCenter

               With .Characters.Font

                     .Name = "Segoe UI"
                     .Size = 10
                     .Bold = True
                       .Color = RGB(245, 250, 252)

               End With

          End With

          ' Qualify the macro with the current workbook name.
          .OnAction = "'" & _
               Replace(ThisWorkbook.Name, "'", "''") & _
               "'!ReturnToGameScreen"

     End With

     ' Activate the history and freeze the column headings.
     ws.Activate

     ActiveWindow.FreezePanes = False
     ws.Range("A5").Select
     ActiveWindow.FreezePanes = True

     ' Open the viewer at its most recent retained event.
     ws.Cells(lastRow, 3).Select

End Sub

 

The underlying history is a collection of small arrays, but Excel's worksheet display works best when we prepare a two-dimensional array and transfer its contents in a single operation. We already used a similar technique in our map renderer, where bulk writing greatly reduced worksheet operations. Here, we construct an eventData array with one row per retained message and three columns for turn number, game time and event text. We then write the array to the history worksheet in one assignment. The result is a familiar Excel table-like view, even though we don't need to create another structured ListObject for it.

 

Column headings are formatted for readability and an AutoFilter is applied. The user can filter by turn number, time or particular event descriptions. We also freeze the headings and select the newest event when opening the viewer. That combination makes it straightforward to inspect the events immediately preceding a player's death or scroll backwards to an earlier turn.

 

The Back to Game shape is created only once and reused on subsequent visits.

 

Returning to the game

 

Add the following procedure beneath ShowMessageHistory:

Public Sub ReturnToGameScreen()

     Dim ws As Worksheet

     ' Return to the current gameplay or Game Over screen.
     GameScreen().Activate

     ' Keep the detailed history hidden until requested again.
     Set ws = ThisWorkbook.Worksheets(SHEET_LOG)
     ws.Visible = xlSheetVeryHidden

End Sub

 

Opening the history viewer doesn't advance the game clock or change actor state. The game isn't running on a continuous timer, so there is no background simulation to suspend. The worksheet simply changes while the player reviews the events. When the Back to Game button is clicked, the player returns to the same gameplay or Game Over screen. The history worksheet is then made VeryHidden, keeping it out of the ordinary worksheet interface until the LOG button is used again.

 

We now have a detailed record of the recent adventure without enlarging the game screen indefinitely.

 

Reorganising the on-screen status display

 

As the game grows, the status area must display more than a pair of coordinates. We now have health, damage, position, player turn number and simulated game time. Rather than concatenate everything into one long line, we'll distribute those values vertically within the existing status area.

 

In modGlobals, retain STATUS_CELL_ADDRESS = "B23" and add:

Public Const STATUS_POSITION_CELL_ADDRESS As String = "B24"
Public Const STATUS_TURN_CELL_ADDRESS As String = "B25"
Public Const STATUS_TIME_CELL_ADDRESS As String = "B26"

 

Then replace UpdatePlayerStatus in modPlayer with:

Public Sub UpdatePlayerStatus()

     Dim player As clsActor
     Dim ws As Worksheet

     Set player = PlayerActor()

     If player Is Nothing Then Exit Sub

     Set ws = GameScreen()

     ' First line: current health and damage.
     ws.Range(STATUS_CELL_ADDRESS).Value2 = _
          "HP " & player.HP & "/" & player.MaxHP & _
          " Dmg " & player.Damage

     ' Second line: coordinates within the active location.
     ws.Range(STATUS_POSITION_CELL_ADDRESS).Value2 = _
          "POS (" & player.X & "," & player.Y & ")"

     ' Third line: accepted player-action count.
     ws.Range(STATUS_TURN_CELL_ADDRESS).Value2 = _
          "TURN " & CurrentTurnNumber()

     ' Fourth line: simulated game time.
     ws.Range(STATUS_TIME_CELL_ADDRESS).Value2 = _
          "TIME " & Format$(CurrentGameTime(), "0.##")

End Sub

 

The player status now occupies four short lines, leaving the adjacent message panel independent. TURN represents the number of accepted player actions. TIME represents simulated game time, which advances according to the action scheduler. Keeping these separate will become increasingly important when we introduce haste, slowing and actions with different time costs. The displayed damage is labelled Dmg, making it easier to distinguish from the other statistics.

 

When returning to the main menu, we'll clear the additional status lines. Because the layout may contain merged cells, we'll clear the complete merged area belonging to each status address. Inside ShowMainMenu, after setting the main status to "MAIN MENU", add:

' Clear the previous adventure's additional status lines.
ws.Range(STATUS_POSITION_CELL_ADDRESS).MergeArea.ClearContents
ws.Range(STATUS_TURN_CELL_ADDRESS).MergeArea.ClearContents
ws.Range(STATUS_TIME_CELL_ADDRESS).MergeArea.ClearContents

 

This allows the status layout to use merged cells for formatting while keeping the worksheet-reset logic consistent.

 

Giving the event log its own button

 

We now have a detailed history viewer, but the player needs a convenient way to open it. In Part 5, we added an Options button to the game interface. We'll keep that feature and place a smaller LOG button directly beneath it, using the narrow black border on the right side of the worksheet. The controls will be arranged vertically in column AH. The Options button will occupy AH2:AH3, while LOG will occupy AH4:AH5. The expandable Main Menu entry will appear immediately to the left of Options, at AB2:AG3. This arrangement keeps both controls readily available without occupying space inside the map or covering the main message panel.

 

Updating the interface configuration

 

Add or update the following constants in modGlobals:

' Options and message-history controls in the right-hand border.
Public Const OPTIONS_BUTTON_ADDRESS As String = "AH2:AH3"
Public Const OPTIONS_DROPDOWN_ADDRESS As String = "AB2:AG3"
Public Const HISTORY_BUTTON_ADDRESS As String = "AH4:AH5"

 

Our existing BuildGameInterface procedure already positions the Options and Main Menu controls using their corresponding range constants, so those controls will use the revised positions when the interface is built. We only need to create the new LOG button. Inside BuildGameInterface, after the existing Options controls have been created, add:

' Create the message-history button beneath Options.
Set btn = GetOrCreateButton(ws, "btnLogHistory")

With btn
     .Left = ws.Range(HISTORY_BUTTON_ADDRESS).Left
     .Top = ws.Range(HISTORY_BUTTON_ADDRESS).Top
     .Width = ws.Range(HISTORY_BUTTON_ADDRESS).Width
     .Height = ws.Range(HISTORY_BUTTON_ADDRESS).Height
End With

FormatButton btn, "LOG", RGB(48, 76, 91)

' Use a compact label suitable for the narrow border column.
btn.TextFrame.Characters.Font.Size = 9

btn.OnAction = MacroReference("ShowMessageHistory")

 

The shape is created using the same reusable button helpers as the rest of our interface. Because the control is positioned using a named worksheet range, its location can be adjusted through modGlobals without changing the shape-generation logic. The button calls ShowMessageHistory, which prepares the log worksheet and opens it at the newest retained event.

 

We'll also make the button available on the Game Over screen. This allows the player to inspect the final combat sequence before deciding whether to start another game.

 

Controlling the LOG button's visibility

 

Near the end of SetGameplayControlsVisible, add:

' The event log is available during an active game.
If playing Then
     ws.Shapes("btnLogHistory").Visible = msoTrue
Else
     ws.Shapes("btnLogHistory").Visible = msoFalse
End If

 

During ordinary gameplay, the button remains visible alongside Options. When we return to the main menu, it is hidden. During Game Over, ShowGameOverScreen explicitly makes it visible again, preserving access to the events leading to the player's death.

 

Starting a new adventure

 

Our growing game now maintains several kinds of session state: the actor system holds the player and monster instances, the turn engine stores the current game time, player readiness and completed-action count, the message module stores both the current message batch and the retained adventure history. Starting a new game must reset all these systems consistently.

 

Open modGame and replace StartNewGame with:

Public Sub StartNewGame()

     Dim player As clsActor

     ' Discard the previous adventure's timing and actor state.
     ResetTurnSession
     ResetPlayer

     ' Discard the previous adventure's event history.
     ClearGameMessages

     ' Load the initial map and recreate all active characters.
     ShowMap

     ' Confirm that the player was successfully initialised.
     Set player = PlayerActor()
     If player Is Nothing Then Exit Sub

     ' Start the clock and establish the initial action schedule.
     StartTurnSession

     ' Reveal ordinary gameplay controls and hide Game Over.
     SetGameplayControlsVisible True

End Sub

 

The sequence is important: we first discard the previous game's state, including its messages; we then load the map and create the player and monsters; only once those objects exist do we start the turn engine; and finally, we display the gameplay controls.

 

The existing ShowMainMenu procedure continues to handle returning to the introductory screen. It resets the active game, clears the message history, rebuilds the interface and presents New Game. Because our status display now occupies several lines, it also clears the additional status fields introduced earlier. The Game Over buttons call these existing startup procedures, so we don't need a separate mechanism for restarting after death. This is another benefit of keeping application startup separate from the systems it initialises.

 

Testing our first complete combat system

 

With the implementation in place, we can test the game using the three monsters already present on Old Fort Approach. Compile the VBA project, save the workbook as .xlsm and reopen it with macros enabled, and the main menu should appear automatically. Clicking New Game should load the starting location, create our adventurer and three monsters, initialise the game clock and display the navigation, Options and LOG controls. The player should begin at full health, with turn number zero and game time zero.

 

Move around the map until one of the monsters approaches. When the player attempts to move into the monster's tile, the command should perform an attack instead. The player's coordinates remain unchanged, the monster loses HP and the message panel records the damage. Subsequent monster actions should occur according to their existing schedule.

 

A goblin with speed 100 attacks once per standard 1,000-unit action interval. Our wolf, with speed 200, can attack twice during the same period. The precise sequence depends on when each creature becomes adjacent and which other actions are scheduled, but the relative timing should remain consistent.

 

Verifying damage and monster death

 

Our adventurer deals four damage, while a goblin begins with eight HP. Two successful attacks should therefore be sufficient to kill a full-health goblin. Once its HP reaches zero, its symbol should disappear from the map. The underlying terrain should be restored, and the tile should become available for ordinary movement. The goblin should no longer appear in the active scheduler or perform any further actions.

 

To test deaths more quickly, we can temporarily change the Damage value in tblActorTypes. Giving the player a damage value of 500 makes the next valid attack lethal to any of our existing monsters. After changing the definition, start a new game so that the actor objects are recreated using the new values. This is a convenient advantage of our data-driven design. We can vary gameplay statistics directly in an Excel Table without modifying the combat implementation.

 

Verifying player death

 

We can perform a similar test by temporarily increasing the wolf's damage to 500. Start a new game, move near the wolf and allow it to attack. The player's HP should immediately reach zero, the scheduler should stop and the Game Over display should appear. The ordinary navigation controls should no longer accept actions. The final status should preserve the time of death, and the message panel should contain the fatal attack and death message. Clicking LOG should reveal the retained history, including the final combat events. Returning from the history should bring us back to the same Game Over screen. The player can then choose New Game or Main Menu.

 

Neither option should leave behind old monster instances, stale turn data or duplicate interface controls.

 

Verifying the message history

 

The detailed log can be checked independently of combat. As the adventure progresses, each accepted player action should increase the turn number by one. Messages generated by monsters between two player decisions should share the same player-turn number but retain their individual game-time values. Opening LOG should display the latest retained event at the bottom of the history, with earlier events available by scrolling upwards. The filter controls should allow individual turns and event descriptions to be examined. After more than 100 player turns, the oldest event groups should drop out of the retained history, while all messages belonging to the most recent 100 turns remain available. The compact message panel should continue to display recent events without obscuring the rest of the status information.

 

Once the tests are complete, restore the initial damage values: four for the adventurer, two for goblins and three for the wolf. These values are sufficient for our current demonstration, although we'll revisit combat balance as more creatures, equipment and player abilities are introduced.

 

The playable Milestone 6 workbook

 

Going forward, every completed development milestone will be accompanied by a playable version of the game. The download package for Part 6 consists of the complete macro-enabled .xlsm workbook, a macro-free .xlsx workbook for readers following the build tutorial, and separately exported VBA modules. The VBA exports include our standard modules and the clsActor class, using the appropriate .bas and .cls file formats. This gives readers two ways to explore the project. Those primarily interested in playing can open the macro-enabled workbook and start a game through the main menu, while those interested in VBA development can use the instructional workbook and exported source modules to follow the implementation themselves. We will continue explaining the architecture, data structures and code throughout the series, even though a ready-to-play build is now available. The purpose of the project remains both educational and recreational.

 

Enabling macros safely

 

Because our game is written in VBA, the playable workbook requires macros to run. Excel applies security restrictions to macro-enabled files, particularly those downloaded from the internet. This is appropriate: VBA is capable of interacting with the local computer, and macros in untrusted workbooks can be dangerous. Readers should therefore enable macros only after confirming that the workbook comes from a source they trust.

 

Download the project from the intended website and keep the original archive or files available for reference. The separately provided source modules can be inspected in a text editor, while the VBA contained in the workbook can be examined through the Visual Basic Editor using Alt+F11.

 

On Windows, Excel may block macros in a downloaded workbook even when the file has been opened successfully. If the source has been verified and the reader has decided to trust the file, they can close Excel, right-click the downloaded .xlsm file in File Explorer, select Properties and look for an Unblock option near the bottom of the General tab. If that option is present, selecting it and reopening the workbook may allow Excel to use its normal macro security process. The option isn't displayed for every file, and organisational security policies may still prevent macros from running.

 

Where Excel presents a security warning offering to enable content, readers should proceed only if they've established that the workbook and its code are trustworthy. There is no need to select a global setting that enables all macros in every workbook, nor should Excel's general security protections be disabled to play the game.

 

Once the workbook has been opened with its macros permitted, our Auto_Open procedure displays the main menu automatically. The player can then click New Game and begin exploring Old Fort Approach.

 

 

What we've accomplished

 

Our Excel RPG now has something resembling a complete gameplay cycle. The player can explore the map, encounter moving monsters, attack them and receive damage in return. Creatures act according to the individual schedules established in Part 5, so speed differences affect combat as well as movement. A living actor's HP changes independently of other characters, and reaching zero HP has a defined consequence. Dead monsters disappear from the map, stop taking turns and no longer block movement. Player death terminates the adventure immediately, preserving the final state long enough for the player to examine what happened.

 

We've also significantly improved our interface. The status display now distinguishes health, damage, coordinates, player turns and simulated game time. The compact message panel reports the most recent events, while the detailed history provides a chronological record of the last 100 player turns. The LOG button offers access to that history during gameplay and after death, while Options continues to provide a straightforward way to return to the main menu.

 

Most importantly, these systems remain separated by responsibility. modCombat resolves attacks and damage. modActors manages individual creatures and their behaviour. modTurnEngine controls when actions occur. modMessages records relevant events. modInterface handles the player-facing controls and Game Over display. The terrain engine doesn't need to understand combat, and the combat engine doesn't need to know how an Excel button is created. That modular structure will help us considerably as the game becomes more sophisticated.

 

There are, of course, many mechanics we haven't introduced yet. Our monsters still wander rather than deliberately pursue the player. Attacks always hit, and damage doesn't account for armour, equipment or character attributes. Creature movement remains limited to the terrain permissions we've already implemented, even though the combat engine can target actors on non-walkable tiles. We also have no way to collect treasure from defeated enemies, obtain better equipment or restore health using consumable items.

 

Those are natural next steps.

 

Next: items, inventory and equipment

 

In the next instalment, we'll begin building the item system. Our current adventurer has a fixed damage value and no possessions. Defeating a goblin offers the satisfaction of survival, but no reward beyond clearing the path. We'll change that by introducing reusable item definitions and individual item instances, following a similar approach to the character system developed in Part 4.

 

Items will need to exist on the ground, be collected into an inventory and eventually be equipped or consumed. We'll also need to decide how multiple objects can occupy the same tile. A potion might lie beneath a monster, a dropped sword might share a tile with another item, and the renderer must know which symbol to display. The layered world model we've been developing since Part 1 was designed with exactly these situations in mind.

 

Once we have equipment, we can begin making combat statistics depend on weapons and armour rather than fixed actor definitions. Consumables will also give the player ways to recover from combat, making the game considerably more interesting than a simple contest of who can inflict damage fastest.

 

For now, though, Old Fort Approach is no longer the harmless place it once was. The goblins can fight back, the wolf's speed has become genuinely dangerous, and careless movement can bring an adventure to an abrupt end. Our spreadsheet has acquired a combat system, a functioning game clock, a record of its own events and a permanent consequence for defeat. The world is still small, but it has finally become dangerous.

 

And that seems like a reasonable point at which to start giving our adventurer a sword.

 

This article is Part 6 of the Building an RPG in Excel series. The accompanying project downloads found here include the instructional workbook, exported VBA source modules and a playable macro-enabled workbook containing the completed and tested Milestone 6 implementation.

04 December 2026

Full Service Consulting

Reporting

Automation

Cat On A Spreadsheet

Cat On A Spreadsheet