MCCodes - Chapter 4: Item Management

MCCodes Walkthrough Tutorial

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:

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.

Each row in the items table represents a unique item type and defines its properties:

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.

Each row in the inventory table links a player to an item type and specifies the quantity:

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:

  1. Viewing Your Inventory (inventory.php)

    • This is your main screen to see everything you own.
    • It reads your inventory table, joins it with the items 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.

  2. 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 the items table (using the inv_itemid found via inv_id).
    • It applies the effect (e.g., increases $ir['hp'], updates userstats).
    • 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.

  3. 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 or armor columns in items).
    • It updates special columns in the users table (equip_primary, equip_secondary, equip_armor) to store the itmid 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 the inventory table and sets the slot in the users table to 0.
  4. 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 in shopitems table, linking shops and items).
    • itembuy.php: Processes your purchase. Takes the item ID (sitemID from shopitems) 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 your inventory (using item_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 your inventory (using item_remove) and adds money (itmsellprice * quantity) to your $ir['money'].
  5. 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 the itemmarket table). It provides links to buy items or remove your own listings.
    • imadd.php: Lets you take an item from your inventory and list it on the itemmarket 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:

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:

  1. Navigate: You click the "Shops" link in the menu, which takes you to shops.php.
  2. List Shops: shops.php checks your location ($ir['location']) and shows shops in that city. You click on "Bob's Armory".
  3. List Items: shops.php (now with ?shop=ID) queries the shopitems table joined with items for Bob's Armory (shopID). It displays the "Basic Sword" with its price and a "Buy" button/form.
  4. Submit Purchase: You enter quantity "1" and click "Buy". Your browser sends a request to itembuy.php?ID=shop_item_id with qty=1.
  5. 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 the shopitems 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 your inventory 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().

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

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:

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