Cat On A Spreadsheet

Building an RPG in Excel, Part 7: Items, Inventory and Equipment

Our Excel RPG has become a considerably more dangerous place. In the previous instalment, we introduced melee combat, damage, death and a proper Game Over system. Goblins can now fight back, the wolf's superior speed makes it a serious threat, and careless movement can bring an adventure to a sudden end. But there is still something missing from our little world. Our adventurer can defeat a goblin, yet there is nothing to collect afterwards. Every encounter is fought with the same damage statistic, regardless of what the player might be carrying. There are no weapons to discover, no armour to put on, and no potions to drink when health is running low. In other words, we've created danger without providing much opportunity for preparation.

 

Today, we're going to address that by introducing an item system. We'll give our world objects that can lie on the ground, be collected, carried, equipped, consumed and dropped. Weapons will improve melee damage, armour will reduce incoming damage, and healing potions will allow our adventurer to recover from injuries. We'll also build an inventory interface, introduce a carrying limit and connect item interactions to the turn scheduler developed in Part 5. Choosing to drink a potion or change equipment will take time, and the monsters won't politely wait while we do it.

 

The interesting challenge isn't simply drawing a sword symbol on the map or adding a list of possessions to another worksheet. It's designing an item system that can distinguish a type of object from a particular instance of that object. Two short swords might be created from the same definition, but they shouldn't have to remain identical forever. One could eventually be sharpened, damaged or enchanted without changing every other sword in the game. This distinction will become particularly important as we introduce more elaborate equipment, treasure and unique objects. We'll establish the necessary foundation now while keeping the actual item mechanics straightforward.

 

By the end of this instalment, our adventurer will be able to explore Old Fort Approach, find equipment, improve their combat statistics, manage a limited inventory and use healing potions to survive longer.

 

An item type is not an item

 

We encountered a similar problem when introducing monsters in Part 4. A goblin definition describes what a goblin generally looks like and how it behaves, but the two goblins wandering through our starting location must be independent characters. Each has its own position, HP and action schedule - and items require the same distinction. A Short Sword definition might specify a particular symbol, colour and damage bonus. But a sword lying on the ground at (10,8) must be a separate object from an otherwise identical sword in the player's inventory. If we change the first sword's damage modifier, that change must not affect the second one.

 

We'll therefore divide item data into two layers. The shared definitions will live in an Excel Table and describe the default properties of each item type, and individual item objects will be represented by instances of a new VBA class, clsItem. An item instance will receive its initial values from the definition, but it will maintain its own properties and state thereafter.

 

This approach provides considerably more flexibility than storing the player's inventory as a collection of item names or type identifiers. It also lets the same item move between different locations without being recreated. Picking up a sword changes where that particular sword exists; it doesn't destroy a ground item and manufacture a replacement inside the inventory.

 

Creating our item definitions

 

Open the GameData worksheet, where we already maintain our terrain, actor and spawn definitions. We'll add a new structured Excel Table named tblItemTypes. The table uses the following column headings:

TypeID | Name | Category | Glyph | Foreground | Slot | DamageBonus | ArmourReduction | HealHP | Description

 

We'll begin with four item types. The SHORT_SWORD definition is named Short Sword, belongs to the WEAPON category, uses / as its map symbol and has foreground colour #E7D398. Its equipment slot is WEAPON, and its DamageBonus is 2. ArmourReduction and HealHP are zero. Its description reads "A serviceable one-handed sword." The RUSTY_DAGGER is another weapon. It uses ) as its glyph, colour #BEA88E, and has a damage bonus of 1. Its description is "Old, but still sharp enough." The LEATHER_ARMOUR belongs to the ARMOUR category, uses [ with colour #D4AC83, occupies the ARMOUR slot and provides one point of protection. Its description is "Light protection from physical attacks." Finally, HEALING_POTION is a CONSUMABLE. It uses ! with colour #D98AAE, has no equipment slot and restores eight HP. Its description is "Restores up to eight HP." The Slot field for the potion should be genuinely empty, rather than containing the word "None".

 

Select the range containing these definitions, press Ctrl+T, confirm that the first row contains headings, and name the resulting Excel Table tblItemTypes. We're keeping the table relatively small, for the time being. At present, weapons need a damage bonus, armour needs a protection value, and potions need a healing amount. Other fields can be introduced when we add mechanics that actually require them. Eventually, we'll probably separate common item properties from specialised weapon, armour, material and effect definitions. For our current collection, however, one table is sufficient.

 

The important design principle is that these values represent defaults, not the permanent state of every item instance.

 

Placing items in the world

 

We'll also create tblItemSpawns, following the same general pattern as our monster-spawn table. Its column headings are:

MapID | InstanceID | TypeID | X | Y

 

For Old Fort Approach, add the following records:

FORT01 | SWORD01 | SHORT_SWORD | 10 | 8 FORT01 | ARMOUR01 | LEATHER_ARMOUR| 11 | 8 FORT01 | POTION01 | HEALING_POTION| 11 | 8 FORT01 | DAGGER01 | RUSTY_DAGGER | 10 | 9 FORT01 | POTION02 | HEALING_POTION| 12 | 8

 

The sword at (10,8) starts directly beneath the adventurer's initial position. This will give us an immediate opportunity to test collecting an item. At (11,8), we'll place both the leather armour and a healing potion. This introduces an important requirement: a single ground tile must be able to contain more than one item. We can't represent ground items solely as one character stored in a map cell. Instead, the items will exist independently in memory, and our renderer will decide which symbol to display. For now, a single item will use its own glyph while a tile containing several items will display an asterisk to indicate a pile.

 

The last potion begins at (12,8), and the dagger is placed at (10,9). These are convenient starting locations for the original Fort Approach map. As we introduce additional locations, we'll use the same spawn-table structure to place items elsewhere. Each InstanceID must be unique within the active item collection. TypeID, by contrast, may appear repeatedly because several objects can share the same definition.

 

Creating the clsItem class

 

Open the Visual Basic Editor with Alt+F11, insert a new Class Module and name it clsItem. As with clsActor, its Instancing property should be set to 1 - Private. Enter the following code.

Option Explicit

' Identity and shared definition reference.
Public InstanceID As String
Public TypeID As String

' Individual descriptive properties.
Public ItemName As String
Public UniqueName As String
Public Description As String

' Map presentation.
Public Glyph As String
Public GlyphColor As Long

' Classification and equipment.
Public Category As String
Public EquipmentSlot As String

' Statistics copied from the shared definition.
Public BaseDamageBonus As Long
Public BaseArmourReduction As Long
Public HealHP As Long

' Modifiers belonging only to this instance.
Public DamageModifier As Long
Public ArmourModifier As Long

' Current location and lifecycle state.
Public LocationKind As String
Public MapID As String
Public X As Long
Public Y As Long

 

The class deliberately contains properties rather than gameplay procedures. InstanceID and TypeID distinguish the individual object from its shared definition. ItemName, Description, Glyph and GlyphColor describe how that object appears to the player. Category distinguishes weapons, armour and consumables, while EquipmentSlot identifies where an equippable item belongs. The base statistics receive their initial values from tblItemTypes; DamageModifier and ArmourModifier, however, belong to the individual object.

 

Suppose two short swords both begin with BaseDamageBonus = 2. If the first sword later receives DamageModifier = 1, its effective bonus becomes three, while the second sword remains at two. Nothing needs to change in the Excel Table.

 

We've also included UniqueName, allowing an individual item to have a name different from its standard type. This will be useful when we eventually introduce unique weapons and artifacts.

 

The remaining fields describe where an object currently exists. LocationKind will contain one of four values: GROUND, INVENTORY, EQUIPPED or USED. A ground item also needs MapID, X and Y to identify its location. For carried or equipped items, those coordinates are not used to determine where the item appears.

 

A consumed potion enters the USED state. We won't delete its object immediately; the lifecycle remains explicit until the adventure ends.

 

We now have a representation capable of following an individual item from its original spawn location, through inventory and equipment, and eventually back to the ground or into a consumed state.

 

Building the item manager

 

We'll create a standard VBA module named modItems to manage the new class. This module will be responsible for loading definitions, creating instances, finding items, changing their locations and calculating the effects of equipment. We'll keep this functionality out of clsItem itself, because while the item class represents an individual object, the manager handles the collection of objects and their relationship to the active game.

 

Begin the module with the following declarations.

Option Explicit

' Supported item lifecycle states.
Public Const ITEM_GROUND As String = "GROUND"
Public Const ITEM_INVENTORY As String = "INVENTORY"
Public Const ITEM_EQUIPPED As String = "EQUIPPED"
Public Const ITEM_USED As String = "USED"

Public Const MAX_CARRIED_ITEMS As Long = 20

' Active item-session data.
Private mItemDefinitions As Object
Private mItems As Collection
Private mActiveMapID As String

' Positions within each shared definition array.
Private Const DEF_NAME As Long = 0
Private Const DEF_CATEGORY As Long = 1
Private Const DEF_GLYPH As Long = 2
Private Const DEF_COLOUR As Long = 3
Private Const DEF_SLOT As Long = 4
Private Const DEF_DAMAGE As Long = 5
Private Const DEF_ARMOUR As Long = 6
Private Const DEF_HEAL As Long = 7
Private Const DEF_DESCRIPTION As Long = 8

 

We use a dictionary to store shared definitions, with TypeID serving as the lookup key. Individual instances are stored in a collection. This collection represents the items belonging to the current adventure, regardless of whether they're on the ground, carried or equipped.

 

The constants describing lifecycle states keep our code consistent. Without them, small differences in spelling could result in an object becoming inaccessible to the inventory or rendering system. The definition-index constants serve a similar purpose: they allow us to store a relatively compact array for each item type while referring to the array's contents by meaningful names.

 

Resetting and initialising the item session

 

Add these procedures to modItems.

Public Sub ResetItemSession()

     ' Release all item data belonging to the previous run.
     Set mItems = Nothing
     Set mItemDefinitions = Nothing

     mActiveMapID = vbNullString

End Sub

Public Sub InitialiseItemSession(ByVal mapID As String)

     ' Every new adventure receives fresh instances.
     ResetItemSession

     mActiveMapID = UCase$(Trim$(mapID))

     ' Load the shared definitions before creating objects.
     LoadItemDefinitions

     Set mItems = New Collection

     ' Populate the active location with its starting items.
     LoadItemSpawns mActiveMapID

End Sub

 

ResetItemSession discards the objects belonging to the previous run. A new game starts with new item instances rather than retaining equipment or modifications from the preceding adventure. InitialiseItemSession first loads our shared definitions and then creates the instances listed in the spawn table. This follows the same general pattern used by the actor manager.

 

Loading the shared item definitions

 

We'll use ListObject to read tblItemTypes, identifying its columns by name rather than relying on their physical order. The following procedure illustrates the complete loading and validation process.

Private Sub LoadItemDefinitions()

     Dim tbl As ListObject
     Dim data As Variant

     Dim r As Long
     Dim typeID As String
     Dim category As String
     Dim slot As String

     Dim cID As Long
     Dim cName As Long
     Dim cCategory As Long
     Dim cGlyph As Long
     Dim cColour As Long
     Dim cSlot As Long
     Dim cDamage As Long
     Dim cArmour As Long
     Dim cHeal As Long
     Dim cDescription As Long

     Set tbl = GameDataSheet().ListObjects("tblItemTypes")

     If tbl.DataBodyRange Is Nothing Then
          Err.Raise vbObjectError + 601, , _
                 "tblItemTypes is empty."
     End If

     cID = tbl.ListColumns("TypeID").Index
     cName = tbl.ListColumns("Name").Index
     cCategory = tbl.ListColumns("Category").Index
     cGlyph = tbl.ListColumns("Glyph").Index
     cColour = tbl.ListColumns("Foreground").Index
     cSlot = tbl.ListColumns("Slot").Index
     cDamage = tbl.ListColumns("DamageBonus").Index
     cArmour = tbl.ListColumns("ArmourReduction").Index
     cHeal = tbl.ListColumns("HealHP").Index
     cDescription = tbl.ListColumns("Description").Index

     Set mItemDefinitions = CreateObject("Scripting.Dictionary")
     mItemDefinitions.CompareMode = vbTextCompare

     data = tbl.DataBodyRange.Value2

     For r = 1 To UBound(data, 1)

          typeID = UCase$(Trim$(CStr(data(r, cID))))
          category = UCase$(Trim$(CStr(data(r, cCategory))))
          slot = UCase$(Trim$(CStr(data(r, cSlot))))

          If Len(typeID) = 0 Or mItemDefinitions.Exists(typeID) Then
               Err.Raise vbObjectError + 602, , _
                     "Blank or duplicate item type: " & typeID
          End If

          If Len(CStr(data(r, cGlyph))) <> 1 Then
               Err.Raise vbObjectError + 603, , _
                     "Invalid item glyph: " & typeID
          End If

          Select Case category

               Case "WEAPON"
                     If slot <> "WEAPON" Then
                           Err.Raise vbObjectError + 604, , "Invalid weapon slot."
                     End If

               Case "ARMOUR"
                     If slot <> "ARMOUR" Then
                         Err.Raise vbObjectError + 605, , "Invalid armour slot."
                     End If

               Case "CONSUMABLE"
                     If Len(slot) <> 0 Then
                             Err.Raise vbObjectError + 606, , "Invalid consumable slot."
                       End If

               Case Else
                     Err.Raise vbObjectError + 607, , _
                       "Unknown item category: " & category

          End Select

          If CLng(data(r, cDamage)) < 0 Or _
               CLng(data(r, cArmour)) < 0 Or _
               CLng(data(r, cHeal)) < 0 Then

               Err.Raise vbObjectError + 608, , _
                 "Invalid item statistics: " & typeID

          End If

          mItemDefinitions.Add typeID, Array( _
               CStr(data(r, cName)), _
               category, _
               CStr(data(r, cGlyph)), _
               ColorFromHex(CStr(data(r, cColour))), _
               slot, _
               CLng(data(r, cDamage)), _
               CLng(data(r, cArmour)), _
               CLng(data(r, cHeal)), _
               CStr(data(r, cDescription)))

     Next r

End Sub

 

The procedure retrieves every table field by its column name, making the definition sheet less sensitive to future rearrangement. It also validates the item identifiers, glyphs, categories, equipment slots and numeric values before storing the definitions. We use the existing ColorFromHex helper from our earlier actor work to convert the hexadecimal foreground values into colours that Excel can use. At the end of the procedure, mItemDefinitions contains a separate definition array for every item type, indexed by its unique TypeID.

 

Constructing individual items

 

Now add CreateItem, which translates a shared definition into a distinct clsItem instance.

Private Function CreateItem( _
     ByVal instanceID As String, _
     ByVal typeID As String) As clsItem

     Dim item As clsItem
     Dim definition As Variant

     typeID = UCase$(Trim$(typeID))

     If Not mItemDefinitions.Exists(typeID) Then
          Err.Raise vbObjectError + 609, , _
                 "Unknown item type: " & typeID
     End If

     definition = mItemDefinitions(typeID)

     Set item = New clsItem

     ' Each item receives independent copies of its defaults.
     With item

          .InstanceID = UCase$(Trim$(instanceID))
          .TypeID = typeID

          .ItemName = CStr(definition(DEF_NAME))
          .Category = CStr(definition(DEF_CATEGORY))

          .Glyph = CStr(definition(DEF_GLYPH))
          .GlyphColor = CLng(definition(DEF_COLOUR))

          .EquipmentSlot = CStr(definition(DEF_SLOT))

          .BaseDamageBonus = CLng(definition(DEF_DAMAGE))
          .BaseArmourReduction = CLng(definition(DEF_ARMOUR))
          .HealHP = CLng(definition(DEF_HEAL))

          .Description = CStr(definition(DEF_DESCRIPTION))

          ' Instance-specific modifiers initially equal zero.
          .DamageModifier = 0
          .ArmourModifier = 0

     End With

     Set CreateItem = item

End Function

 

This is the point where a shared definition becomes an actual object. A newly created short sword starts with the normal damage bonus of two, but its properties belong to that individual clsItem. The definition remains unchanged and can be used to construct as many additional swords as we need.

 

Reading item spawn positions

 

The following procedure reads tblItemSpawns and creates the items belonging to the requested map.

Private Sub LoadItemSpawns(ByVal mapID As String)

     Dim tbl As ListObject
     Dim data As Variant

     Dim item As clsItem
     Dim existing As clsItem

     Dim r As Long
     Dim instanceID As String
     Dim x As Long
     Dim y As Long

     Dim cMap As Long
     Dim cID As Long
     Dim cType As Long
     Dim cX As Long
     Dim cY As Long

     Set tbl = GameDataSheet().ListObjects("tblItemSpawns")

     If tbl.DataBodyRange Is Nothing Then Exit Sub

     cMap = tbl.ListColumns("MapID").Index
     cID = tbl.ListColumns("InstanceID").Index
     cType = tbl.ListColumns("TypeID").Index
     cX = tbl.ListColumns("X").Index
     cY = tbl.ListColumns("Y").Index

     data = tbl.DataBodyRange.Value2

     For r = 1 To UBound(data, 1)

          If StrComp(CStr(data(r, cMap)), mapID, _
               vbTextCompare) = 0 Then

               instanceID = UCase$(Trim$(CStr(data(r, cID))))

               If Len(instanceID) = 0 Then
                     Err.Raise vbObjectError + 610, , "Blank item InstanceID."
               End If

               Set existing = GetItemByInstanceID(instanceID)

               If Not existing Is Nothing Then
                     Err.Raise vbObjectError + 611, , _
                           "Duplicate item InstanceID: " & instanceID
               End If

               x = CLng(data(r, cX))
               y = CLng(data(r, cY))

               ' Starting items must occupy accessible tiles.
               If Not IsTileWalkable(x, y) Then
                     Err.Raise vbObjectError + 612, , _
                           "Invalid item spawn: " & instanceID
               End If

               Set item = CreateItem( _
                     instanceID, CStr(data(r, cType)))

               With item

                     .LocationKind = ITEM_GROUND
                     .MapID = mapID
                     .X = x
                     .Y = y

               End With

               mItems.Add item

          End If

     Next r

End Sub

 

Each matching row creates an independent object and assigns its initial ground location. Our starter items are restricted to walkable spawn tiles so the player can reach them using the movement system we currently have. Multiple items may share those coordinates, however; we don't impose an item-occupancy restriction. This is different from actor movement; two living monsters cannot occupy the same tile, but several objects may form a pile.

 

The completed item manager now has two very different kinds of information in memory: a dictionary describing item types and a collection holding the individual objects created from those types.

 

Finding and identifying individual items

 

Other systems need to find objects without knowing how the internal collection is organised. We'll expose a small set of helper functions from modItems.

Public Function CurrentItemMapID() As String

     CurrentItemMapID = mActiveMapID

End Function

Public Function ItemInstances() As Collection

     Set ItemInstances = mItems

End Function

Public Function GetItemByInstanceID( _
     ByVal instanceID As String) As clsItem

     Dim item As clsItem

     If mItems Is Nothing Then Exit Function

     For Each item In mItems

          If StrComp(item.InstanceID, instanceID, _
               vbTextCompare) = 0 Then

               Set GetItemByInstanceID = item
               Exit Function

          End If

     Next item

End Function

 

ItemInstances exposes the active collection for iteration, while GetItemByInstanceID returns a particular object. The latter will become especially useful in our inventory interface. A worksheet row can contain an instance identifier, and the interface can use it to retrieve precisely the item the player selected.

 

We also need a way to display item names and statistics.

Public Function ItemDisplayName(ByVal item As clsItem) As String

     Dim result As String

     If Len(item.UniqueName) > 0 Then
          result = item.UniqueName
     Else
          result = item.ItemName
     End If

     If item.DamageModifier > 0 Then
          result = result & " (+" & item.DamageModifier & ")"
     ElseIf item.DamageModifier < 0 Then
          result = result & " (" & item.DamageModifier & ")"
     End If

     ItemDisplayName = result

End Function

Public Function ItemEffectSummary(ByVal item As clsItem) As String

     Select Case item.Category

          Case "WEAPON"
               ItemEffectSummary = "+" & _
                     (item.BaseDamageBonus + item.DamageModifier) & " damage"

          Case "ARMOUR"
               ItemEffectSummary = "Protection " & _
                     (item.BaseArmourReduction + item.ArmourModifier)

          Case "CONSUMABLE"
               ItemEffectSummary = "Restores " & item.HealHP & " HP"

     End Select

End Function

 

The display name may differ from the standard item type name. A modified sword can display an additional (+1) suffix, and an individually named item can use UniqueName instead of its original definition name. The effect summary provides a concise description appropriate to the item's category. We'll use these strings in the inventory listing.

 

The important point is that neither function changes the object. They interpret its current individual state for presentation.

 

Drawing ground items without changing the map

 

We can now turn our attention to rendering. Since Part 1, our map has contained terrain independently of the symbols displayed on the worksheet. Later milestones introduced actors that are drawn over that terrain. Now, items will form another layer between terrain and actors.

 

When a sword lies on an empty floor tile, the sword's glyph should be visible. When the adventurer steps onto that tile, the player's @ symbol takes priority and, when the adventurer moves away again, the sword should reappear. We'll implement this without changing the terrain array.

 

First, add a function to count items occupying a particular tile.

Public Function GroundItemCountAt( _
     ByVal x As Long, _
     ByVal y As Long) As Long

     Dim item As clsItem

     If mItems Is Nothing Then Exit Function

     For Each item In mItems

          If item.LocationKind = ITEM_GROUND And _
               item.MapID = mActiveMapID Then

               If item.X = x And item.Y = y Then
                     GroundItemCountAt = GroundItemCountAt + 1
               End If

          End If

     Next item

End Function

 

The function examines the active item collection and counts only objects in the GROUND state belonging to the active map. Carried, equipped and consumed items don't contribute to ground piles.

 

Now add the rendering procedures.

Public Sub DrawGroundItemAt( _
     ByVal x As Long, _
     ByVal y As Long)

     Dim item As clsItem
     Dim candidate As clsItem

     Dim itemCount As Long
     Dim displayCell As Range

     If mItems Is Nothing Then Exit Sub

     For Each item In mItems

          If item.LocationKind = ITEM_GROUND And _
               item.MapID = mActiveMapID Then

               If item.X = x And item.Y = y Then

                   itemCount = itemCount + 1
                 Set candidate = item

               End If

          End If

     Next item

     If itemCount = 0 Then Exit Sub

     Set displayCell = GetScreenCell(x, y)

     With displayCell

          If itemCount = 1 Then

               .Value2 = candidate.Glyph
               .Font.Color = candidate.GlyphColor

          Else

               .Value2 = "*"
               .Font.Color = RGB(247, 205, 108)

          End If

          .Font.Bold = True

     End With

End Sub

Public Sub DrawAllGroundItems()

     Dim item As clsItem

     If mItems Is Nothing Then Exit Sub

     For Each item In mItems

          If item.LocationKind = ITEM_GROUND And _
               item.MapID = mActiveMapID Then

               DrawGroundItemAt item.X, item.Y

          End If

     Next item

End Sub

 

DrawGroundItemAt draws a single item using its own glyph and colour and, if several objects occupy the same tile, it displays a yellow asterisk. We don't lose access to the individual objects when they form a pile. They remain separate instances with their own identifiers and properties.

 

DrawAllGroundItems provides a convenient way to draw every item after the map has been loaded.

 

Integrating items into RedrawWorldTile

 

Open modActors and replace its existing RedrawWorldTile procedure with the following version.

Public Sub RedrawWorldTile( _
     ByVal x As Long, _
     ByVal y As Long)

     Dim monster As clsActor
     Dim player As clsActor

     ' Restore the underlying terrain.
     RedrawTerrainTile x, y

     ' Ground items appear over terrain.
     DrawGroundItemAt x, y

     ' Living monsters appear over ground items.
     Set monster = MonsterAt(x, y)

     If Not monster Is Nothing Then
          DrawActor monster
     End If

     ' The living player takes highest display priority.
     Set player = PlayerActor()

     If Not player Is Nothing Then

          If player.HP > 0 Then

               If player.X = x And player.Y = y Then
                     DrawActor player
               End If
          End If
     End If

End Sub

 

The sequence is what matters. Terrain is drawn first, followed by ground items, living monsters and finally the player. This creates a consistent display priority while preserving the underlying world state.

 

We've already arranged for actors to be rendered over items when a new game begins. We'll connect the full drawing sequence to startup shortly.

 

Telling the player what lies beneath their feet

 

There is one subtle consequence of rendering the player above ground items: objects beneath the @ symbol are no longer visible. That is correct for display priority, but we don't want the player to overlook items simply because they are standing on them, so we will therefore extend the message system to announce objects whenever the adventurer enters an occupied ground tile. For a single item, the message might read "A short sword lies here." If several items share the tile, we'll display "A pile of items lies here."

 

Add this function to modItems.

Public Function GroundItemMessageAt( _
     ByVal x As Long, _
     ByVal y As Long) As String

     Dim item As clsItem
     Dim itemCount As Long
     Dim itemName As String
     Dim article As String

     itemCount = GroundItemCountAt(x, y)

     If itemCount = 0 Then Exit Function

     If itemCount > 1 Then
          GroundItemMessageAt = "A pile of items lies here."
          Exit Function
     End If

     For Each item In mItems

          If item.LocationKind = ITEM_GROUND And _
               item.MapID = mActiveMapID And _
               item.X = x And item.Y = y Then

               itemName = LCase$(ItemDisplayName(item))
               article = "A"

               Select Case UCase$(Left$(itemName, 1))
                     Case "A", "E", "I", "O", "U"
                           article = "An"
               End Select

               GroundItemMessageAt = article & " " & _
                     itemName & " lies here."

               Exit Function

          End If

     Next item

End Function

 

The message generator uses a simple article-selection rule based on the first letter of the item name. There will be errors; "leather armour" for example is a mass noun, so it should not be preceded by an article, but we are not attempting to create a comprehensive English grammar system here. The purpose is to generate useful, readable descriptions for our small initial item catalogue.

 

Now open modPlayer and find the end of MovePlayer, after the player's coordinates and visible tiles have been updated. Replace the final messaging and scheduling lines with:

' Report the terrain entered.
LogGameMessage GetTerrainMessage(newX, newY, False)

' Announce any ground item or pile at the destination.
LogGameMessage GroundItemMessageAt(newX, newY)

' Advance game time and execute scheduled monster actions.
CompletePlayerAction STANDARD_ACTION_COST

 

LogGameMessage already ignores empty messages, so an empty floor tile won't generate an unnecessary notification. We will also call GroundItemMessageAt when a new game begins, allowing the sword beneath the player's starting position to be announced immediately.

 

Giving the player an inventory

 

Ground objects are only useful if the adventurer can do something with them, so we will introduce an inventory capacity of 20 individual items. At this stage, we're not using item weights or combining identical consumables into quantity stacks. Two potions are two independent item objects, even when they share the same type.

 

Equipped equipment continues to count towards the carrying limit. A sword doesn't cease to be something the player owns merely because it is currently in their hand.

 

Add these functions to modItems.

Public Function PlayerCarryCount() As Long

     Dim item As clsItem

     If mItems Is Nothing Then Exit Function

     For Each item In mItems

          If item.LocationKind = ITEM_INVENTORY Or _
               item.LocationKind = ITEM_EQUIPPED Then

               PlayerCarryCount = PlayerCarryCount + 1

          End If

     Next item

End Function

Public Function GetEquippedItem( _
     ByVal requestedSlot As String) As clsItem

     Dim item As clsItem

     If mItems Is Nothing Then Exit Function

     For Each item In mItems

          If item.LocationKind = ITEM_EQUIPPED Then

               If StrComp(item.EquipmentSlot, requestedSlot, _
                     vbTextCompare) = 0 Then

                     Set GetEquippedItem = item
                     Exit Function

               End If
          End If

     Next item

End Function

 

PlayerCarryCount counts every carried or equipped item instance. GetEquippedItem retrieves the object currently occupying a particular equipment slot. For now, our two supported slots are WEAPON and ARMOUR. Because each item carries its own state, changing equipment doesn't require copying statistics into the player's actor object. Instead, other systems can ask which item is currently equipped and calculate the resulting effect.

 

That brings us to the most immediately useful consequence of introducing equipment: combat statistics can finally change.

 

Equipment and effective combat statistics

 

The player already has a Damage property inherited from their actor definition. Until now, that number has represented the damage inflicted by every attack. We'll keep it as the starting value, but introduce a function that calculates the player's effective melee damage based on their current equipment. For Milestone 7, our rule is deliberately simple: an equipped weapon adds a fixed bonus to the actor's existing damage. Our adventurer begins with damage 4. A Short Sword adds 2, producing an effective damage value of 6. The Rusty Dagger adds 1, producing damage 5. We'll introduce more sophisticated weapon calculations later, but the immediate objective is to make combat respond dynamically to equipment changes.

 

Add the following functions to modItems.

Public Function EffectiveMeleeDamage( _
     ByVal actor As clsActor) As Long

     Dim weapon As clsItem

     If actor Is Nothing Then Exit Function

     ' Begin with the actor's own damage statistic.
     EffectiveMeleeDamage = actor.Damage

     ' Only the player uses equipment in this milestone.
     If actor Is PlayerActor() Then

          Set weapon = GetEquippedItem("WEAPON")

          If Not weapon Is Nothing Then

               EffectiveMeleeDamage = EffectiveMeleeDamage + _
                   weapon.BaseDamageBonus + weapon.DamageModifier

          End If

     End If

     If EffectiveMeleeDamage < 0 Then
          EffectiveMeleeDamage = 0
     End If

End Function

Public Function EffectiveArmourReduction( _
     ByVal actor As clsActor) As Long

     Dim armour As clsItem

     If actor Is Nothing Then Exit Function

     If actor Is PlayerActor() Then

          Set armour = GetEquippedItem("ARMOUR")

          If Not armour Is Nothing Then

               EffectiveArmourReduction = _
                     armour.BaseArmourReduction + armour.ArmourModifier

          End If

     End If

     If EffectiveArmourReduction < 0 Then
          EffectiveArmourReduction = 0
     End If

End Function

 

Both functions accept an actor object, rather than assuming they always operate on the player. At present, only the player has an inventory and can equip items, so monsters continue using their existing damage values. However, other modules don't need to know those details. They can call EffectiveMeleeDamage or EffectiveArmourReduction and receive the appropriate result. This is particularly valuable for the combat system.

 

Connecting equipment to modCombat

 

Open modCombat and locate ResolveMeleeAttack, which we introduced in Part 6. Add two local variables, rawDamage and protection, both declared as Long, then replace its existing damage calculation with:

' Determine the attacker's effective damage.
rawDamage = EffectiveMeleeDamage(attacker)

' Determine the defender's equipment protection.
protection = EffectiveArmourReduction(defender)

' Calculate the full damage delivered by the attack.
damageDone = rawDamage - protection

' Protection cannot turn an attack into negative damage.
If damageDone < 0 Then
     damageDone = 0
End If

' Apply the full amount, including damage beyond zero HP.
defender.HP = defender.HP - damageDone

 

Keep the remainder of ResolveMeleeAttack, including its attack messages and death-handling logic. This calculation means that a goblin dealing two damage against an adventurer wearing Leather Armour will cause one damage and a wolf dealing three damage will cause two. If protection completely absorbs an attack, the result is zero damage.

 

A change to the previous milestones comes in the form of removing the damage cap based on the defender's remaining HP. A 500-damage attack against a creature with 1 HP remaining still deals and reports 500 damage, leaving the creature with negative HP. Our combat and actor systems already identify death using HP <= 0, so that behaviour is compatible with the existing game. Keeping the actual damage value will also leave open the possibility of tracking overkill in a future combat milestone.

 

The important architectural improvement is that the combat resolver no longer needs to know which particular sword or armour the player is wearing. It asks for effective attack and protection values, then applies the result. When the player changes equipment, the next attack automatically uses the updated statistics.

 

We should make that change visible in the status panel too. In modPlayer, update the damage portion of UpdatePlayerStatus so that it uses EffectiveMeleeDamage(player) rather than the player's fixed Damage property. The first status line will therefore use:

ws.Range(STATUS_CELL_ADDRESS).Value2 = _
     "HP " & player.HP & "/" & player.MaxHP & _
     " Dmg " & EffectiveMeleeDamage(player)

 

The other status lines for position, turn number and game time remain unchanged.

 

Validating item actions before changing the world

 

We now have objects, ground locations, inventory capacity and equipment calculations. The next step is letting the player interact with the items. Our inventory will support picking up, dropping, equipping, unequipping and using items.

 

Not every action is valid for every item. A healing potion cannot be equipped as a weapon and a sword lying on the ground cannot be unequipped. A full inventory should prevent further pickups, and trying to drink a potion at full health should not waste the potion. These rules belong in the item manager, not in the interface.

 

We'll implement a function named ItemActionAllowed, which checks the requested operation and returns an explanatory message when it cannot be performed. This also gives us a convenient way to ensure that invalid commands don't consume game time.

Public Function ItemActionAllowed( _
     ByVal item As clsItem, _
     ByVal actionName As String, _
     ByRef reason As String) As Boolean

     Dim player As clsActor

     reason = vbNullString

     If item Is Nothing Then
          reason = "Select an item first."
          Exit Function
     End If

     Set player = PlayerActor()

     If player Is Nothing Then
          reason = "There is no active player."
          Exit Function
     End If

     Select Case UCase$(actionName)

          Case "PICKUP"

               If item.LocationKind <> ITEM_GROUND Or _
                     item.MapID <> mActiveMapID Then

                     reason = "This item is not on the ground."

               ElseIf item.X <> player.X Or item.Y <> player.Y Then

                     reason = "Stand on the item to pick it up."

               ElseIf PlayerCarryCount() >= MAX_CARRIED_ITEMS Then

                     reason = "Your inventory is full."

               Else
                     ItemActionAllowed = True
               End If

          Case "DROP"

               If item.LocationKind = ITEM_INVENTORY Then
                     ItemActionAllowed = True
               Else
                     reason = "Unequip the item before dropping it."
               End If

          Case "EQUIP"

               If item.LocationKind <> ITEM_INVENTORY Then
                     reason = "Only carried items can be equipped."

               ElseIf Len(item.EquipmentSlot) = 0 Then
                     reason = "This item cannot be equipped."

               Else
                     ItemActionAllowed = True
               End If

          Case "UNEQUIP"

               If item.LocationKind = ITEM_EQUIPPED Then
                     ItemActionAllowed = True
               Else
                     reason = "This item is not equipped."
               End If

          Case "USE"

               If item.LocationKind <> ITEM_INVENTORY Or _
                     item.Category <> "CONSUMABLE" Then

                     reason = "This is not a carried consumable."

               ElseIf item.HealHP <= 0 Then

                     reason = "This item has no healing effect."

               ElseIf player.HP >= player.MaxHP Then

                     reason = "Your health is already full."

               Else
                     ItemActionAllowed = True
               End If

          Case Else
               reason = "Unknown item action."

     End Select

End Function

 

We now have a single place where the rules governing item interactions are defined. For example, picking up an item requires that the object be lying on the player's current tile and that the carrying limit hasn't been reached; equipping requires an item in the inventory with a valid equipment slot; drinking a healing potion requires that the player is injured and that the selected object is a carried consumable. The validation function doesn't change the item, alter HP or advance time, it only determines whether the requested action is permitted, and that allows the interface to reject invalid commands without invoking the turn scheduler.

 

Performing item actions

 

Once an action has been validated, we need to apply it. We'll add PerformItemAction to modItems.

Public Function PerformItemAction( _
     ByVal item As clsItem, _
     ByVal actionName As String) As String

     Dim player As clsActor
     Dim previousItem As clsItem

     Dim healDone As Long
     Dim reason As String

     ' Validate the operation before changing item state.
     If Not ItemActionAllowed(item, actionName, reason) Then
          Err.Raise vbObjectError + 613, , reason
     End If

     Set player = PlayerActor()

     Select Case UCase$(actionName)

          Case "PICKUP"

               item.LocationKind = ITEM_INVENTORY

               RedrawWorldTile item.X, item.Y

               PerformItemAction = "You pick up the " & _
                     LCase$(ItemDisplayName(item)) & "."

          Case "DROP"

               item.LocationKind = ITEM_GROUND
               item.MapID = mActiveMapID

               item.X = player.X
               item.Y = player.Y

               RedrawWorldTile item.X, item.Y

               PerformItemAction = "You drop the " & _
                     LCase$(ItemDisplayName(item)) & "."

          Case "EQUIP"

               ' Return any existing equipment to inventory.
               Set previousItem = GetEquippedItem(item.EquipmentSlot)

               If Not previousItem Is Nothing Then
                     previousItem.LocationKind = ITEM_INVENTORY
               End If

               item.LocationKind = ITEM_EQUIPPED

               PerformItemAction = "You equip the " & _
                     LCase$(ItemDisplayName(item)) & "."

          Case "UNEQUIP"

               item.LocationKind = ITEM_INVENTORY

               PerformItemAction = "You unequip the " & _
                     LCase$(ItemDisplayName(item)) & "."

          Case "USE"

               healDone = item.HealHP

               ' Healing stops at the actor's maximum HP.
               If healDone > player.MaxHP - player.HP Then
                     healDone = player.MaxHP - player.HP
               End If

               player.HP = player.HP + healDone

               ' The consumed object is no longer carried.
               item.LocationKind = ITEM_USED

               PerformItemAction = "You drink the " & _
                     LCase$(ItemDisplayName(item)) & _
                   " and recover " & healDone & " HP."

     End Select

End Function

 

Most of these actions are changes to the item's location state. Picking up an object changes LocationKind from GROUND to INVENTORY, and then we redraw its old tile, revealing whatever remains there. Dropping does the reverse: the item becomes a ground object at the player's current coordinates, and the tile is redrawn. Equipping an item changes its state to EQUIPPED; if another item already occupies the corresponding slot, that item is returned to the inventory automatically. The previous weapon isn't destroyed or dropped; it remains a separate object, ready to be equipped again later. Unequipping is similarly straightforward: the object moves from EQUIPPED back to INVENTORY.

 

The potion is slightly different because it changes the player's state. We calculate how much health can actually be restored, ensuring that the result never exceeds MaxHP, then we increase the player's current HP and mark the potion as USED.

 

Every successful operation returns a description suitable for our message system.

 

Notice that this procedure doesn't advance the turn scheduler - it only changes item and character state. The inventory interface will decide when to begin a timed action, call PerformItemAction and then advance the game clock. This maintains the same separation between an action and its scheduling that we've used for movement and combat.

 

Testing instance-specific modifications

 

Before moving on to the interface, we'll add one small development helper that demonstrates the distinction between item types and item instances. Add this procedure to modItems.

Public Sub DebugSetItemDamageModifier( _
     ByVal instanceID As String, _
     ByVal modifier As Long)

     Dim item As clsItem

     Set item = GetItemByInstanceID(instanceID)

     If item Is Nothing Then
          Err.Raise vbObjectError + 614, , _
                 "Unknown item instance: " & instanceID
     End If

     ' Modify only the selected object.
     item.DamageModifier = modifier

End Sub

 

Once the game is running, we can execute the following command from the VBA Immediate Window:

DebugSetItemDamageModifier "SWORD01", 1

 

The sword identified as SWORD01 now has an individual damage modifier of +1 and, since the shared Short Sword definition already provides +2, the sword's effective bonus becomes +3. If the adventurer equips it, their current damage increases from four to seven. Another Short Sword instance would still have its original +2 bonus, because its modifier is stored in a different object.

 

This demonstrates the foundation we'll later use for sharpening, enchantments and individual weapon properties. For now, we're changing the value directly for testing rather than introducing a separate sharpening action.

 

Building the Inventory worksheet

 

We now need a way for the player to interact with the item system. We'll build a dedicated Inventory worksheet, created automatically when the player opens it. The interface will contain two item lists: carried and equipped items will appear on the left, while items lying on the player's current tile will appear on the right. It will also display the equipped weapon and armour, current carrying capacity, effective damage and protection. The player will select an item by clicking its row, then choose an action from a set of buttons.

 

We're using the worksheet as an interface rather than as the authoritative inventory store. The actual items continue to live in mItems, and the worksheet simply displays their current state. This means switching between worksheets doesn't require transferring item ownership between tables or reconstructing objects.

 

Creating modInventoryUI

 

Insert a new standard VBA module named modInventoryUI. Begin by defining the interface state and the procedures responsible for opening and closing it.

Option Explicit

' True while the dedicated Inventory worksheet is active.
Private mInventoryOpen As Boolean

Public Function IsInventoryOpen() As Boolean

     IsInventoryOpen = mInventoryOpen

End Function

Public Function InventorySheet() As Worksheet

     On Error Resume Next
     Set InventorySheet = ThisWorkbook.Worksheets(SHEET_INVENTORY)
     On Error GoTo 0

End Function

Private Function EnsureInventorySheet() As Worksheet

     Dim ws As Worksheet

     Set ws = InventorySheet()

     If ws Is Nothing Then
          Set ws = ThisWorkbook.Worksheets.Add(After:=GameScreen())
          ws.Name = SHEET_INVENTORY
     End If

     Set EnsureInventorySheet = ws

End Function

Public Sub ShowInventory()

     Dim ws As Worksheet

     ' Open only when the game is waiting for the player.
     If Not CanPlayerAct() Then Exit Sub

     Set ws = EnsureInventorySheet()

     mInventoryOpen = True
     ws.Visible = xlSheetVisible

     RefreshInventoryScreen

     ws.Activate
     ws.Range("A1").Select

End Sub

Public Sub CloseInventory()

     Dim ws As Worksheet

     If Not mInventoryOpen Then Exit Sub

     mInventoryOpen = False

     Set ws = InventorySheet()

     GameScreen().Activate

     If Not ws Is Nothing Then
          ws.Visible = xlSheetVeryHidden
     End If

End Sub

Public Sub ResetInventoryInterface()

     Dim ws As Worksheet

     mInventoryOpen = False

     Set ws = InventorySheet()

     If ws Is Nothing Then Exit Sub

     GameScreen().Activate
     ws.Visible = xlSheetVeryHidden

End Sub

 

The Inventory worksheet is created only when first needed, and hidden again when the player returns to the game. We use xlSheetVeryHidden, just as we do for the detailed message history, to keep auxiliary game worksheets out of the normal workbook interface.

 

ResetInventoryInterface closes the viewer without attempting to preserve a selected item or partially completed interaction. We'll call it when starting or ending an adventure. Opening and closing Inventory won't consume game time - that distinction matters because examining possessions is not itself a timed action, while actually manipulating them will be.

 

Reusable buttons

 

We can create Inventory buttons using the same general technique introduced for our main game screen. Add a private helper named GetOrCreateInventoryButton to modInventoryUI.

Private Function GetOrCreateInventoryButton( _
     ByVal ws As Worksheet, _
     ByVal shapeName As String, _
     ByVal caption As String, _
     ByVal macroName As String, _
     ByVal x As Double, _
     ByVal y As Double, _
     ByVal buttonWidth As Double) As Shape

     Dim btn As Shape

     On Error Resume Next
     Set btn = ws.Shapes(shapeName)
     On Error GoTo 0

     If btn Is Nothing Then

          Set btn = ws.Shapes.AddShape( _
               msoShapeRoundedRectangle, _
               x, y, buttonWidth, 28)

          btn.Name = shapeName

     End If

     With btn

          .Left = x
          .Top = y
          .Width = buttonWidth
          .Height = 28

          .Placement = xlFreeFloating

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

          With .TextFrame

               .Characters.Text = caption
               .HorizontalAlignment = xlHAlignCenter
               .VerticalAlignment = xlVAlignCenter

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

          End With

          .OnAction = "'" & _
               Replace(ThisWorkbook.Name, "'", "''") & _
               "'!" & macroName

     End With

     Set GetOrCreateInventoryButton = btn

End Function

 

This helper finds an existing named shape or creates it when necessary, then it positions, formats and binds the shape to the requested public macro. That lets us refresh the Inventory worksheet repeatedly without accumulating duplicate buttons.

 

Populating the item lists

 

The main RefreshInventoryScreen procedure handles the worksheet's layout. It clears the displayed cell contents without deleting the shapes, writes the current equipment and carrying information, and iterates through the active item collection. Carried and equipped items are displayed in columns A through E, beginning at row 8, and ground items located at the player's current coordinates are displayed in columns H through L.

 

The identifier column is particularly important. Even when two items have identical displayed names, their InstanceID values distinguish them.

 

The following is the central part of the list-population logic.

carriedRow = 8
groundRow = 8

Set items = ItemInstances()

If Not items Is Nothing Then

     For Each item In items

          If item.LocationKind = ITEM_INVENTORY Or _
               item.LocationKind = ITEM_EQUIPPED Then

               ws.Cells(carriedRow, 1).Value2 = ItemDisplayName(item)
               ws.Cells(carriedRow, 2).Value2 = item.Category

               If item.LocationKind = ITEM_EQUIPPED Then
                     ws.Cells(carriedRow, 3).Value2 = "Equipped: " & item.EquipmentSlot
               Else
                     ws.Cells(carriedRow, 3).Value2 = "Carried"
               End If

               ws.Cells(carriedRow, 4).Value2 = ItemEffectSummary(item)
               ws.Cells(carriedRow, 5).Value2 = item.InstanceID

               carriedRow = carriedRow + 1

          ElseIf item.LocationKind = ITEM_GROUND Then

               If item.MapID = CurrentItemMapID() Then

                     If item.X = player.X And item.Y = player.Y Then

                           ws.Cells(groundRow, 8).Value2 = ItemDisplayName(item)
                           ws.Cells(groundRow, 9).Value2 = item.Category
                            ws.Cells(groundRow, 10).Value2 = "Ground"
                           ws.Cells(groundRow, 11).Value2 = ItemEffectSummary(item)
                         ws.Cells(groundRow, 12).Value2 = item.InstanceID

                             groundRow = groundRow + 1

                   End If
               End If

          End If

     Next item

End If

 

The remaining part of RefreshInventoryScreen formats the worksheet and creates the controls. The title appears at A1, weapon and armour details occupy row 3, with carrying capacity and effective combat statistics in row 4. The list headings occupy row 7. We use row 2 for the action buttons, increasing its height to 44 points so that the 28-point shapes fit comfortably without overlapping the equipment information. The button row is centred vertically with:

ws.Rows(2).RowHeight = 44

buttonTop = ws.Range("A2").Top + _
     (ws.Rows(2).Height - 28) / 2

buttonLeft = ws.Range("A2").Left

 

The six actions are Pick Up, Drop, Equip, Unequip, Use and Inspect. A separate Back to Game button uses the same vertical alignment. We can create them from parallel arrays of captions, macro names and shape names.

labels = Array( _
     "PICK UP", "DROP", "EQUIP", _
     "UNEQUIP", "USE", "INSPECT")

macros = Array( _
     "InventoryPickup", "InventoryDrop", _
     "InventoryEquip", "InventoryUnequip", _
     "InventoryUse", "InventoryInspect")

names = Array( _
     "btnInvPickup", "btnInvDrop", _
     "btnInvEquip", "btnInvUnequip", _
     "btnInvUse", "btnInvInspect")

For n = LBound(labels) To UBound(labels)

     Set actionButton = GetOrCreateInventoryButton( _
          ws, CStr(names(n)), CStr(labels(n)), _
          CStr(macros(n)), _
          buttonLeft + n * 112, buttonTop, 105)

Next n

Set actionButton = GetOrCreateInventoryButton( _
     ws, "btnInvBack", "BACK TO GAME", _
     "CloseInventory", ws.Range("K2").Left, _
     buttonTop, 145)

 

As with the main game interface, this is a data-driven way to create a collection of buttons without writing separate shape-generation code for every action. The shapes remain in place when the worksheet is refreshed; only their captions, dimensions and assignments are updated as necessary.

 

Selecting an individual item

 

The Inventory worksheet already displays each object's InstanceID, so we'll use that value to identify the selected item. When the player clicks a cell in one of the item rows, the interface examines the active row and determines whether the selection belongs to the carried-items list or the ground-items list.

 

Add this function to modInventoryUI.

Private Function SelectedItem() As clsItem

     Dim ws As Worksheet
     Dim rowNumber As Long
     Dim columnNumber As Long
     Dim instanceID As String

     Set ws = InventorySheet()

     If ws Is Nothing Then Exit Function
     If Not (ActiveSheet Is ws) Then Exit Function

     rowNumber = ActiveCell.Row
     columnNumber = ActiveCell.Column

     If rowNumber < 8 Then Exit Function

     Select Case columnNumber

          Case 1 To 5
               instanceID = Trim$(CStr(ws.Cells(rowNumber, 5).Value2))

          Case 8 To 12
               instanceID = Trim$(CStr(ws.Cells(rowNumber, 12).Value2))

          Case Else
               Exit Function

     End Select

     If Len(instanceID) = 0 Then Exit Function

     Set SelectedItem = GetItemByInstanceID(instanceID)

End Function

 

This eliminates the need for a separate Select button beside every item. It also means that item names don't have to be unique. Two Healing Potions can share the same displayed name without becoming indistinguishable to the game. The worksheet may display an item, but the real object remains in mItems. We always retrieve that object before taking an action.

 

Making inventory actions part of the game clock

 

We now have an item interface and a way to identify the selected object. The next challenge is integrating inventory interactions with our turn engine.

 

In Part 5, we created a scheduler that waits for the player to submit an action, processes that action and then advances through the intervening monster events. Opening a menu isn't inherently a timed action. A player should be able to inspect their possessions without losing turns but picking up a sword, equipping armour or drinking a potion takes time.

 

For Milestone 7, we'll use the standard action cost of 1,000 for picking up, dropping, equipping, unequipping and consuming items. The same speed-based delay calculations used for movement and melee combat will apply, which means the player cannot drink a healing potion without giving nearby monsters an opportunity to act.

 

Allowing actions from the Inventory worksheet

 

Our existing CanPlayerAct function deliberately accepts ordinary gameplay commands only while the main Screen worksheet is active. We'll retain that restriction for movement and combat. However, item actions take place on the Inventory worksheet - we therefore need a second validation function that recognises this different input context.

 

Add the following function to modTurnEngine.

Public Function CanPlayerActInInventory() As Boolean

     Dim player As clsActor
     Dim ws As Worksheet

     Set player = PlayerActor()

     If player Is Nothing Then Exit Function

     ' Item actions are unavailable after death.
     If player.HP <= 0 Then Exit Function
     If mSessionEnded Then Exit Function

     ' The scheduler must be awaiting the player.
     If Not mWaitingForPlayer Then Exit Function

     ' Inventory must be open and currently displayed.
     If Not IsInventoryOpen() Then Exit Function

     Set ws = InventorySheet()

     If ws Is Nothing Then Exit Function

     If Not (ActiveSheet Is ws) Then Exit Function

     CanPlayerActInInventory = True

End Function

 

This checks the same fundamental conditions as ordinary player input: the session must be active, the player must be alive and the scheduler must be waiting for a decision. The additional checks confirm that Inventory is open and that its worksheet is currently active.

 

We also need to tell BeginPlayerAction which interface is submitting the command. Replace the existing function in modTurnEngine with:

Public Function BeginPlayerAction( _
     Optional ByVal fromInventory As Boolean = False) As Boolean

     ' Apply the appropriate input-context validation.
     If fromInventory Then

          If Not CanPlayerActInInventory() Then Exit Function

     Else

          If Not CanPlayerAct() Then Exit Function

     End If

     ' Begin processing an accepted action.
     mWaitingForPlayer = False

     ' Every accepted timed action counts as a player turn.
     mPlayerActionCount = mPlayerActionCount + 1

     ' Start a fresh message batch.
     StartMessageBatch

     BeginPlayerAction = True

End Function

 

The optional argument defaults to False, so our existing movement and melee procedures can continue calling BeginPlayerAction() exactly as before. Inventory actions will instead call BeginPlayerAction(True).

 

Once an action has been accepted, both contexts use the same game-time system. We haven't introduced a second scheduler or separate inventory-turn mechanism, and that's an important advantage of the work completed in earlier milestones: adding a new kind of player action doesn't require rewriting the timing model.

 

Executing a timed inventory command

 

Return to modInventoryUI. We'll create a private procedure called InventoryAction that connects the selected item, validation, execution, messages and the scheduler.

Private Sub InventoryAction(ByVal actionName As String)

     Dim item As clsItem
     Dim ws As Worksheet

     Dim reason As String
     Dim result As String

     ' Accept commands only from an active Inventory screen.
     If Not CanPlayerActInInventory() Then Exit Sub

     Set ws = InventorySheet()
     Set item = SelectedItem()

     ' Invalid actions do not consume game time.
     If Not ItemActionAllowed(item, actionName, reason) Then

          ws.Range("A5").Value2 = reason
          Exit Sub

     End If

     ' Begin a timed action using the Inventory input context.
     If Not BeginPlayerAction(True) Then Exit Sub

     ' Change the item's state.
     result = PerformItemAction(item, actionName)

     ' Record the action in the current message batch.
     LogGameMessage result

     ' Advance to the next player turn, processing monster actions.
     CompletePlayerAction STANDARD_ACTION_COST

     ' The player may have died during the intervening events.
     If mInventoryOpen Then

          RefreshInventoryScreen

          ws.Range("A5").Value2 = result

          ' Require a fresh selection for the next command.
          ws.Range("A1").Select

     End If

End Sub

 

The sequence is deliberate. We identify the selected item and validate the requested action before advancing time. If the command is invalid, an explanatory message appears in Inventory and the procedure ends; if the command is valid, we begin a player action, change the item state and record the result. Finally, CompletePlayerAction advances the scheduler. Any monsters due to act before the next player turn are allowed to move or attack. The call to RefreshInventoryScreen occurs afterwards, provided the game session remains active.

 

The mInventoryOpen check matters because the player might be killed during the monster actions triggered by an inventory command. In that case, the Game Over system will close Inventory, and we must not reopen it or redraw its contents as though the character were still alive. This allows the same death-handling mechanism developed in Part 6 to work regardless of what action caused the final advance in game time.

 

Connecting the action buttons

 

We can now provide public wrappers for the five timed item operations.

Public Sub InventoryPickup()
     InventoryAction "PICKUP"
End Sub

Public Sub InventoryDrop()
     InventoryAction "DROP"
End Sub

Public Sub InventoryEquip()
     InventoryAction "EQUIP"
End Sub

Public Sub InventoryUnequip()
     InventoryAction "UNEQUIP"
End Sub

Public Sub InventoryUse()
     InventoryAction "USE"
End Sub

 

These are the public procedures assigned to the Inventory shapes. Each wrapper delegates to the same validation and execution logic, so we don't have to duplicate the scheduler integration for every kind of item interaction.

 

Inspecting an item is different. It only displays information and therefore doesn't consume time.

Public Sub InventoryInspect()

     Dim item As clsItem
     Dim ws As Worksheet

     If Not IsInventoryOpen() Then Exit Sub

     Set ws = InventorySheet()

     If ws Is Nothing Then Exit Sub
     If Not (ActiveSheet Is ws) Then Exit Sub

     Set item = SelectedItem()

     If item Is Nothing Then

          ws.Range("A5").Value2 = "Select an item row to inspect."

     Else

          ws.Range("A5").Value2 = _
               ItemDisplayName(item) & ": " & _
               item.Description & _
               " [" & ItemEffectSummary(item) & "]"

     End If

End Sub

 

The item system can now perform every interaction required by this milestone. Our inventory interface remains separate from the main map display, but all timed commands participate in the same game simulation.

 

Adding the Inventory shortcut to the main game screen

 

We need one final piece of interface work: a button that opens Inventory during normal gameplay. We'll place it on the narrow black border to the right of the map, beneath the Options and LOG controls established in Part 6.

 

In modGlobals, add:

Public Const SHEET_INVENTORY As String = "Inventory"
Public Const INVENTORY_BUTTON_ADDRESS As String = "AH6:AH7"

 

Options remains at AH2:AH3, and LOG remains at AH4:AH5. Next, open modInterface, locate BuildGameInterface, and add the following code alongside the existing Options and LOG button creation.

' Create the Inventory shortcut.
Set btn = GetOrCreateButton(ws, "btnInventory")

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

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

btn.TextFrame.Characters.Font.Size = 9
btn.OnAction = MacroReference("ShowInventory")

 

The same reusable shape helpers used throughout the game create and configure the new button.

 

We'll make it visible during normal gameplay and hide it on the main menu. Near the end of SetGameplayControlsVisible, add:

If playing Then
     ws.Shapes("btnInventory").Visible = msoTrue
Else
     ws.Shapes("btnInventory").Visible = msoFalse
End If

 

The INV button now opens the Inventory worksheet without consuming an action. The player can return through Back to Game, again without advancing time. However, any successful item interaction performed while the Inventory worksheet is open will consume the appropriate action cost and allow scheduled monsters to act.

 

That is the behaviour we want: examining equipment is free, while actually manipulating it is part of the simulation.

 

Integrating items with game startup

 

Our game now maintains several kinds of session state: the actor manager holds the adventurer and monsters, the turn engine holds the game clock and action schedules, the message module holds the recent event history, and now our new item manager holds definitions and individual item instances. Starting a new adventure must initialise all of these systems in a consistent order, and we will also need to make sure that the Inventory worksheet is closed when the player dies or returns to the main menu.

 

Closing Inventory on death

 

Open modInterface and locate ShowGameOverScreen. Near the beginning of that procedure, add:

' Close the inventory viewer before displaying Game Over.
ResetInventoryInterface

 

Within the existing group of controls hidden during Game Over, add:

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

 

If a monster kills the player during an inventory action, the turn engine will call ShowGameOverScreen, which closes Inventory and returns to the main game worksheet before displaying the death overlay. The existing LOG button will remain available, allowing the final events to be reviewed.

 

Resetting the item session from the main menu

 

Open modGame and locate ShowMainMenu. Add the following calls near the beginning, after the local variable declarations:

' Close Inventory and discard the previous item's session state.
ResetInventoryInterface
ResetItemSession

 

The existing actor, clock, message and interface resets remain in place. This ensures that returning to the main menu abandons the current inventory along with the rest of the adventure.

 

Starting a new game with ground items

 

Replace StartNewGame with the following version.

Public Sub StartNewGame()

     Dim player As clsActor

     ' Discard the previous adventure's state.
     ResetInventoryInterface
     ResetItemSession

     ResetTurnSession
     ResetPlayer

     ClearGameMessages

     ' Load the starting world and its actors.
     ShowMap

     Set player = PlayerActor()

     If player Is Nothing Then Exit Sub

     ' Create the initial item instances.
     InitialiseItemSession START_MAP_ID

     ' Draw items between terrain and living actors.
     DrawAllGroundItems
     DrawAllActors

     ' Start the normal action schedule and message batch.
     StartTurnSession

     ' Announce any items beneath the starting position.
     LogGameMessage GroundItemMessageAt(player.X, player.Y)

     ' Reveal movement, Options, LOG and Inventory controls.
     SetGameplayControlsVisible True

End Sub

 

Again, the order is important. We first reset the previous session state, then call ShowMap, which loads the terrain and initial actors. Next, we initialise the item session. The item loader can now validate spawn locations against the active map. We draw ground items over the terrain and redraw the actors above them. Only after the world is populated do we start the turn engine. Finally, we announce the sword lying beneath the player and reveal the interface controls.

 

The adventurer now begins a new game in the familiar starting location, surrounded by the same monsters as before, but with several objects to discover. The sword under the starting position provides an immediate opportunity to try the inventory system.

 

Testing the item lifecycle

 

The quickest way to understand what we've built is to play through the item's complete lifecycle. Start a new game and examine the starting message panel. It should announce that a sword lies beneath the adventurer.

 

Click INV in the right-hand border. The Inventory worksheet should open, showing an empty carried-items list and the Short Sword in the ground-items list. Select the sword's row and click Pick Up. The sword should disappear from the ground-items list and appear among the player's possessions. The carried-item count should increase to one. The action also consumes time, which means the world may advance and nearby monsters may move.

 

Now select the sword from the carried-items list and click Equip. The weapon slot should display Short Sword, and the player's effective damage should increase from four to six. Returning to the main game screen should show the same damage value in the status panel.

 

This demonstrates that equipping an item changes combat statistics without rewriting the player's base actor definition.

 

Armour and healing

 

The armour and healing potion at (11,8) provide the next useful test, so move the player onto their shared tile; the game should report that a pile of items lies there. Opening Inventory will show both items separately, each with its own instance identifier. Collect the armour and potion, then equip the armour - the adventurer's protection should increase to one. A goblin's normal two-damage attack should now cause only one damage, while the wolf's three-damage attack should cause two. The attack messages should report the actual damage inflicted after protection.

 

Once the player has lost health, the potion can be used. A Healing Potion restores up to eight HP, without exceeding the player's maximum. If the adventurer is missing only three HP, the potion restores three. After consumption, the potion leaves the carried-items list because its state becomes USED.

 

Attempting to drink a potion while already at full health should be rejected without consuming the item or advancing game time.

 

Dropping and changing equipment

 

Dropping a carried item returns it to the ground at the player's current coordinates. If another item is already there, the map will display a pile symbol, but the dropped item retains its individual properties, including any damage modifier we have applied. Picking it up again retrieves the same object rather than constructing a replacement from the shared definition.

 

Equipping another weapon automatically returns the previously equipped weapon to the inventory. Both remain available, but only one occupies the weapon slot. The same principle applies to armour. This confirms that equipment state, item ownership and ground location are all managed through the individual objects rather than through fixed worksheet values.

 

Checking the carrying limit

 

Our inventory capacity is 20 individual items. Equipped objects count towards that total, and identical consumables don't combine into stacks. The first twenty items can be carried, but attempting to pick up a twenty-first is rejected and, because the validation happens before BeginPlayerAction, the failed pickup consumes no game time.

 

We can test the capacity by temporarily adding more item-spawn records in tblItemSpawns, using unique instance IDs and placing multiple objects on the same accessible tile. After testing, the original five-item starting configuration can be restored.

 

Checking independent item modifiers

 

The most important architectural test is that modifications belong to individual instances. Start with a Short Sword that provides +2 damage and, using the development helper, assign an additional modifier of +1 to SWORD01. When equipped, that sword should now provide +3, bringing the adventurer's effective damage to seven. The Short Sword definition in tblItemTypes remains unchanged and a second Short Sword instance, if present, still provides its normal +2 bonus. This confirms that the item manager isn't merely retrieving current values from the shared table whenever equipment is used. It is working with the state of a particular object.

 

That distinction will be fundamental when we develop item enhancement and unique equipment.

 

Item actions during combat

 

Finally, we should verify that manipulating inventory doesn't interrupt the normal game simulation. Allow a monster to approach the player, then open Inventory. You will notice that opening the worksheet itself doesn't consume time - however, equipping an item, dropping an object or drinking a potion advances the scheduler by the appropriate action cost. The monster may therefore attack during the resulting interval and, if a fatal attack occurs, Inventory closes and the Game Over screen appears. The final messages remain available through LOG, exactly as they do following an ordinary movement or combat action.

 

This confirms that our new item system is properly integrated with the clock, combat and death mechanisms developed in earlier instalments.

 

All of these behaviours have been tested in the completed Milestone 7 build, including the existing movement, rendering, menu and message-history functionality.

 

A more capable adventurer

 

At the end of Part 6, our player had one way to influence combat: move into an adjacent monster to attack it. Now the player has meaningful preparation choices: collecting the Short Sword increases damage, wearing Leather Armour reduces incoming attacks, and carrying a healing potion provides an opportunity to recover from injuries, but drinking it consumes time and may expose the player to another attack. Items can be left on the ground, retrieved later or exchanged for other equipment.

 

Even with this very small catalogue, those mechanics begin to change how the game feels. The adventurer is no longer just an actor with fixed combat statistics. They have possessions that influence their capabilities, and those possessions persist as individual objects throughout the current adventure.

 

Our map renderer has also gained another independent layer. Terrain continues to exist beneath ground items, items remain beneath actors, and piles can contain several objects even though only one symbol is displayed. Moving, picking up and dropping objects all use the same tile-redrawing system we've been developing since the first instalment.

 

The inventory interface introduces another application state without changing the fundamental structure of gameplay. Item commands use the same event-driven scheduler as movement and combat, preserving the relationship between player decisions, monster speed and game time, and the item manager itself remains separate from the interface. We can change how Inventory looks or where its controls appear without changing the way items are stored, equipped or consumed. That's particularly valuable for a game built inside Excel, where the worksheet is both a convenient interface and a potential source of unnecessary coupling.

 

The Milestone 7 project download

 

As with Part 6, this instalment is accompanied by a complete playable version of the project. The release package contains the tested macro-enabled .xlsm workbook, a macro-free .xlsx version for readers following the tutorial, and the exported VBA source modules. The exported source includes the new clsItem class, modItems and modInventoryUI, alongside the existing game modules updated for this milestone.

 

Readers who want to explore the current game can use the .xlsm workbook. Those who prefer to build the system themselves can start from the instructional workbook and follow the code and explanations in this article. Because the playable version relies on VBA, macros must be permitted for the game to run. Readers should obtain the files from the trusted project source, inspect the VBA if desired and enable macros only for the specific workbook they have chosen to trust.

 

Excel may block macros in workbooks downloaded from the internet. On Windows, a verified download may offer an Unblock option in the file's Properties dialog, after which Excel's normal macro security controls apply. There is no need to enable macros globally or disable Excel's security protections. The project is intended for desktop Excel with VBA support.

 

Where do we go from here?

 

We've deliberately kept this first item system manageable. Our weapons provide fixed damage bonuses, armour subtracts a fixed amount from incoming attacks, and healing potions restore a defined number of HP. The item class supports independent modifications, but we haven't yet introduced ordinary gameplay actions for sharpening weapons or enchanting equipment. Similarly, we don't have weapon materials, Strength requirements, durability, item identification or unique artifacts with special abilities - those systems deserve their own dedicated work.

 

When we develop the advanced item model, weapons will have proper damage expressions such as 1d6 or 3d6, and weapon damage will replace the actor's unarmed damage rather than simply being added to it. Materials and individual modifiers will affect those calculations, and characters may require sufficient Strength to wield heavy weapons effectively. Eventually, items may also have effects beyond damage and protection. A weapon might inflict cold damage or slow an opponent, while a staff could provide advantages when travelling through difficult terrain. Our current item-instance design gives us a place to attach those capabilities when we're ready to implement them.

 

There are other opportunities for improvement as well. At present, Inventory occupies its own worksheet, while the game map and message panel remain on Screen. A later interface milestone could bring inventory management closer to the map, allowing the player to see world events while manipulating possessions. We can also introduce clearer action notifications and more elaborate item descriptions once our catalogue grows.

 

For the next stage of gameplay, though, there is an especially attractive opportunity: making the world itself more rewarding to explore. We can begin using our new item system to populate additional locations, introduce meaningful treasure and eventually allow monsters or containers to yield loot.

 

Until then, our five starting items are enough to demonstrate a complete object lifecycle. A sword can begin on the ground, be picked up, modified, equipped, exchanged and dropped again without ever losing its identity. A potion can be collected, carried and consumed. Armour can change the result of attacks without altering the player's underlying actor definition. And all of those interactions take place within the same turn-based world we've been building from the beginning. For an RPG written entirely in Excel, that's a substantial new set of possibilities. Our adventurer finally has something worth carrying and perhaps, with a sword in hand, armour on their back and a healing potion tucked away, Old Fort Approach will be a little less unforgiving.

 

This article is Part 7 of the Building an RPG in Excel series. The accompanying project release found here contains the instructional workbook, exported VBA source and the complete playable Milestone 7 game.

11 December 2026

Full Service Consulting

Reporting

Automation

Cat On A Spreadsheet

Cat On A Spreadsheet