var flag = this.findFlag(flag);
var enemy = this.findNearestEnemy();
var item = this.findNearestItem();
var itemX = item.pos.x;
var itemY = item.pos.y;
loop {
// Find coins and/or attack the enemy.
// Use flags and your special moves to win!
if (this.distanceTo(enemy) < 10) {
if (this.isReady("power-up")) {
this.powerUp();
}
else if (this.isReady("bash")) {
this.bash(enemy);
}
else {
this.attack(enemy);
}
}
else if (item) {
this.moveXY(itemX, itemY);
}
}
The avatar goes out and kills the AI, but he won’t collect coins. What am I missing?
I don’t do Javascript, but I’m pretty sure changing if (this.distanceTo(enemy) < 10) to something like if enemy and (this.distanceTo(enemy) < 10) would be preferable.
Here are the things I can see off the top of my head:
You define all your variables outside the loop. This means that the variables will store only the first occurrence of such things. For instance, var flag = this.findFlag(flag); would return null, and your hero will not respond to any flags. Move your variables inside the loop.
Also, this.findFlag(flag); does not work. Use this.findFlag();.
You don’t check for an enemy in the first place. This could possibly break your code. Add an if(enemy) { before your code for attacking an enemy.
The way your code is written, your hero will never collect coins as long as there is an enemy. Fix that.
loop {
var flag = this.findFlag();
var enemy = this.findNearestEnemy();
var item = this.findNearestItem();
var itemX = item.pos.x;
var itemY = item.pos.y;
// Find coins and/or attack the enemy.
// Use flags and your special moves to win!
if (enemy) {
if (this.distanceTo(enemy) < 10) {
if (this.isReady("power-up")) {
this.powerUp();
}
else if (this.isReady("bash")) {
this.bash(enemy);
}
else {
this.attack(enemy);
}
}
}
else if (item) {
this.moveXY(itemX, itemY);
}
}
I added the if (enemy) statement to the attack lines and put the variables in the loop. Now my guy whacks the enemy because they are close, collects a couple coins, then just stops.
@ChronistGilver, I’m not sure how to fix it. Please explain?
loop {
var flag = this.findFlag();
var enemy = this.findNearestEnemy();
var item = this.findNearestItem();
var itemX = item.pos.x;
var itemY = item.pos.y;
if (item) {
this.moveXY(itemX, itemY);
}
else if (this.distanceTo(enemy) < 20) {
if (this.isReady("power-up")) {
this.powerUp();
}
else if (this.isReady("bash")) {
this.bash(enemy);
}
else if (enemy) {
this.attack(enemy);
}
}
}
So I put the variables in the loop, and he would still kill the enemy once, collect a few coins, then stop.
This code here, I put the if (item) first to see what would happen. Now he collects coins, but won’t attack the enemy.