Let's Build a Tiny City of AI Delivery Trucks From Scratch

Akram Chauhan
Akram Chauhan
8 min read159 views
Let's Build a Tiny City of AI Delivery Trucks From Scratch

Ever find yourself watching a delivery truck weave through traffic and wonder about the sheer complexity of it all? Thousands of packages, endless routes, tight deadlines. Now, what if those trucks were completely autonomous? How would they decide which package to grab? How would they avoid running out of juice?

It sounds like science fiction, but it’s a problem that engineers are tackling right now. And honestly, the best way to understand a complex system is to try and build a simple version of it yourself.

So, that's what we're going to do today.

We're going to build a tiny, digital city bustling with a fleet of smart, autonomous delivery trucks. These aren't just dumb sprites moving on a screen. Each truck will be an "agent" with its own little brain. It will have a bank account, a battery level, and the ability to make its own decisions to maximize profit.

We'll watch as they compete for delivery jobs in a real-time auction, plan the best routes, and even duck out to find a charging station when their batteries get low. It’s like building a digital ant colony, but with electric trucks and capitalism. Let's get started.

Setting the Stage: Our Digital Sandbox

Before we can have trucks, we need roads for them to drive on. We’re not going to render a full 3D city—that’s overkill. Instead, we’ll use something much more elegant: a graph.

Think of it like a subway map. You have stations (we’ll call them nodes) and the lines connecting them (edges). In our simulation:

  • Nodes are key locations: warehouses, houses, and charging stations.
  • Edges are the roads connecting them, each with a "weight" representing distance or travel time.

We'll use a popular Python library called networkx to whip up this city grid in just a few lines of code. We'll randomly sprinkle some of these nodes as "chargers" (because even AI trucks need to refuel) and the rest as regular locations.

Now, let's create our star players: the AgenticTruck class. This is the blueprint for every truck in our fleet. Each one will need to keep track of a few key things:

  • Its current location on the map (current_node).
  • How much battery it has left.
  • Its bank balance (gotta make money!).
  • Its current state: Is it IDLE, MOVING to a destination, or CHARGING?

This initial setup is like building the game board and creating the player pieces. We're laying the foundation for all the interesting behavior that’s about to unfold.

# A simplified look at our truck's 'DNA'
class AgenticTruck:
    def __init__(self, agent_id, start_node, graph):
        self.id = agent_id
        self.current_node = start_node
        self.graph = graph
        self.battery = 100.0
        self.balance = 1000.0
        self.state = "IDLE" # Can be IDLE, MOVING, TO_CHARGER, CHARGING
        self.path = []
        self.current_order = None

Giving Our Trucks a Brain: How to Make Smart Decisions

Okay, we have a city and we have trucks. But right now, they're just sitting there. To bring them to life, we need to give them the ability to think. This is where the "agentic" part comes in. Their intelligence will revolve around a few key questions.

"What's the best way to get from A to B?"

This is a classic problem, and thankfully, it's one that graph theory solves beautifully. Using networkx, we can instantly find the shortest path between any two nodes. Our trucks will use this to calculate travel distance and fuel costs. No getting lost!

"Is this delivery job worth my time?"

This is the core of our truck's business logic. When a new delivery order pops up, each idle truck runs a quick mental calculation. It asks:

  1. Can I even carry this? (Is the package weight within my capacity?)
  2. Do I have enough battery? (No point in accepting a job if I’ll die halfway through.)
  3. Will I make a profit? The truck calculates the distance to the destination, estimates the fuel cost, and subtracts it from the delivery payout. If the remaining profit is too low, it's a hard pass.

The truck then submits a "bid" based on how good the job looks. In our simple model, the bid is just the distance to the target—a lower distance is a better bid. It's a proxy for "I'm close and can do it efficiently."

# The truck's thought process for bidding on an order
def calculate_bid(self, order):
    # Rule 1: Can't accept if busy, low on battery, or package is too heavy
    if self.state != "IDLE" or self.battery < 25 or order.weight_kg > self.capacity:
        return float('inf') # An infinitely high bid means "no thanks"

    # Rule 2: Calculate profit
    dist_to_target, _ = self.get_path_cost(self.current_node, order.target_node)
    fuel_cost = dist_to_target * FUEL_PRICE
    expected_profit = order.payout - fuel_cost

    # Rule 3: If profit is too low, don't bother
    if expected_profit < 10:
        return float('inf')

    # Otherwise, bid based on how close I am
    return dist_to_target

"Uh oh, my battery is low. What now?"

A truck that runs out of battery is a useless truck. So, we need a self-preservation instinct. If a truck's battery dips below a critical threshold (say, 25%), its top priority changes. It stops looking for jobs and instead asks, "Where is the nearest charging station?" It then plots a course and heads there directly.

This simple rule prevents our fleet from grinding to a halt and adds a fascinating layer of resource management to the simulation.

The Conductor: Running the Simulation

We've designed the city and the players. Now we need a "game master" to make everything happen. This is our Simulation class. It’s responsible for orchestrating the whole show.

The Marketplace

At regular intervals, the simulation does two things:

  1. Generates new orders: A new delivery job pops up at a random location with a random payout.
  2. Runs an auction: The simulation presents the new order to all the trucks. Each truck calculates its bid using the logic we just discussed.

The simulation then looks at all the bids. The truck with the lowest valid bid (meaning the closest one that can actually do the job profitably) wins! The order is assigned, and the truck's state changes from IDLE to MOVING.

This auction system creates a simple, decentralized market. We don't need a central dispatcher telling everyone what to do. The trucks sort it out among themselves through competition. The most efficient truck for the job naturally wins.

The Clock Ticks

With every "tick" of our simulation clock, time moves forward. For each truck, we run a step() function that updates its status based on its current state:

  • If MOVING: It moves one step along its planned path, consuming battery and "money" for fuel. If it reaches the destination, it collects the payout and becomes IDLE again.
  • If TO_CHARGER: It moves along its path to the charging station.
  • If CHARGING: It stays put, and its battery level goes up (while its bank balance goes down slightly to pay for the electricity).
  • If IDLE: It checks its battery. If it's low, it switches to the TO_CHARGER state. Otherwise, it just waits for the next auction.

This step-by-step loop is the engine of our simulation. It’s what turns a static set of rules into a dynamic, evolving system.

Bringing It All to Life: The Visualization

This is the best part. All these numbers and states are abstract, but we can use matplotlib to draw our little world and watch it run in real time.

With each step of the simulation, we'll clear the screen and redraw everything:

  • The city graph with its nodes and roads.
  • The charging stations (maybe color them red).
  • The pending delivery orders (we can use a gold star icon).
  • And, of course, our trucks! We’ll draw them as little squares on their current node, color-coded by their state (e.g., green for idle, orange for moving). We can even label them with their ID, battery level, and cash.

Watching the visualization is mesmerizing. You see green trucks suddenly turn orange as they win a bid and start moving. You see a truck on a long journey suddenly make a detour to a red charging node. You see gold stars appear and then vanish as orders are completed.

You're not just looking at a chart; you're observing a tiny economy in motion.

# A simplified peek at the visualization logic
def visualize(self, step_num):
    clear_output(wait=True)
    plt.figure(figsize=(10, 8))
    pos = nx.get_node_attributes(self.G, 'pos') # Get coordinates for each node

    # Draw the city map
    nx.draw(self.G, pos, with_labels=True, ...)

    # Draw each agent
    for agent in self.agents:
        x, y = pos[agent.current_node]
        color = 'green' if agent.state == "IDLE" else 'orange'
        plt.plot(x, y, marker='s', color=color, ...)
        plt.text(x, y, f"A{agent.id}\n${int(agent.balance)}", ...)

    plt.title(f"Logistics Swarm Simulation | Step: {step_num}")
    plt.show()

What We've Really Built Here

When you run this simulation for a few minutes, you start to see something amazing: emergent behavior.

We never explicitly programmed the trucks to "cooperate" or "divide up the city." All we did was give each truck a simple set of selfish rules: maximize profit and don't run out of battery. Yet, the system as a whole starts to look incredibly intelligent. Trucks naturally specialize in deliveries near them. The fleet automatically adapts when a new charging station is added or when orders are clustered in one area.

This is more than just a fun coding project. It's a powerful sandbox for understanding complex systems. You could use this exact framework to test out new ideas. What if fuel prices suddenly doubled? What if we introduced traffic jams? What's the optimal number of charging stations for a city of this size?

By building this tiny world, we gain a real, intuitive feel for how multi-agent AI systems work. We see firsthand how simple, local rules can lead to complex, global intelligence. And that, to me, is one of the most exciting things about AI. You don't always have to build one giant, monolithic brain; sometimes, you can just build a swarm.

Tags

AI Robotics Automation Agentic AI AI Engineering AI System Design Python Autonomous Systems Software Development Distributed Systems Multi-Agent Systems Logistics AI Route Planning Graph-Based Simulation Real-time Visualization Dynamic Auctions Simulation Optimization Algorithms

Stay Updated

Get the latest articles and insights delivered straight to your inbox.

We respect your privacy. Unsubscribe at any time.

Aicosoft

AI & Technology News, Insights & Innovation

AICOSOFT delivers cutting-edge AI news, technology breakthroughs, and innovation insights. Stay informed about artificial intelligence, machine learning, robotics, and the latest tech trends shaping tomorrow.

Connect With Us

© 2026 Aicosoft. All rights reserved.