Itβs time for 4 - Loops π
π Repeating Actions with while
Loops
A while
loop lets your robot repeat actions as long as a condition is true β just like an if
statement that keeps checking over and over.
while (getEnergy() > 50) {
forward(100);
back(100);
}
This bot will move back and forth while it has energy above 50.
βΎοΈ Infinite Loop for Main Behavior
Robocode bots often use an infinite while (true)
loop for their main logic:
public void run() {
while (true) {
scan();
forward(50);
turnRight(30);
}
}
This keeps the bot active for the entire round.
β Be Careful!
If the condition in your while
loop never becomes false, it can go forever. Thatβs great for behavior loops, but not for checks that should eventually stop.
while (getGunHeat() > 0) {
turnGunRight(5); // Keep turning until gun is cool
}
π§ Think Like a Loop
- Start with a condition (like an
if
) - Repeat whatβs inside
{}
until the condition is false
while (enemyCount > 0) {
scan();
fire(2);
enemyCount--;
}
Looping ends when no enemies are left.
Navigation
β¬ οΈ Back: Truth Tables β‘οΈ Next: Reactionary Logic