In Sarven Rescue, I set a series of flag commands to control my character. The black flag was supposed to control combat. (See code below) I expected combat loop to continue until the enemy were all defeated. Instead, the character would attack once and then quit. I finessed the level by dropping multiple flags for combat.
Can I create a secondary loop inside the “if enemy:” statement? How do I do it? I tried “while enemy:” but that was an infinite or a very slow loop.
loop:
black = self.findFlag("black")
if black:
self.pickUpFlag(black)
enemy = self.findNearestEnemy()
if enemy:
self.attack(enemy)
It is not the clean programming option, you can create a loop but you have to continuously update enemy inside the loop.
enemy = self.findNearestEnemy()
while enemy:
self.attack(enemy)
enemy =self.FindNearestEnemy()
To write a clean program, start with your basic loop
loop:
find enemy
if enemy:
attack enemy
then add extra code to cover exceptional cases
loop:
find flag
if flag:
pick up flag
# Whas this "if flag" enough to cover the exceptional case?
# Good, then back to my original behaviour
find enemy
if enemy:
attack enemy
I don’t quite understand the “clean” option, but I see where I made my mistake with the “While enemy:” statement.
A few more weeks cogitating and I should get the better process as well.
The idea is that you should only have to write code once. If you create 2 blocks of code that both had to handle the same situation, then you may have trouble in the future.
In your code, what happens if you do not have black flag? You will still have to kill enemy in that case.
So you code will have to be:
loop:
if black:
code to kill enemy here
# need to kill enemy if no black flag also
code to kill enemy here