Acknowledged. This will be fixed soon. Thanks
Best posts made by info-creaticode
-
RE: Some avatars aren't shown to select until searched for
-
"Remote Edit" - 2 users working on the same project remotely
Introduction
When 2 users are using their own computers, they can collaborate on the same project remotely, using a new feature called “remote edit”. This is a fun experience that allows 2 people to write code together. When one person makes a change, such as adding a block or changing an input value, the other person sees the change right away. This is similar to how 2 people can edit the same Google Doc at the same time.
How to start a “remote edit” session
Here are the 4 steps for two users to start a remote edit session:
-
Owner User shares a new project. There are a few ways to share a project, such as sharing with everyone, sharing with friends only and sharing unlisted (no one can see it unless they have the project URL). The owner user then gives the project URL to the guest user, maybe through email or text message.
-
Guest User opens the project and clicks “Look inside” to open the project in the playground. The guest user selects the “Edit” menu on top, and then select “Request to edit”, then wait for the owner user to accept the request.
-
Owner User receives a request from the guest user, and clicks “Accept” button.
-
Guest User will receive the approval, and their project will automatically reload. This is to make sure the guest user starts with exactly the same project content as the owner user.
Here is a screen recording for what the 2 users would see on their computers (the left half is for the owner user and the right half is for the guest user):
After the 4 steps above, both users will be able to see and change the same project at the same time.
Making Changes
After the remote edit session has started, both users can make changes, such as adding/removing blocks, changing input values, etc. When one user is changing a block, that block will become greyed out on the other user’s screen, which indicates the remote user is making some changes. Users should try to avoid making changes to the same block at the same time, since the changes may conflict with each other, and only one change will be saved.
Limitations
There are some limits put in place to ensure the 2 users are always in sync:
-
No New Sprites: Currently, neither user can add new sprites once the session has started, and the “add sprite” button is hidden. Therefore, it is suggested that the owner user first creates all the sprites they need before starting the session.
-
Only Owner can save the project: Only the owner user can save the project, since that user still owns the project. The owner user should save the project whenever some important changes have been completed.
How to end a “remote edit” session
To end a “remote edit” session, either the owner or the guest user can click the red “End” button at the bottom.
Best Practices
Here are some suggestions on how to make use of this feature effectively:
-
Voice Communication: When the 2 users are not in the same room, it is better to have a voice communication channel, such as a zoom meeting or a phone call on the side. This can make it much easier for the 2 users to decide who will do what.
-
Division of Work: Although these 2 users can both make changes at the same time, they can not change exactly the same block at the same time. For example, if one user is updating the input parameters in a block, and the other user is deleting that block, then the result may be unexpected. It is recommended that the 2 users work on different blocks or stacks of blocks to avoid conflicts.
-
-
RE: What is this?
Please give it a try. I would love to hear your feedback. It is always a challenge to know when to give out the answer and when to hold it back, even for human teachers. Our current setting is to make the AI keep providing more hints when the user struggles. Hopefully, that will be good enough for most situations.
-
Wishlist for New Models
If you are looking for a particular 3D model that is not in our library, please reply to this topic. If you can include an example picture of it, it would be more clear what you are looking for. We will try to fulfill these requests as best as we can. Please make sure you do not submit duplicate requests by searching for it first.
Thanks
CreatiCode Support -
How to record and share screen recordings as gifs
Introduction
When you need to explain how a project should work, the best way is to make a screen recording of the stage. This short article will explain which tools you can use to record the screen, and also how to share the gif file to get a URL for it.
Screen Recording on Windows
If you are using a Windows computer, we recommend a free tool named “ScreenToGif”, which you can download here: https://www.screentogif.com/
Here is a short video explaining how to use it: https://www.yo utube.com/watch?v=ELfCBzN1Mtc
Screen Recording on Macbook
If you are using a Macbook, you can use a free tool called “Giphy Capture”: https://giphy.com/apps/giphycapture
Here is a short video showing how to use it: https://www.yo utube.com/watch?v=m-4cJMBGfS4
Share your gif file
Once your gif file is ready, you can share it this way:
-
Go to the “My Stuff” page at https://play.creaticode.com/mystuff, and make sure you are logged in.
-
Select “My Files” tab on the bottom left
-
Click the “+Share a New File” button on the top right
-
In the pop up window, click “Click to upload file”, and then select the gif file from your computer.
-
Click the green button that says “upload and share with the CC Attribution license” at the bottom.
After that, you will see the new file in the list of files, and then you can click “Copy file URL” button for that file, which will copy the URL to the clipboard, which would look like this: https://ccdncreaticodecom.b-cdn.net/user-files/BfemEPCxatY6MMAPs/castfireball.gif
-
-
RE: Some avatars aren't shown to select until searched for
FYI this issue is fixed now.
-
Magic Wand Selector in the Costume Editor
Introduction
In the costumer editor, when the costume is in bitmap mode (as opposed to vector mode), you can use the magic wand tool to select an area with similar colors, then delete the designated area or fill it with a new color.
Making a Selection
To make a selection, you simply need to select the magic wand tool, then click on the area you would like to select. It can be of any shape, and may even contain holes in it:
Behind the scenes, it uses a “flood fill” algorithm to expand the selected area into neighboring points, so long as their colors are similar to the point you have clicked.Note that if your computer is slow or if the costume is big, then it will take longer for this tool to determine the selected area.
Changing the Tolerance Threshold
When the magic wand is selected, you can specify a tolerance threshold value. Its value is between 1 and 255, and by default, it is 5. This value represents how much difference in color it would tolerate when it tries to expand the selection area:
- When the value is low, it will make sure the selected area only contains points very similar to the point you have clicked;
- As the value increases, it will include more points even if they are more different from the starting point.
As shown, when you change this value, the selected area will be updated automatically:
Delete or Fill the Selected Area
After you have made the selection, there are 2 operations you can do with those points:
- You can click the “Delete” button or press the DELETE key to delete all of those points;
- You can also pick a color from the “Fill” dropdown, then click the “Fill” button to fill the selected area with that color.
-
RE: Current error with accessing the website
Hi all,
Sorry there was an outage on our platform earlier this morning. Sorry about the inconvenience. Now we are back online.
CreatiCode
-
RE: Code block presets?
You are right. We should allow users to submit new extensions.
However, the code snippet library should be more like backpack than extension, since it will allow users to modify the code blocks after a snippet is imported. If it is an extension, then users won’t see its implementation and also won’t be able to customize it.
-
RE: Need help and ideas
Maybe you can try these ideas?
- Click the trash bin again to make it stop yelling
- Make random garbage items fly out of the trash bin
- Drag and drop garbage items into the trash bin
- Make the trash bin move to random places on the stage
- Add multiple clones of the garbage bin of different looks.
Latest posts made by info-creaticode
-
RE: New block -- "When stop sign pressed"
This project shows a dog saying hello right? So when it says Hello, you can press the button to update the preview. It will become this:
-
RE: Checking back on notifications progress
Most likely, we will implement a system similar to MIT Scratch’s “messages” (https://scratch.mit.edu/messages). But this is currently behind other more urgent tasks.
-
RE: New block -- "When stop sign pressed"
If it is not working, can you share the project link? And you pressed that button while the project is running?
-
RE: Add a block to point at closest clone/ closest clone of a certain sprite
We have added 2 new blocks to make it easier to work with clones. Please check them out there:
https://www.forum.creaticode.com/topic/2032/2-blocks-to-scan-for-clones
-
2 blocks to scan for clones
Introduction
In game projects, clones are commonly used to create objects like enemies, obstacles or powerups. However, it is not easy to scan for them in our code, which is often needed when we need to do something clever, such as “find all the enemies near me”, or “check if I have a clear line of fire”.
In CreatiCode, every clone has a clone ID, and the original sprite can also be treated as a clone with an ID of “originalsprite”. There are 2 new blocks that can be used to scan for clones of a given sprite: one is simply based on distance from this sprite, and the other based on a scan area.
Find Clones by Distance
You can use this sensing block to find clones of a given sprite within the given distance from this sprite, and save their information in the given table:
Notes:- You can pick any sprite, even this sprite itself
- The original sprite can also be treated as a clone, with a clone ID of “originalsprite”.
- The distance is the direct-line distance between this sprite and each clone of that sprite, calculated using their x and y positions.
- If any clones are found within this distance, they are listed in the table in order of increasing distance (nearest first). The table will always have at least 4 columns: clone ID, x, y and distance. If the clone has any private variables, they will also be added as additional columns.
Example
Here is an example program showing how it works: play.creaticode.com/projects/685e804081a45ef495ae5fdf
In the Tree sprite, we create 5 clones of the tree. Each clone will go to a random position, generate a “secret” that is private to itself, and then say its clone ID to identify itself.
So on stage, you will see 6 tree objects like this:
Now, in the Truck sprite, we can use this sensing block to find trees that are with 100 units distance from the truck:
Then we can look at the content oftable1
:
As shown, there are 3 clones whose distance is less than 100 from the truck.The nearest clone is the original tree sprite, which is at x of 0 and y of 0. It is about 64.85 units away from the truck.
The second nearest clone is the one with ID of “clone_3”. It is a bit further away, and its
secret
is 78.You can try to change the distance threshold or drag the trees around, and observe how
table1
changes. For example, when the distance threshold is very large, all clones should be listed in the table; and when it is very small, the table should become empty.
Detect Blocking Clones in the Forward Direction
Another very common question we need to ask is whether there are obstacles in front of our sprite, which may block our sprite’s movement or block the shots it fires.
One way to do this checking is to use the block above to find all clones on the stage, and then check the position of each of them. But the calculation become more complex when the sprite is facing an angle (not straight left/right or up/down).
Instead, you can use the following block for this task, which defines a rectangle “scan area” in front of this sprite, and list any clone of the given sprite it finds in this area in the given table.
Notes:
- You can pick any sprite, even this sprite itself
- The original sprite can also be treated as a clone, with a clone ID of “originalsprite”.
- The distance is going forward along this sprite’s current direction. So if this sprite is facing 45 degrees, you can imagine it moves forward along this direction for 200 units, and check if there are any clones that’s 20 (half of 40) units away on the left or right side.
- If any clones are found within this distance, they are listed in the table in order of increasing distance (nearest first). The table will always have at least 4 columns: clone ID, x, y and distance. If the clone has any private variables, they will also be added as additional columns.
Example
Here is an example program showing how it works:
play.creaticode.com/projects/685e928081a45ef495ae82c0
The truck is facing -30 degrees (upper left direction). In the Tree sprite, 2 clones are created in a similar way.
You can drag them to a formation like this:
The original tree sprite is directly on the forward path of the truck. The clone 2 is slightly blocking the path on the right side, and clone 1 should not be a blocker.
Now, suppose we run this block in the truck sprite:
The detection area will be 200 by 70 in front of the truck:
The table1 will contain 2 rows:
Explanation:- The center point of both the original sprite and the clone 2 are inside the red rectangle, so they are included in the result table.
- For clone 1, although its edge touches with the red rectangle, its center point is outside the rectangle. Since we only look at the x/y position of each clone, and not their size, the only thing that matters is their center point’s position.
Therefore, when deciding the width of the detection area, you need to consider the width of both this sprite and the clones.
Now, suppose we change the block to use width of 100, then the table will contain 3 rows, because the detection area now includes the center point of the clone 1 as well:
You can try to play with different truck direction, tree position, distance and width settings to understand how this block works better. -
RE: How to find "If Shift key pressed"
This change has been released. Please refresh your playground to get latest code.
-
Game AI for <Candy Truck Battle> - Part 2 (Difficulty: 5)
Introduction
In part 1 of this tutorial, we built a basic AI controller for the game. That AI could already move the truck to random locations, and even seek and attack the opponent.
In this second part, we’re going to supercharge our AI! We’ll add two major new skills: collecting power-ups and avoiding tree obstacles. With these upgrades, our AI will become a much tougher competitor in battle.
Here is a demo of what we’ll be building:
Version 4 - Collecting Powerups (Difficulty: 4)
To get our truck to collect powerups, it first needs to know where they are. Then, it has to drive over to them. A key part of the logic will be deciding when to go for a powerup versus when to keep attacking the opponent.
Step 1 - Duplicate the Previous AI Code
We’ll be building on the AI controller we made in Part 1 (Version 3). Go ahead and open that project, and then save a copy of it. This way, you’ll always have the original version to go back to if you need it.
Step 2 - Check for Powerups
To collect powerups, our AI first needs to know that they’ve appeared on the map. It only makes sense to change the truck’s behavior after a powerup is available. The best spot for this check is right at the start of our main
forever
loop.Let’s create a new custom block and name it
check powerups
. Important: Make sure to check the box for “Run without screen refresh.” This gives our code a nice little speed boost.
And we will place this new block at the beginning of the main loop:
Step 3 - Check Our Life Count
Remember, there are two types of powerups in the game:
- Sugar: Increases our truck’s life count (up to a max of 3).
- Gas: Boosts our truck’s speed (up to a max of 120).
It makes sense to prioritize survival. If our truck has fewer than 3 lives, getting a Sugar powerup should be the top priority. Let’s start by adding a check for that.
Note that the☁ my lives
variable keeps track of the life count for our truck, which is identified by themy team
ID. This sensing block is very handy when you need to access any private property of a clone so long as you know its ID.
Step 4 - Look for Sugar Powerups
If our truck needs health (meaning it has less than 3 lives), it’s time to scan the area for any Sugar powerups. We can do this using the special
find clones of
sensing block.
This block is incredibly useful. It searches for all visible clones of a specific sprite within a certain distance. Since we want to find Sugar anywhere on the map, let’s use a large distance like 1000. Any Sugar clones it finds will be listed in thetable1
variable.
Step 5 - Check If Table1 is Not Empty
If the
find clones of
block successfully located one or more Sugar sprites, it will add them as rows totable1
. So, to see if we found anything, we just need to check if the number of rows intable1
is greater than 0.
Step 6 - Update Mode and Target Location
Okay, we’ve found a Sugar powerup! The next step is to drive to it. The
table1
is conveniently sorted by distance, meaning the very first row always points to the closest clone. For example, this screenshot shows that one Sugar clone was found. It has a clone ID of1
, is located at X: 160 and Y: -65, and is 96.43 units away from our truck.
Now, we could create a whole new mode like “collect sugar,” but there’s a clever, simpler way. We can just reuse our existingwander
mode! All we have to do is update thetarget x
andtarget y
variables with the location of the Sugar item. The existing code in thewander
block will then automatically navigate our truck right to it.
Step 7 - Return from “check powerups”
Once we’ve spotted a Sugar clone and decided to go for it, our job inside the
check powerups
block is done for this cycle. There’s no need to continue and check for Gas powerups. We can use areturn
block to exit the custom block immediately.Pro Tip: It’s a common misunderstanding that the
return
block is only for reporter blocks (the ones that return a value). You can also use it in regular stack blocks like this one to simply stop the block from running any further. Its return value is just ignored. This is equivalent of using thestop [this script]
block.
Step 8 - Look for Gas Powerups
If our truck is at full health, or if there were no Sugar powerups to find, the code continues. Now we can check for Gas powerups. But, there’s no point in grabbing a Gas powerup if our speed is already maxed out at 120. So, let’s first check our
☁ my speed
variable.
Step 9 - Complete the Rest
The logic for finding and collecting Gas clones is nearly identical to what we just did for Sugar. See if you can build the rest of the code yourself! It’s great practice.
Here is the complete solution for thecheck powerups
block:
Step 10 - Test This Version
Time to test our new powerup-collecting AI! To focus just on this new skill, let’s keep the
tree count
at 0 for now (you can change this in the Setup sprite).It’s also really helpful to make the
table1
variable visible on the stage. This way, you can see exactly when the AI finds a powerup.One last tip for faster testing: in the Sugar sprite, you can shorten the time it waits before reappearing. For example, try changing the random wait to between 3 and 9 seconds.
Now you can test your AI by opening the project in two browser tabs and letting them battle. It should look something like this:
Version 5 - Avoiding Trees (Difficulty: 5)
Now for a real challenge: obstacle avoidance! Right now, our truck will just drive straight into trees and get stuck, completely stopping it from chasing the opponent or grabbing powerups. We’re going to fix this by teaching our AI how to detect when a tree is in the way and then plot a “detour” to get around it.
Step 1 - Export Version 4 for Backup
First thing’s first. Let’s make a backup of our working powerup-collecting version. Export your Controller sprite as a file (it will be named something like
sprite3
). This way, if anything goes wrong, you can easily import this version and start again.
Step 2 - Define a New Reporter Block
To avoid trees, our AI first needs a way to “see” if its path is blocked. We’ll create a new custom block that can answer a simple question: “Is this direction blocked?”. Let’s name it
direction is blocked
, and it will take thecommand
as an input. Make sure to select “Run without screen refresh” and define it as a reporter block. A reporter block returns a value; ours will return1
if the path is blocked and0
if it’s clear.
Step 3 - Discussion On How to Detect Tree Obstacles
Before we jump into coding, let’s talk strategy. How can our Controller sprite, which only sends commands, know if the Truck sprite is about to hit a tree?
In standard Scratch, you might try a “ghosting” technique: quickly move the sprite forward, check for a collision, and move it back before the screen refreshes. But that won’t work here, because our Controller sprite and Truck sprite are separate. The Controller can’t directly move the Truck to test for collisions.
So, we need a different, more clever approach:
- We’ll temporarily move our invisible Controller sprite to the exact location of our Truck.
- We’ll point the Controller sprite in the direction we want to move.
- From that position, we’ll use a new sensing block to scan a rectangular “detection area” in front of the sprite to see if any trees are inside it.
Let’s implement this idea in the next few steps.
Step 4 - Move the AI sprite to the Truck
First, let’s get the current X and Y position of our truck using its
my team
clone ID. Then, we’ll use ago to x y
block to instantly move our Controller sprite to that same spot.
Remember, the Controller sprite is invisible, so you won’t see anything change on the stage. The whole point of this move is to establish a starting point for our tree-detection scan.
Step 5 - Face Upward if Command is 1
If the
command
we’re checking is1
(move up), we need to check for trees above the truck. To do this, we’ll point our Controller sprite upwards (direction 0). This step is crucial because the detection area we’re about to create is always relative to the direction the sprite is facing.
Again, we’re just using the invisible sprite’s direction to set up our detection area.
Step 6 - Handle the Other 3 Directions
Similarly, we’ll handle the other three possible commands (
2
for down,3
for left, and4
for right), pointing the Controller sprite in the corresponding direction each time.
Step 7 - Detect Tree Clones in a Rectangle Area
With our Controller sprite now at the truck’s location and pointing in the direction of intended movement, we’re ready to scan for trees. We’ll use the
find clones of sprite in rectangle
block. Here’s how this powerful block works for our setup:
Explanations:- We are looking for visible clones of the Tree sprite. The original Tree sprite is hidden, so this check will correctly ignore it.
- The rectangle is defined relative to the Controller sprite’s forward direction. So if the
command
is1
(up), the Controller is facing upward, and the rectangle will extend 60 units forward and expand 90 units wide, like this:
- We will store information about all clones found in the
table1
variable.
Feel free to fine-tune thedistance
andwidth
values. Think of distance as how far ahead the AI can “see,” and width as its “peripheral vision,” or how wide you want to scan.If the center of any Tree clone is inside this rectangle (i.e. its center point falls into this rectangle), it will be listed in the table, which includes columns for clone ID, x, y, and distance.
If more than one clone is found, the table will be sorted by distance, with the closest one listed first.
Step 8 - Check If Table is Empty
We don’t need the specific details of the trees, just whether any tree was found. So, we can simply check if
table1
has any rows. If the row count is greater than 0, a tree is blocking the path, and our block shouldreturn 1
. Otherwise, the path is clear, and it shouldreturn 0
.
Step 9 - Check if Command Direction is Blocked
Now we can put our new reporter block to use! Back in the main loop, right before we set the
new command
, we’ll calldirection is blocked
to check the path.Also, to make our AI more responsive and quicker to react to obstacles, let’s reduce the
wait
time in the main loop to0.1
seconds. This allows it to check for blockages more frequently.
Step 10 - Calculate a Detour Command
If our check finds that the intended direction is blocked, we need to calculate a detour. We’ll create another new custom block,
calculate detour
, to handle this logic. This block will figure out a new, unblockeddetour command
which will then temporarily override thenew command
.
Step 11 - Discussion on How to Make a Detour
So, how do we calculate a smart detour? There are many complex pathfinding algorithms, but we’re looking for a solution that is effective, fast, and simple to build.
Imagine the truck needs to get the Gas on the top right, but a tree is blocking the path to the right.
We have a few command options:new command
: The original, blocked command (e.g., move right).alt command
: The other direction towards the target. Since the Gas is also above the truck, moving up would be a good alternative.alt command 2
: The opposite of thealt command
. This is a backup plan if thealt command
is also blocked.back command
: The opposite of thenew command
. If all forward and side paths are blocked, our only choice is to back up to escape the “trap”.
Our strategy will be this: when we’re blocked, we will check these alternatives in order. Once we find a clear path, we’ll execute a two-step detour (e.g., move sideways for 1 second, then move toward the target for 1 second) before returning to our normal logic. This simple strategy will handle most situations very effectively. Let’s build it!
Step 12 - Initialize Detour
Inside our new
calculate detour
block, the first thing we’ll do is set up a couple of variables to manage the detour process:in detour
: A “flag” variable. We’ll set this to1
to signal that the AI is currently executing a detour.detour start time
: We’ll record the currenttimer
value here. This will help us time each step of the detour.
Step 13 - Calculate the Alt Command
Next, we need to determine the best alternative command (
alt command
). This command should still move the truck generally closer to its ultimate target.If our original
new command
was vertical (up/down), thealt command
should be horizontal (left/right). We can pick the correct horizontal direction by looking atdistance x
. Ifdistance x
is positive, the target is to the right, so ouralt command
should be4
(move right).
Similarly, if thenew command
was horizontal (left/right), thealt command
should be vertical (up/down). We can usedistance y
to decide whether to move up or down.
Step 14 - Calculate the Alt Command 2
The
alt command 2
is always the opposite of thealt command
. We can use a neat little math trick for this: since(left=3) + (right=4) = 7
, we can calculate the opposite by subtracting from 7. This logic works whether thenew command
was vertical or horizontal.
Step 15 - Calculate the Back Command
The
back command
is always the opposite of thenew command
. We can use a similar calculation based on whether the command is vertical or horizontal.
Step 16 - Take the Alt Command If Available
Now we’ll decide which detour path to take. Our first choice is always the
alt command
. We use ourdirection is blocked
reporter to check if that path is clear. If it is, we’ve found our detour! We’ll set up a two-step plan:detour command
: Set to thealt command
.detour command 2
: Set to the originalnew command
.
This means the truck will first move sideways, then try to resume its original path. Since we’ve found a plan, we can use a
return
block to exit thecalculate detour
script.
Step 17 - Take the Alt Command 2 If Available
But what if the
alt command
path is also blocked? This means obstacles are in front of us AND on one side. Our next best option is to tryalt command 2
(the other side). If that path is clear, we’ll set our detour plan to usealt command 2
first, followed by the originalnew command
.
Step 18 - Take the Back Command as a Last Resort
In the worst-case scenario, the paths forward, left, and right are all blocked. The truck is trapped! The only way out is to back up. We’ll set the detour plan to use the
back command
first, and then follow it up with thealt command
to try and steer around the trap.
Step 19 - Add a New Branch for Detour
Now we need to modify our main loop to actually execute the detour. When the
in detour
flag is set to1
, we need to bypass all our normal logic (checking powerups, finding the opponent, etc.). Instead, we will run a separate branch of code dedicated to the detour.The animation below shows how to restructure your main loop with an
if/else
block based on thein detour
variable. Notice that the block that sends the command to the truck is now outside and after theif/else
, so it runs in every situation.
Step 20 - Stop Detour in 2 Seconds
Inside the new “detour” branch of our
if/else
block, we’ll manage the two-step detour sequence. The whole detour will last for 2 seconds. By default, thenew command
will be ourdetour command
. If thetimer
shows that 2 seconds have passed since thedetour start time
, the detour is over. We’ll set thein detour
flag back to0
, so that on the next loop, the AI will go back to its normal behavior.
Step 21 - Switch to Second Detour Command in 1 Second
The detour itself has two parts. For the first second, the truck will follow
detour command
. After one second has passed, we’ll switch thenew command
todetour command 2
for the second half of the detour. This creates the “go sideways, then go forward” maneuver.
And that’s it! Our detour logic is complete. In short, when the AI “sees” a tree, it will now intelligently try to move sideways or even back up for a moment to get around it.
Step 22 - Test This Version
It’s time for the final test! Go to the Setup sprite and set the
tree count
to6
(or even more to make it really challenging). Run the project and watch how your AI truck now cleverly navigates around the trees instead of getting stuck. You can also speed up the powerup spawn times again for a more action-packed test.Here is a demo:
Further Improvements
This AI controller is already much smarter, but there’s always room for improvement! If you want to take your AI to the next level and win battles, consider these enhancements:
-
Smarter Attack and Dodge: Have you noticed your truck sometimes has a perfect shot lined up but decides to wander off instead? Improve the
attack
mode to recognize when it’s aligned with the opponent, take the shot, and then immediately move sideways to dodge any return fire. -
Strategic Powerup Denial: Right now, your AI only grabs powerups it needs. But what if your opponent is low on health and a Sugar powerup appears? A truly smart AI would grab that powerup just to prevent the opponent from getting it! Modify your
check powerups
logic to consider the opponent’s status, too. -
Don’t Waste Ammo: Firing donuts into a tree is a waste! Before shooting, you can use a similar detection method to the one we built for avoiding trees. Check if the line of sight to the opponent is clear. If it’s blocked by a tree, hold your fire and reposition.
-
Press the Advantage: When your truck is stronger (more lives, more speed), it should be more aggressive! Instead of firing one shot and then wandering away, why not make it stay in
attack
mode and keep firing as long as it has the upper hand?
These are just a few ideas to get you started. The best way to improve your AI is to watch it battle. What mistakes does it make? When does it get outsmarted? Every battle is a chance to learn and come up with your own unique strategies to build the ultimate champion -
RE: How to find "If Shift key pressed"
That’s the idea. It shouldn’t take long once we finish the other tasks ahead of it in the queue.
-
Game AI for Candy Truck Battle - Part 1 (Difficulty: 3)
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:
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:
-
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.
-
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:
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:
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: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:
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:
- Open two browser windows side by side.
- Open your remixed project in both windows.
- In browser A:
- Click the green flag
- Click Create Game
- In browser B:
- Click the green flag
- Click Join Game using the same session ID
- In browser A:
- Click Start Game
Now both trucks will begin moving randomly!
Here’s what that looks like:
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.
- Detach the old random command block.
- Keep the basic loop and message-sending logic.
- Remove the block that picks a random number (0–4).
The structure should now look like this:
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
andtarget y
. These should be initialized before the loop starts.Make sure the coordinates are within the stage boundaries:
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.At the start of each loop iteration, calculate and store the horizontal and vertical distances:
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.
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.
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.
This version of the AI will go horizontally first in this case.
To decide left or right, check the sign of
distance x
:
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
:
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.Display variables
Show these 4 variables on top of the stage, so we can check the truck’s movement against these variables:
Now run 2 instances side by side. You’ll see the trucks moving directly toward randomly chosen spots:
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:
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:
- Wandering to a random location (as in Version 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 calledwander
.This simplifies the main loop to:
And the
wander
block contains the logic we moved:
Step 2 - Define the
mode
The AI can now be in one of two modes:
"wander"
or"attack"
. We’ll create a new variablemode
, and initialize it to"wander"
:
Step 3 - Switch to “attack” mode
Instead of picking a new random target after reaching one, we now switch to
attack
mode:
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:
Step 5 - Calculate Distance to Opponent
Inside the
attack
block, we calculate the X and Y distance to the opponent truck using clone ID3 - my team
: For example, ifmy team
is 1, then the opponent’s ID is 3 - 1 = 2.
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):
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:
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:
The code change is very simple. We just need to swap the 2 “if-then-else” blocks:
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:
We will use it in the “attack” logic:
Step 9 - Send out the movement command
The
turn to opponent
block sets the command, but doesn’t send it. So send it now:
Step 10 - Take a Shot
After turning, wait briefly so the truck finishes its turn, then fire the shot:
Step 11 - Switch back to “wander” mode
After firing, the AI goes back to
wander
mode and picks a new random location:
Step 12 - Testing
Keep trees disabled in the Setup sprite.
Show themode
variable on screen to visualize what the AI is doing.Here’s how it looks in action:
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 toattack
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.