First, thanks so much for Code Combat. I’m working on changing careers by learning how to code. I’m fairly new to coding, so I’m sure there is a simple answer to this question that I’m just not seeing.
On “Patrol Buster”, I wrote a code where the warrior kills each enemy and returns to the center of the map. It works fine, but I keep getting an “Unexpected Token” error. It has to do with “dead”, but the code works. I tried re-writing several different ways using else, elif, and such, but I can’t figure it out. Below is my code, thanks for the help!
loop:
enemy = self.findNearestEnemy()
if enemy:
self.attack(enemy)
if enemy dead:
self.moveXY(35, 30)
Well, dead enemies aren’t returned by findNearestEnemy, so every “enemy” you see is alive.
When there’s no nearest enemy is because there are no enemies alive on the map, so you can just add an else: instead of if enemy.health == 0:.
It still sees a dead enemy as a target, but the target is null. I get an error saying “Target is null, is there always a target to attack?”
I’ve tried different versions of else commands, but I can’t figure out exactly what it’s looking for to stop targeting a dead enemy and move to the next one.
You’re using Python which is sensitive to white-space, in order for the if statement to determine whether or not the attack method is called, it needs to be indented properly:
loop:
enemy = self.findNearestEnemy()
if enemy:
self.attack(enemy)
else:
self.moveXY(...)
Otherwise you have:
if enemy:
# do nothing
self.attack(enemy) #always try to attack the enemy variable.
This is not true for example in JavaScript. The following is a totally valid JavaScript-Programm, but do you know what’s going on in there?
Bad Indentations
loop{var items = this.findItems(); var best = null; var value = 0; for(var i = 0; i < items.length; i++){if (items[i].value > value){best = items[i]; value = best.value;}} this.move(best.pos);}
Better is
Good Indentations
loop{
var items = this.findItems();
var best = null;
var value = 0;
for(var i = 0; i < items.length; i++){
if (items[i].value > value){
best = items[i];
value = best.value;
}
}
this.move(best.pos);
}
“Hi, I need help” . . . doesn’t get anyone very far…
What kind of help? What is wrong? What have you tried? what code did you use and what did it do or not do that you did or didn’t expect?
(Read the FAQ before posting so you will have an idea of what to post and how to do so if you include code.)
Hey this is Luke Patterson you, I started coding a month ago, and have gotten to backwoods forest, I dont know if this is right but in the code, I dont think its necessary to move to the enemy. I think you should let them come to you then kill them. Heres the code that I did:
loop:
enemy = self.findNearestEnemy()
# If there is an enemy, attack it!
if enemy:
self.attack(enemy)
self.attack(enemy)