MCCodes - Chapter 4: Item Management
Welcome to Chapter 4! In Chapter 3: Crime System, we saw how you can commit crimes to earn rewards like money, experience, and sometimes even items. But what happens after you get an item? How does the game keep track of it? How do you use it, sell it, or equip it if it's a weapon or armor? That's where Item Management comes in.
The Problem: Handling All the Stuff!
Imagine a game where you find a cool sword, but there's no way to see it, equip it, or sell it. Or maybe you need a health potion, but there's no place to buy one. A game needs a system to handle all the virtual goods -- defining what they are, tracking who owns what, and providing ways for players to interact with them.
The Solution: MCCodes has a comprehensive Item Management system. It's like the game's entire logistics network for physical goods. It involves:
- Defining Items: What is a "Sword"? What does a "Health Potion" do? (Stored in the
items
table). - Tracking Ownership: Who has which items, and how many? (Stored in the
inventory
table). - Viewing & Managing: Letting players see their items (
inventory.php
). - Using Items: Applying an item's effect, like drinking a potion (
itemuse.php
). - Equipping Gear: Putting on weapons or armor (
equip_*.php
,unequip.php
). - Buying/Selling: Interacting with game-controlled shops (
shops.php
,itembuy.php
,itemsell.php
). - Player Trading: Listing items for sale to other players (
itemmarket.php
).
Think of it as managing warehouses (inventory
), stores (shops
), and marketplaces (itemmarket
), along with the rules for using or wearing the items.
What is an Item? The items
Table
Before you can own an item, the game needs to know what that item is. This information is stored in the items
database table.
- Analogy: Think of this like a product catalog. Each entry describes one type of item available in the game world.
Each row in the items
table represents a unique item type and defines its properties:
-
itmid
: A unique ID number for this item type (e.g., 1 might be "Knife", 2 might be "Health Potion"). -
itmtype
: What kind of item is it? (e.g., Weapon, Armor, Potion, Food - linked toitemtypes
table). -
itmname
: The name players see (e.g., "Sharp Knife"). -
itmdesc
: A description of the item. -
itmbuyprice
: How much it costs to buy from an NPC shop (if buyable). -
itmsellprice
: How much you get for selling it back to an NPC shop. -
itmbuyable
: Can this item be bought from shops? (Yes/No). -
effect1
,effect2
,effect3
: What happens when you use the item? (e.g., restores HP, increases strength). These store complex details about the effect. (Note: These often use PHP'sserialize
function to store structured data as text, which requires careful handling). -
effect1_on
,effect2_on
,effect3_on
: Are the respective effects active/usable? (Yes/No). -
weapon
: If it's a weapon, how much attack power does it add? -
armor
: If it's armor, how much defense does it add?
Admins can add new items or modify existing ones through the Staff Panel (staff_items.php
), which updates this items
table.
Your Backpack: The inventory
Table
Knowing what items can exist isn't enough. The game needs to track which player owns which items. This is done using the inventory
table.
- Analogy: This is your personal backpack or warehouse storage. It lists exactly what you are carrying.
Each row in the inventory
table links a player to an item type and specifies the quantity:
-
inv_id
: A unique ID for this specific inventory entry (like a tracking number for a stack of items). -
inv_itemid
: Which item type is this? (This links to theitmid
in theitems
table). -
inv_userid
: Which player owns this item? (This links to theuserid
in theusers
table). -
inv_qty
: How many of this item does the player have in this stack?
So, if player with userid
10 owns 5 "Health Potions" (which have itmid
2), there might be a row in inventory
like: inv_id=123, inv_itemid=2, inv_userid=10, inv_qty=5
.
Core Item Actions (and the Files Involved)
Let's look at the common things you can do with items and which files handle them:
Viewing Your Inventory (
inventory.php
)- This is your main screen to see everything you own.
- It reads your
inventory
table, joins it with theitems
table to get names and details, and displays it nicely. - It also shows your currently equipped items (from the
users
table) and provides links to manage items (use, sell, equip, send, add to market).
<?php // File: inventory.php (Simplified Concept) require_once('globals.php'); // Load user data ($ir), connect DB ($db), start page ($h) echo "<h3>Inventory</h3>"; // Query to get items for the current user ($userid) $inv = $db->query("SELECT iv.inv_id, iv.inv_qty, i.itmname, i.itmsellprice /* ... other fields ... */ FROM inventory iv INNER JOIN items i ON iv.inv_itemid = i.itmid WHERE iv.inv_userid = $userid"); echo "<table>"; // Start an HTML table while ($row = $db->fetch_row($inv)) { echo "<tr> <td>{$row['itmname']} x{$row['inv_qty']}</td> <td>" . money_formatter($row['itmsellprice']) . "</td> <td> [<a href='itemuse.php?ID={$row['inv_id']}'>Use</a>] [<a href='itemsell.php?ID={$row['inv_id']}'>Sell</a>] ... other links ... </td> </tr>"; } echo "</table>"; $db->free_result($inv); $h->endpage(); // Finish the page ?>
This code fetches your inventory, loops through each item stack, and displays its name, quantity, sell price, and links for actions.
Using an Item (
itemuse.php
)- Handles the logic when you click the "[Use]" link for an item like a potion or a stat booster.
- It reads the item's
effect
fields from theitems
table (using theinv_itemid
found viainv_id
). - It applies the effect (e.g., increases
$ir['hp']
, updatesuserstats
). - It then removes one quantity of the item from your inventory.
<?php // File: itemuse.php (Simplified Concept) require_once('globals.php'); // Load user data ($ir), etc. // Get the inventory ID from the URL (?ID=...) $inv_id = abs((int)$_GET['ID']); // Fetch item details and effects based on inv_id and userid $q = $db->query("SELECT i.effect1, i.effect1_on, /* ... more effects ... */ i.itmname, iv.inv_itemid FROM inventory iv INNER JOIN items i ON iv.inv_itemid = i.itmid WHERE iv.inv_id = {$inv_id} AND iv.inv_userid = $userid"); if ($db->num_rows($q) > 0) { $item_data = $db->fetch_row($q); // Loop through effects 1 to 3 for ($e = 1; $e <= 3; $e++) { if ($item_data["effect{$e}_on"]) { // IMPORTANT: Unserializing data can be risky if the source isn't trusted. // Here, it comes from the admin-controlled `items` table. $effect_info = unserialize($item_data["effect{$e}"]); // Apply the effect based on $effect_info (increase/decrease stat, etc.) // ... (complex logic here to modify $ir or userstats) ... // Example: $ir['hp'] += $effect_info['inc_amount']; // ... (code to update the database for the stat change) ... } } echo "Used {$item_data['itmname']} successfully!"; // Remove 1 quantity of the item (uses a helper function) item_remove($userid, $item_data['inv_itemid'], 1); } else { echo "Invalid item."; } $db->free_result($q); $h->endpage(); ?>
This script finds the item in your inventory, checks its effects, applies them to your character's stats (updating the database), displays a success message, and removes one count of the item.
Equipping/Unequipping Gear (
equip_weapon.php
,equip_armor.php
,unequip.php
)- Handles putting on or taking off weapons and armor.
- When equipping, it checks if the item is actually a weapon/armor (using
weapon
orarmor
columns initems
). - It updates special columns in the
users
table (equip_primary
,equip_secondary
,equip_armor
) to store theitmid
of the equipped item. - It moves the item from your
inventory
to the equipped slot. If something was already equipped, it moves that back to the inventory. -
unequip.php
does the reverse: moves the item from the equipped slot back to theinventory
table and sets the slot in theusers
table to 0.
Buying/Selling at NPC Shops (
shops.php
,itembuy.php
,itemsell.php
)-
shops.php
: Displays a list of shops available in your current location ($ir['location']
). When you enter a shop, it shows the items available for sale there (defined inshopitems
table, linkingshops
anditems
). -
itembuy.php
: Processes your purchase. Takes the item ID (sitemID
fromshopitems
) and quantity. Checks if you have enough money ($ir['money']
) and are in the right location. If yes, it deducts money and adds the item to yourinventory
(usingitem_add
). -
itemsell.php
: Processes selling items from your inventory back to the game. Takes the inventory ID (inv_id
) and quantity. Checks if you actually have the item. If yes, it removes the item from yourinventory
(usingitem_remove
) and adds money (itmsellprice
* quantity) to your$ir['money']
.
-
Trading on the Player Market (
itemmarket.php
,imadd.php
, etc.)-
itemmarket.php
: The main hub for player-to-player item trading. It lists items put up for sale by other players (reading from theitemmarket
table). It provides links to buy items or remove your own listings. -
imadd.php
: Lets you take an item from yourinventory
and list it on theitemmarket
table for a specific price (in money or crystals). - Buying logic (within
itemmarket.php
's 'buy' action): Transfers the item from the seller's market listing to the buyer's inventory, and transfers the currency (money or crystals) between the players.
-
Helper Functions: item_add()
and item_remove()
You might notice that buying items, receiving items from crimes, unequipping gear, or receiving items from other players all need to add items to your inventory. Similarly, selling, using, or equipping items involves removing them.
Instead of repeating the complex logic for updating the inventory
table everywhere, MCCodes uses helper functions, typically found in global_func.php
or a similar core file:
-
item_add($userid, $itemid, $quantity)
: This function takes a user ID, an item ID, and a quantity. It intelligently updates theinventory
table. If the user already has that item, it increases theinv_qty
. If not, it adds a new row to theinventory
table. -
item_remove($userid, $itemid, $quantity)
: This function removes a specified quantity of an item from a user's inventory. It finds the correct row(s) in theinventory
table and decreases theinv_qty
. If the quantity reaches zero, it might delete the row.
These functions centralize the inventory update logic, making the code in files like itembuy.php
or itemuse.php
much simpler. They just need to call item_add
or item_remove
without worrying about the database details.
Walkthrough: Buying an Item from a Shop
Let's trace the steps when you buy a "Basic Sword" from a shop:
- Navigate: You click the "Shops" link in the menu, which takes you to
shops.php
. - List Shops:
shops.php
checks your location ($ir['location']
) and shows shops in that city. You click on "Bob's Armory". - List Items:
shops.php
(now with?shop=ID
) queries theshopitems
table joined withitems
for Bob's Armory (shopID
). It displays the "Basic Sword" with its price and a "Buy" button/form. - Submit Purchase: You enter quantity "1" and click "Buy". Your browser sends a request to
itembuy.php?ID=shop_item_id
withqty=1
. - Process Purchase (
itembuy.php
):- Includes
globals.php
(loads$ir
,$db
, etc.). - Gets the
shopitems
ID ($_GET['ID']
) and quantity ($_POST['qty']
). - Queries the database to get item details (
itmid
,itmbuyprice
,itmname
) and shop location, using theshopitems
ID. - Check 1: Location: Is
$itemdata['shopLOCATION'] == $ir['location']
? (Yes) - Check 2: Buyable: Is
$itemdata['itmbuyable'] == 1
? (Yes) - Check 3: Money: Is
$ir['money'] >= $itemdata['itmbuyprice'] * $qty
? (Let's assume Yes) - Action 1: Deduct Money: Updates the
users
table:SET money = money - price WHERE userid = $userid
. Updates your local$ir['money']
. - Action 2: Add Item: Calls the helper function
item_add($userid, $itemdata['itmid'], $qty)
. This function updates yourinventory
table, either adding a new row for the Basic Sword or increasing the quantity if you already had some. - Log: Records the purchase in
itembuylogs
. - Display Message: Shows "You bought 1 Basic Sword for $50."
- Calls
$h->endpage()
.
- Includes
Under the Hood: The Buying Process Flow
Here's a simplified sequence diagram of buying an item:
sequenceDiagram participant B as Browser participant S as shops.php participant IB as itembuy.php participant G as globals.php participant DB as Database participant Func as item_add() B->>S: Request shops.php?shop=X S->>G: require 'globals.php' G-->>S: Setup done ($ir, $db, $h) S->>DB: Get items for shop X (from shopitems & items) DB-->>S: Return item list S-->>B: Display items, including "Basic Sword" with Buy form (posts to itembuy.php) B->>IB: Submit Buy form (itembuy.php?ID=Y&qty=1) IB->>G: require 'globals.php' G-->>IB: Setup done ($ir, $db, $h) IB->>DB: Get item details (price, buyable) & shop location for ID=Y DB-->>IB: Return item & shop data IB->>IB: Check location ($ir['location'] == shopLocation?) IB->>IB: Check money ($ir['money'] >= price?) IB->>DB: Update user's money (money = money - price) DB-->>IB: Money updated IB->>Func: Call item_add(userid, itmid, qty) Func->>DB: Check if user has item in inventory DB-->>Func: Result (Yes/No) alt User already has item Func->>DB: UPDATE inventory SET inv_qty = inv_qty + qty WHERE ... else User does not have item Func->>DB: INSERT INTO inventory (inv_userid, inv_itemid, inv_qty) VALUES (...) end DB-->>Func: Inventory updated Func-->>IB: Item added successfully IB->>DB: Log transaction in itembuylogs DB-->>IB: Logged IB-->>B: Display "Successfully bought item!" message
This shows how itembuy.php
coordinates with the database and the item_add
function to check conditions, update the player's money, and finally add the item to their inventory.
Key Tables and Files
- Tables:
-
items
: Defines all possible items (the catalog). -
itemtypes
: Categories for items (Weapon, Armor, Potion...). -
inventory
: Tracks who owns what (player backpacks). -
shops
: Defines NPC shops and their locations. -
shopitems
: Links shops to the items they sell. -
itemmarket
: Lists items players are selling to each other. -
users
: Stores currently equipped items (equip_primary
,equip_secondary
,equip_armor
). - Various Log Tables (
itembuylogs
,itemselllogs
,itemxferlogs
,imarketaddlogs
, etc.): Keep records of transactions for staff review.
-
- Key PHP Files:
-
inventory.php
: View your items and equipped gear. -
itemuse.php
: Use an item's effect. -
equip_weapon.php
/equip_armor.php
: Equip gear. -
unequip.php
: Unequip gear. -
shops.php
: Browse shops and see items for sale. -
itembuy.php
: Handle buying from NPC shops. -
itemsell.php
: Handle selling items to NPC shops. -
itemsend.php
: Send items to another player. -
itemmarket.php
: View and interact with the player market. -
imadd.php
: Add items from your inventory to the player market. -
staff_items.php
: Staff panel tool for managing items and types. -
global_func.php
(or similar): Often containsitem_add()
anditem_remove()
helper functions.
-
Conclusion
You've now explored the Item Management system of MCCodes! It's a crucial part of the game, handling everything related to items. We learned about:
- How items are defined (
items
table) and how player ownership is tracked (inventory
table). - The various PHP files that allow players to view (
inventory.php
), use (itemuse.php
), equip (equip_*.php
), buy/sell from shops (shops.php
,itembuy.php
,itemsell.php
), and trade on the market (itemmarket.php
). - The importance of helper functions like
item_add
anditem_remove
for simplifying inventory updates.
This system provides the foundation for players to gather resources, improve their characters with gear and consumables, and participate in the game's economy.
Now that you know how to get and manage items, including weapons and armor, let's see how you can use that equipment in combat!
Next Up: Chapter 5: Attacking System
Previously: Chapter 3: Crime System
First published April 21, 2025
Tags: MCCodes Walkthrough Tutorial