Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • CreatiCode
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Brand Logo

CreatiCode Scratch Forum

  1. CreatiCode Forum
  2. Knowledge Base
  3. Tutorials
  4. Game AI for Candy Truck Battle - Part 1 (Difficulty: 3)

Game AI for Candy Truck Battle - Part 1 (Difficulty: 3)

Scheduled Pinned Locked Moved Tutorials
1 Posts 1 Posters 922 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • CreatiCodeI Offline
    CreatiCodeI Offline
    CreatiCode
    wrote on last edited by
    #1

     

    Introduction

     
     

    Candy Truck Battle is a 2D online shooting game played between two players. Each player controls a candy-themed truck that can move around, collect power-up items like Sugar and Gas, and fire donuts at the opponent.

    Players control the truck using:

    • WASD keys to move in 4 directions
    • SPACE to shoot donuts

    In this tutorial, we’ll build an AI (Artificial Intelligence) that can automatically control the truck in this game. Instead of using the keyboard, the AI will decide when to move and shoot, all by itself.

    We’ll go through a series of increasingly powerful AI versions, each adding more intelligence and strategy.

    Here’s a preview of what happens when two AIs face off after you complete this tutorial:

    attack.gif

     
     
     
     
     
     
     
     
     

    Version 1 - Random Walk (Difficulty: 2)

     

    The first version of the AI will do something very simple: send out random movement commands. It won’t think, aim, or chase. It will just wander around randomly, like a monkey pressing buttons.

    That might sound silly at first, but it’s actually very useful for two reasons:

    1. It helps us set up and test the AI system early, without needing complicated logic. Once we get this working, we can improve it gradually.

    2. It serves as a baseline. Any future AI we build should be able to beat this one. If not, the new AI probably isn’t very smart.

    Let’s get started.

     
     

    Step 1 - Remix the Game Project

     

    Go to the following link and remix the original game project to create your own copy:

    play.creaticode.com/projects/6858d69beb4683fb2ab03c73
     
    If you’re interested in how this multiplayer game was built, you can read the detailed explanation in this tutorial.

     
     

    Step 2 - Understand the Manual Controller

     

    The Controller sprite is responsible for handling user input. Let’s take a look at the script that controls movement and shooting:

    blocks (1).png

    Here’s what the code does:

    • It starts running after receiving the "start game" message.
    • It enters a forever loop, constantly checking if the player is pressing any movement keys (W/A/S/D).
    • If the SPACE key is pressed, it sends out a "shoot donut" message.
    • If one of the W/A/S/D keys is pressed, it sends out a movement command using the "my team" message, with a value of 1–4 (up/down/left/right).
    • If no key is pressed, it sends command 0 (stand still).
    • It only sends a command when it’s different from the last one, to avoid spamming cloud variable updates.

      

    In summary, our AI needs to:

    • Send "my team" messages with movement commands (0 to 4).
    • Send "shoot donut" messages at the right time.

    That’s it! Once we can send those messages, we can fully control the truck without touching the keyboard.

     

     
     

    Step 3 - Remove the Key Press Related Code

     

    Let’s begin building our AI by reusing the manual controller’s loop, but deleting all the blocks related to key presses.

    We end up with this stripped-down version:

    a9892099-e063-41e4-8c87-7332c49bab8c-image.png

    Now we have a basic framework that can send commands. Next, we’ll let it pick commands at random.

     
     

    Step 4 - Set a random new command

     

    To make the truck move randomly, just pick a number between 0 and 4.
    Each number means:

    • 0 → stand still
    • 1 → move up
    • 2 → move down
    • 3 → move left
    • 4 → move right

    Use the pick random block like this:

    de138734-7a34-424e-984c-f7de5e83e789-image.png

    This alone is enough to make the truck wander.

     
     

    Step 5 - Add a Short Wait

     

    Without a delay, the loop may send hundreds of commands per second, which can overwhelm the cloud server or cause lag.

    Let’s slow it down by adding a wait block. One second is a good starting point:

    02094c89-ddf6-436a-a69c-61f45423525e-image.png

    Now the AI will choose a new move every second.

     
     

    Step 6 - Test the AI By Yourself

     

    Now it’s time to test! You can run two copies of your game in your browser to simulate two AIs playing against each other.

    Here’s how:

    1. Open two browser windows side by side.
    2. Open your remixed project in both windows.
    3. In browser A:
      • Click the green flag
      • Click Create Game
         
    4. In browser B:
      • Click the green flag
      • Click Join Game using the same session ID
         
    5. In browser A:
      • Click Start Game

    Now both trucks will begin moving randomly!

    Here’s what that looks like:

    randomwalk.gif

    This is a working AI. It’s not smart, but it’s alive. And now that you’ve built this, you’re ready to level up and give your truck a brain.

     
     
     
     
     
     
     
     
     

    Version 2 - Random Targets (Difficulty: 3)

     

    In the second version of our AI, we’ll give it a bit more purpose: instead of randomly pressing movement buttons, it will now pick a random target location and attempt to move there.

    This small change makes the AI appear more intentional, even though it’s still completely blind to rewards, opponents, or obstacles. In future versions, we’ll replace the randomness with smarter decision-making.

     
     

    Step 1 - Prepare for the new version

     

    We will duplicate the code from Version 1 and modify it.

    1. Detach the old random command block.
    2. Keep the basic loop and message-sending logic.
    3. Remove the block that picks a random number (0–4).

    The structure should now look like this:

    71ec534b-b736-49c8-9a77-87b1f496b2b5-image.png

     
    Don’t forget to disconnect the existing code from version 1. Otherwise it will keep sending random commands.

     
     

    Step 2 - Initialize with a random target location

     

    We’ll choose a random position on the stage as our target. Use two new variables: target x and target y. These should be initialized before the loop starts.

    Make sure the coordinates are within the stage boundaries:

    fa38b795-4a5b-4da6-a0b8-eb50edb913cc-image.png

     
     

    Step 3 - Calculate X and Y Distances

     

    To move toward the target, the AI needs to compare the truck’s position to the target’s position.

    You can use the following sensing block to get the X and Y coordinates of the truck. Make sure to reference the correct clone ID, which matches the player’s my team value.

    f35740ea-5ea3-4b98-91a0-22ebd7809c30-image.png

    At the start of each loop iteration, calculate and store the horizontal and vertical distances:

    0ebcb715-3054-4c09-8eb5-dc87432509cd-image.png

     
     

    Step 4 - Pick a New Random Target Upon Arrival

     

    If both distances are small (e.g. less than 20), the truck is close enough to its target. In that case, we’ll pick a new random target.

    6cb1da1c-520f-46d2-99b5-077bfaefac29-image.png

     
     

    Step 5 - Compare Distance X and Distance Y

     

    To decide whether to move horizontally or vertically, we compare the absolute value of the distances. Whichever is larger becomes the axis we move along.

    fb8431e1-ab46-4efc-a886-0a0a652cc005-image.png

     
     

    Step 6 - If Horizontal Distance is Larger

     

    If the distance is wider horizontally, then we move left or right depending on whether the truck is to the left or right of the target.

    5f1742f2-4c6a-4237-a40c-10efa05019d7-image.png

    This version of the AI will go horizontally first in this case.

    To decide left or right, check the sign of distance x:

    6b314471-5e49-4e2c-aa52-5eb4b2a480cf-image.png

     
     

    Step 7 - If Horizontal Distance is Smaller

     

    Otherwise, vertical distance is larger, so we’ll go up or down based on the sign of distance y:

    f5d92b4e-08bf-4f7e-b627-b8540e51459b-image.png

     
     

    Step 8 - Test with No Trees

     

    To test if our AI is working properly, we will make some adjustments to the project:

    Remove Trees

     
    In the Setup sprite, change the tree count to 0. This is because our truck can not avoid trees yet, so it would get stuck at a tree forever.

    30fec463-c3e5-420d-ae13-90094e0977d6-image.png

     

    Display variables

     
    Show these 4 variables on top of the stage, so we can check the truck’s movement against these variables:

    a3693fa6-a446-47fc-b850-426a0c14d22f-image.png

     
    Now run 2 instances side by side. You’ll see the trucks moving directly toward randomly chosen spots:

    randomtarget.gif

     
     

    Step 9 - Fix the Deadlock Issue

     

    You might notice that sometimes a truck gets stuck at the target, going back and forth near the target point but never switching to a new target.

    Here’s what that looks like:

    stuck.gif

     
    Can you think about what the reason is?

     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     

    The reason for this issue is the wait time in the loop. Here’s what’s happening:

    • Truck is 30 steps from the target → moves forward
    • The truck moves 80 steps in one second
    • It overshoots → next time it’s 50 steps away, but on the opposite side
    • This repeats endlessly

     

    ✅ The Solution:

    Lower the wait time. Set the wait block to 0.2 seconds or even smaller. This way, the AI updates its movement more frequently, and doesn’t overshoot as easily.

     
     
     
     
     
     
     
     
     

    Version 3 - Random Targets or Attacking (Difficulty: 3)

     

    In this third version of our AI, we add the ability to switch between two behaviors:

    1. Wandering to a random location (as in Version 2);
    2. Attacking the opponent truck directly.

    This change brings the AI to life. It now uses the second message type, shoot donut, and can actually cause the game to end, unlike before where both trucks wandered forever.

     
     

    Step 1 - Refactor the Code for Random Target

     

    Start by duplicating the AI code from Version 2.
    We’ll extract all the logic related to reaching random targets into a custom block called wander.

    This simplifies the main loop to:

    ad44f943-2bce-4f15-8f45-d05571f345b8-image.png

    And the wander block contains the logic we moved:

    ab3972da-4183-48ba-9918-3262bf8222fd-image.png

     
     

    Step 2 - Define the mode

     

    The AI can now be in one of two modes: "wander" or "attack". We’ll create a new variable mode, and initialize it to "wander":

    1522a61a-205c-4309-8014-e152c279b067-image.png

     
     

    Step 3 - Switch to “attack” mode

     

    Instead of picking a new random target after reaching one, we now switch to attack mode:

    bc4952a3-28c2-4b52-9d22-7b711f58e037-image.png

     
     

    Step 4 - Define the “attack” Block

     

    Define a new block “attack” to contain the logic of attacking the opponent.

    Then, in the main loop, we’ll now check the mode before deciding which behavior to run:

    d6eb7056-676d-4968-af72-c8fb037760c6-image.png

     
     

    Step 5 - Calculate Distance to Opponent

     

    Inside the attack block, we calculate the X and Y distance to the opponent truck using clone ID 3 - my team: For example, if my team is 1, then the opponent’s ID is 3 - 1 = 2.

    5b997cfe-7d12-4452-bad5-e9fb5b76385d-image.png

     
     

    Step 6 - Check If We can make a shot

     

    We are ready to shoot if the opponent is aligned horizontally or vertically with our truck (i.e., the distance in the X or Y direction is less than 15):

    8d3f1204-07fc-4dcf-bca5-4b727537541b-image.png

     
     

    Step 7 - Move to Align with the Opponent

     

    Let’s work on the logic to move to the target first, since we already have code doing similar things.

    We can first duplicate the logic from the “wander” block, which looks at whether the vertical or horizontal distance is larger and turns the truck accordingly:

    a45cb1ae-574f-485e-8b39-91a6d72d5964-image.png

     
    However, we will make one change: when the horizontal distance is larger, we should move our truck vertically, since it is faster to align horizontally to make a shot.

    For example, in this situation below, we should move the yellow truck down, then fire the shot horizontally:

    b2835bde-144f-4e6c-b1a8-8ce4806a259d-image.png

     
    The code change is very simple. We just need to swap the 2 “if-then-else” blocks:

    a78657c0-2af5-459f-89c6-050d8af47d3e-image.png

     
     

    Step 8 - Turn to the Opponent

     

    To shoot at the opponent, we need to first turn our truck towards it. Let’s define a new block turn to opponent. It turns out this is exactly the same logic we used for moving the truck towards the target position:

    67b82d3e-ad4c-4d5c-b19c-1d990ed01d2d-image.png

     
    We will use it in the “attack” logic:

    ccf8541c-9ecd-4537-ae03-07f89d220d3c-image.png

     
     

    Step 9 - Send out the movement command

     

    The turn to opponent block sets the command, but doesn’t send it. So send it now:

    3ecc2613-4a6e-4321-b064-a24e4a8251e1-image.png

     
     

    Step 10 - Take a Shot

     

    After turning, wait briefly so the truck finishes its turn, then fire the shot:

    e6918415-843e-491e-ab54-c1058936572f-image.png

     
     

    Step 11 - Switch back to “wander” mode

     

    After firing, the AI goes back to wander mode and picks a new random location:

    1c398e36-0844-43ac-8619-f8f63ec72210-image.png

     
     

    Step 12 - Testing

     

    Keep trees disabled in the Setup sprite.
    Show the mode variable on screen to visualize what the AI is doing.

    Here’s how it looks in action:

    attack.gif

     
     
     
     
     
     
     

    Improvements

     

    Version 3 completes the core loop of wander → attack → wander, allowing the game to reach an actual ending. But it’s still a pretty weak AI. Let’s look at a few obvious improvements.

    ✅ 1. Smarter Target Switching

    Currently, the AI only switches to attack mode after arriving at a random target. But it may have had a clear shot on the opponent midway through wandering.

    Fix: Constantly check if it’s aligned with the opponent, even during wander, and switch to attack instantly if possible.

     

    ✅ 2. Dodging After Attacking

    After shooting, the truck just picks a new random target — which might keep it in the line of fire.

    Fix: After firing, pick a target that’s not in the same row or column as the opponent.
    Or define a third mode: escape, and cycle like this:
    wander → attack → escape → wander …

     

    ✅ 3. Combo Firing

    Once the AI aligns with the opponent, it only fires one shot.
    But it may be better to fire multiple donuts before wandering off.

    Fix: Add a cooldown timer and allow burst fire.


    These enhancements will make your AI more competitive — especially against another AI using the same version.

    In Part 2 of this tutorial, we’ll teach the AI to avoid obstacles and collect power-ups.

    1 Reply Last reply
    0
    • CreatiCodeI CreatiCode pinned this topic on

    Hello! It looks like you're interested in this conversation, but you don't have an account yet.

    Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.

    With your input, this post could be even better 💗

    Register Login
    Reply
    • Reply as topic
    Log in to reply
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes


    • Login

    • Don't have an account? Register

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • CreatiCode