Sarven Rescue help please

Rescue the peasant from the bandits and return her to the village.

Choose the path that suits you, avoiding patrols or facing them head on.

Potions will grant random effects–some good, some bad.

Feeling brave? Bonus if you can loot the ogre treasure chest.\

item = self.findItems()
enemies = self.findEnemies()

loop:
enemyIndex = 0
while enemyIdex < len(enemies):
enemy = enemies[enemyIndex]
enemy = self.findNearest(self.findEnemies())
item = self.findNearest(self.findItems())
if enemy:
if self.distanceTo(enemy) >= 10:
self.attack(enemy)
if self.isReady(“cleave”):
self.cleave(enemy)
enemyIdex += 1
if item:
position = item.pos
x = position.x
y = position.y
self.moveXY(x, y)
else:
self.moveXY(123, 13)
self.say(“follow me”)

Merged Doublepost

I can get my hero to move around the board. He will attack enemies while trying to find potions, but he will not kill all enemies in an area. he will kill some and then decide to find an item and then eventually kill an enemy again

Merged Doublepost

You have already been told how to present your code properly. Please do so.
If you do not remember it, look again in the FAQ.

item = self.findItems()
enemies = self.findEnemies()   
loop:
    enemy = self.findNearest(self.findEnemies())
    item = self.findNearest(self.findItems())
    if enemy:
        if self.distanceTo(enemy) < 5:
            self.attack(enemy)
            self.attack(enemy)
        if self.isReady("cleave") and self.distanceTo(enemy) < 5:
            self.cleave(enemy)
        else:
            if item:
                position = item.pos
                x = position.x
                y = position.y
                self.moveXY(x, y)

Sorry :frowning:
How can I get my character to keep attacking enemies? With my code above, he will attack for awhile, but many times does not totally kill off and enemy before moving on to search out an item.

I realize that I still have other issues as well. Namely that I haven’t figured out how to get him to the hostage and then get them to follow me and to kill the sand-yak, but I need to figure out what I’m doing wrong here first.

Thanks for any help.

1 Like

According to your code, he will only attack (or cleave) an enemy within 5 meters. This means that he will never attack enemies in an area, unless they come within 5 meters of him to start. (Once they are in 5 meters, he may chase them as attack will follow any given enemy).

A good rule of thumb is to have a default behavior with few or no conditions, but override or preempt special conditions. This means it will always do something, even if it is not the right thing. (Often times, figuring out how to do the right thing is easier to figure out how to do anything at all). Here’s an example of what I mean (forgive me, I code in JS):

if enemy:
    if self.distanceTo(enemy) <= 10:
        if self.isReady("cleave"):
            self.cleave()
    else:
        this.attack(enemy)

This isn’t always the way to do things, but it is how a lot of advanced code gets done. In the sample above, it will attack whenever it can’t cleave(). So, if there’s an enemy, attacking is the default action and cleave is a special circumstance. Hope that makes sense!

Thanks Fuzical. That makes alot of sense. :grinning:

Unfortunately, I still can’t get my code to work. I even deleted my code and started again trying to do it with flags and I that didn’t work.

I’m currently trying to do it with arrays and while loops but I know my code is way fubared for that. I shouldn’t even post this code because I know there are too are way too many problems with it. This code also gets back into the same problem before where I am not attacking always by using “else” but it keeps telling me its in unexpected token when I use it. I’m assuming you can’t use an “Else” in a while loop?

Is it possible to collect items and fight enemies with arrays and while loops?

     enemy = self.findNearestEnemy()
    item = self.findItems()
    itemNames = ['potion', 'chest']
    itemIndex = 0
    while itemIndex < len(itemNames):
        itemName = itemNames[itemIndex]
        self.move(item.pos)
        itemIndex = itemIndex  + 1
    if enemy:
            if enemy.type is "sand-yak" or enemy.type is "burl":
                self.say("your dead")
                self.attack(enemy)
            if self.isReady("cleave"):
                self.cleave(enemy)
            if enemy.type is "thrower" or enemy.type is "ogre":
                self.say("I'm going to kill you")
                self.attack(enemy)
            if self.isReady("cleave"):
                self.cleave(enemy)  

This is is the closest thing I have to working, but my warrior still doesn’t take care of all of the bad guys. he will initiate contact maybe kill one, maybe more if he cleaves, then he will decide to get a potion, but not the potion right beside the other one. he will then go to the bottom of the screen and collect another potion while enemies are hacking him to death.

item = self.findItems()
enemies = self.findEnemies()   
loop:
    enemies = self.findNearest(self.findEnemies())
    item = self.findNearest(self.findItems())
    if enemies:
        if self.isReady("cleave") and self.distanceTo(enemies) < 5:
            self.cleave(enemies)
        else:
            self.attack(enemies)
            self.attack(enemies)
            self.attack(enemies)
            if item:
                position = item.pos
                x = position.x
                y = position.y
                self.moveXY(x, y)

I often use several if/else combos. Don’t neglect the power of:

  • if
  • else/if
  • else

Great! In fact, I actually pretty much ignore findByType() and build my own arrays off of findEnemies(). This can really help with advanced auto-targeting. Be careful with the while loop. They are best handled for small operations (array sorting, etc.)

Yes, but that can get a little complicated. Typically, I kill enemies and if there are no enemies, then I collect items. However, you can indeed separate your “destination” from your “target”, which I do in a lot of my level code. What I do is probably very different from others, but here is a simplification:

loop:
// Automatic Actions (if any)

// Choose Destination
    if flag:
    else if item:

// Choose Target
    enemies = self.findEnemies()
    nearest = self.findNearest(enemies)
    // Loop through enemies to choose target, and after done:
    // If there is no target, choose nearest.
    if !target:
        target = nearest

// Control Allies (if I have them)

// Attack Target (if nearby)
    if target:
        if self.distanceTo(target) <= this.attackRange || 5
            self.attack(target)
        else if self.distanceTo(target) <= 10
            self.cleave()
    else if nearest:
        if self.distanceTo(nearest) <= this.attackRange || 5
            self.attack(nearest)

// Move toward Destination
    if destination:
        self.move(destination)
    else if target:
        self.move(target.pos)
    else
        self.move(home) // Used if you need a "center point"

Now, the above is pseudo-code, which means that it’s more about the process than the code itself. I couldn’t demonstrate the for/while loop for enemies because I don’t really understand CoffeeScript. I use this basic structure for almost every level (even multiplayer levels) and it allows for a lot of freedom. I can move as I need or around a target killing everything in my path along the way.

From your statements and your code, it sounds like you want something similar to this process. Using this, you simply have to realize that each cycle will update with the newest information (even if targets and destination don’t change). Just add conditions to the branch that you need… for instance, if you need to heal by going to a particular point, add else if to the “moving” branch.

I know its a lot, but I hope this helps a bit. Again, I don’t know CoffeeScript, so I can’t give a code answer… just a thinking one.

1 Like

Thank you Fuzzical. I will try that. I appreciate all of the help. I’m very new to all of this. I’m trying to learn this so that I can teach it to my middle school kids. They will probably be teaching me here soon. :slight_smile:

IF you want to kill an enemy dead before moving on make the “self.attack(nearest)”

            while enemy.health > 0:
                self.attack(nearest)

Sometimes, you may want to focus on one enemy (say thrower or shaman) and other times you don’t…
So use with care. :slight_smile:

1 Like

Precisely. It all depends on circumstance. Also, don’t forget: you may stick a while in an if (or else if):

    if target
        while target.health > 0:
            self.attack(target)

Ultimately, you have to think about programming as if you were solving a real life task. It really is no different. We all have priorities and conditions upon our own actions. The difference with programming only lies in that we have figure as much of these special circumstances as early as possible. If you are able to think in a task oriented manner, everything else will come with time.

I got it work thanks to your help. I appreciate it Fuzzical. Thanks Vlevo as well. That will come in handy. :smiley:

Congratulations and you are very welcome. Hopefully our comments will be useful for your future levels, as well.

Hello I try to move my hero with flag. but it did not workout .
Can someone tell me about my error?
thanks
flag = hero.findFlag(“green”)
flagGreen = hero.findFlag(“green”)
enemy = hero.findNearestEnemy()
while True:
if flagGreen:
greenPos = flagGreen.pos
greenX = greenPos.x
greenY = greenPos.y
hero.moveXY(greenX, greenY)
hero.pickUpFlag(flag)
continue

if enemy:
    if hero.isReady("cleave"):
        hero.cleave(enemy)
    else:
        hero.attack(enemy)

Есть решение проще, но конечно не изящное.

Этот уровень находится в середине игры CodeCombat,а значит на прошлых уровнях ты, анон, уже собрал достаточно игровой валюты и можешь купить любую одежку.

Покупаем хорошие доспехи (1), хороший меч (2) и очки, которые видят врагов сквозь стены (3), таким образом нам не придется направлять героя к врагам, он сам их найдет =)

А далее пара строк всего:

while True:
    enemy = hero.findNearestEnemy()
    hero.attack(enemy)
    flag = hero.findFlag("green")
    if flag:
        hero.moveXY(flag.pos.x, flag.pos.y)

Добро пожаловать в сообщество, но просьба не размещать здесь решения и не возрождать тему, это портит цель обучения и нарушает правила.

1 Like