Python——极客战记codecombat关卡代码

  • 不到万不得已,请各位不要走这条捷径噢,毕竟思路比代码本身更重要
  • 成果不易,转载请注明出处,谢谢

文章目录

kithgard地牢

地牢

 #向宝石进发。
 #小心尖刺!
 #在下面输入你的代码,完成后点击运行。
hero.moveRight()
hero.moveDown()
hero.moveRight()

深藏的宝石

# 利用你的移动命令收集所有宝石。

hero.moveRight()
hero.moveDown()
hero.moveUp()
hero.moveUp()
hero.moveRight()

幽灵守卫

# 避开食人魔的视线,收集宝石。
hero.moveRight()
hero.moveUp()
hero.moveRight()
hero.moveDown()
hero.moveRight()

真实姓名

# 抵御 Brak 和 Treg!
# 你必须攻击小食人魔两次。

hero.moveRight()
hero.attack("Brak")
hero.attack("Brak")
hero.moveRight()
hero.attack("Treg")
hero.attack("Treg")

高举之剑

# 打败食人魔
# 记住,每个攻击两次。

hero.attack("Rig")
hero.attack("Rig")
hero.attack("Gurt")
hero.attack("Gurt")
hero.attack("Ack")
hero.attack("Ack")

焰中舞动

# 代码通常按编写顺序执行。
# 循环会多次重复一个代码块。
# 按Tab或4个空格,把移动指令缩进到循环内部。

while True:
    hero.moveRight()
    # 在这里给循环里加 moveLeft 命令。
    hero.moveLeft()

KITHMAZE二度历险

# 使用while-true循环穿越迷宫!

while True:
    hero.moveRight()
    # 再键入3条移动命令来完成这个迷宫:
    hero.moveUp()
    hero.moveRight()
    hero.moveDown()

老对手

# 你可以像名牌那样使用变量

enemy1 = "Kratt"
enemy2 = "Gert"
enemy3 = "Ursa"
# 你可以像名牌那样使用变量

enemy1 = "Kratt"
enemy2 = "Gert"
enemy3 = "Ursa"

hero.attack(enemy1)
hero.attack(enemy1)
hero.attack(enemy2)
hero.attack(enemy2)
hero.attack(enemy3)
hero.attack(enemy3)
##########用下面的可能更方便#################
# while True:
#    enemy = hero.findNearestEnemy()
#    if enemy:
#        hero.attack(enemy)
###########################################

名称大师

# 你的英雄不知道这些敌人的名字!
# 这眼镜给了你 “findNearestEnemy” 寻找最近敌人的能力。
while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.attack(enemy)

矮人之乱

# 在 while true循环里,使用 findNearestEnemy() 并攻击!
while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.attack(enemy)

KITHMAZE最终历险

# 使用while-true循环移动并攻击目标

while True:
    hero.moveRight()
    hero.moveUp()
    enemy = hero.findNearestEnemy()
    hero.attack(enemy)
    hero.attack(enemy)
    hero.moveRight()
    hero.moveDown()
    hero.moveDown()
    hero.moveUp()

KithGard之门

# 建造三个围栏来阻挡食人魔!

hero.moveDown()
hero.buildXY("fence", 36, 34)
hero.buildXY("fence", 36, 30)
hero.buildXY("fence", 36, 27)
while True:
    hero.moveRight()

边地森林

平原森林保卫战

# 在标记上建造两个围栏保护村民
# 把鼠标放在地图上得到X,Y坐标
hero.buildXY("fence", 40, 52)
hero.buildXY("fence", 40, 20)

羊肠小道

# 到小路的尽头去,并在那儿修一个栅栏。
# 利用你的 moveXY(x, y) 函数。


# 这是路径的第一个节点。
hero.moveXY(36, 59)
# 移动到路径的第二个节点。
hero.moveXY(37, 13)
# 移动到路径的第三个节点
hero.moveXY(73, 63)
# 用盾牌提供保护
while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.shield()
# 建造栅栏抵挡食人魔。
hero.buildXY("fence", 72, 25)

林地小屋

# 通过林地,务必留意危险!
# 这些森林小屋中可能有食人魔!

hero.moveXY(19, 33)
enemy = hero.findNearestEnemy()
# if语句会检查某变量是否有食人魔。
if enemy:
    hero.attack(enemy)
    hero.attack(enemy)
    
    pass

hero.moveXY(49, 51)
enemy = hero.findNearestEnemy()
if enemy:
    # 攻击这里的敌人:
    hero.attack(enemy)
    hero.attack(enemy)
    
    # pass不做任何事情,它只负责结束if语句
    pass

hero.moveXY(58, 14)
enemy = hero.findNearestEnemy()
# 使用if语句检查敌人是否存在:
if enemy:
    # 如果敌人存在,就攻击它:
    hero.attack(enemy)
    hero.attack(enemy)
    pass

if的盛宴

# 在食人魔的营地中打败它们!

while True:
    enemy = hero.findNearestEnemy()
    # 使用一个 “if” 语句去检查是否有敌人存在:
    if enemy:
        
        # 攻击敌人,如果存在的话:
        hero.attack(enemy)
        hero.attack(enemy)

背靠背

# 待在中间防守!

while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        # 亦或主动出击...
        hero.attack(enemy)
        pass
    else:
        # 亦或回到你的阵地防守。
        hero.moveXY(40, 34)
        hero.say("爸爸回来了!")
        pass

森林劈斩者

# 尽可能经常使用你的新技能“cleave”

hero.moveXY(23, 23)
while True:
    enemy = hero.findNearestEnemy()
    if hero.isReady("cleave"):
        # 用“Cleave”干掉敌人!
        hero.cleave(enemy)
        pass
    else:
        # 否则(如果“cleave”还没准备好),就用你的普通攻击
        hero.attack(enemy)
        pass

边地僵局

# 矮人正在攻击!
# 攻击会有规律的一波波袭来。
# 可以的话,使用劈斩来清理大量敌人。

while True:
    enemy = hero.findNearestEnemy()
    # 使用带有‘isReady’的if语句来检查 “cleave”
    if hero.isReady("cleave"):
        # 劈斩!
        hero.cleave(enemy)
        pass
    # 否则,如果 cleave 还没准备好的话:
    else:
        # 攻击最近的食人魔!
        hero.attack(enemy)
        pass

测距仪

# 食人魔正在森林中巡视!
# 使用distanceTo方法找到敌人在哪。
# 说出与每个敌人的距离,告诉大炮向哪开火!

enemy1 = "Gort"
distance1 = hero.distanceTo(enemy1)
hero.say(distance1)

enemy2 = "Smasher"
distance2 = hero.distanceTo(enemy2)
# 说出distance2变量!
hero.say(distance2)
# 找到并说出与剩余敌人之间的距离:
# 不要攻击友方!
friend3 = "Charles"
pass
enemy4 = "Gorgnub"
distance4 = hero.distanceTo(enemy4)
hero.say(distance4)

while True:
    enemy = hero.findNearestEnemy()
    distance = hero.distanceTo(enemy)
    if distance < 10:
        # 如果他们与农民太近,就攻击他们
        # 当然,你也可以不用放大招
        if hero.isReady("cleave"):
            hero.cleave(enemy)
            pass
        else:
            hero.attack(enemy)
        pass
    # 否则的话,呆在农民旁边!使用else
    else:
        hero.moveXY(40, 38)

发狂的矮人

# 又一个宝箱等待英雄打开!
# 攻击宝箱来打开它。
# 有些食人魔矮人可不会呆呆地站着挨打!
# 当食人魔离你太近时,你得学着保护你自己

while True:
    enemy = hero.findNearestEnemy()
    distance = hero.distanceTo(enemy)
    if hero.isReady("cleave"):
        # 如果劈斩就绪,优先使用劈斩:
        if hero.isReady("cleave"):
            hero.cleave(enemy)
            pass
    elif distance < 5:
        # 攻击靠近并离你最近的食人魔矮人
        hero.attack(enemy)
        pass
    else:
        # 否则,尝试打开宝箱:
        # Use the name of the chest to attack: "Chest".
        hero.attack("Chest")
        pass
    

跃火林中

# 在这关,别碰恶魔石!往其他方向移动避开它们!
while True:
    evilstone = hero.findNearestItem()
    if evilstone:
        pos = evilstone.pos
        if pos.x == 34:
            # 如果恶魔石在左边,走到右边。
            hero.moveXY(46, 22)
            pass
        else:
            # 如果恶魔石在右边,走到左边。
            hero.moveXY(34, 22)
            pass
    else:
        # 如果没有恶魔石,那就去到中间。
        hero.moveXY(40, 22)
        pass

乡村漫游者

# 这定义了findAndAttackEnemy函数
def findAndAttackEnemy():
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.attack(enemy)

# 这段代码不是函数的一部分。
while True:
    # 现在你可以使用findAndAttackEnemy在村子里巡逻
    hero.moveXY(35, 34)
    findAndAttackEnemy()
    
    # 现在移动到右侧入口。
    hero.moveXY(60, 31)
    # 使用findAndAttackEnemy
    findAndAttackEnemy()

边地之叉

# 一大波食人魔正在到来!
# 使用 checkAndAttack 函数让代码易读。

# 这个函数有一个参数。
# 参数是一种给函数传递信息的方式。
def checkAndAttack(target):
    # target参数只是一个变量!
    # 它包含了函数调用时的参数。
    if target:
        hero.attack(target)
    hero.moveXY(43, 34)

while True:
    hero.moveXY(58, 52)
    topEnemy = hero.findNearestEnemy()
    checkAndAttack(topEnemy)
    # 移动到底部的X标记处。
    hero.moveXY(58, 16)
    # 创建名为 bottomEnemy 的变量,寻找最近敌人。
    bottomEnemy = hero.findNearestEnemy()
    checkAndAttack(bottomEnemy)
    # 使用 checkAndAttack 函数,并使用 bottomEnemy 变量。

交给劈斩者

# 一大波食人魔正在到来!
# 使用 checkAndAttack 函数让代码易读。

# 这个函数有一个参数。
# 参数是一种给函数传递信息的方式。
def checkAndAttack(target):
    # target参数只是一个变量!
    # 它包含了函数调用时的参数。
    if target:
        hero.attack(target)
    hero.moveXY(43, 34)

while True:
    hero.moveXY(58, 52)
    topEnemy = hero.findNearestEnemy()
    checkAndAttack(topEnemy)
    # 移动到底部的X标记处。
    hero.moveXY(58, 16)
    # 创建名为 bottomEnemy 的变量,寻找最近敌人。
    bottomEnemy = hero.findNearestEnemy()
    checkAndAttack(bottomEnemy)
    # 使用 checkAndAttack 函数,并使用 bottomEnemy 变量。

友人和敌人

# 农民和士兵聚集在森林。
# 命令农民战斗,苦工远离!

while True:
    friend = hero.findNearestFriend()
    if friend:
        hero.say("To battle, " + friend.id + "!")
    # 寻找最近的敌人,然后让他们滚蛋
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.say("Go away!," + enemy.id + "!")

巫师之门

# Move to 'Laszlo' and get his secret number.
hero.moveXY(30, 13)
las = hero.findNearestFriend().getSecret()

# 向 Laszlo 的数字中加7就能得到 Erzsebet的号码
# Move to 'Erzsebet' and say her magic number.
erz = las + 7
hero.moveXY(17, 26)
hero.say(erz)

# 将 Erzsebet 的数字除以 4 得到 Simoyi 的数字。
# Go to 'Simonyi' and tell him his number.
sim = erz / 4
hero.moveXY(30, 39)
hero.say(sim)
# 将 Simonyi 的数字乘以 Laszlo 的数字得到 Agata 的数字。
# Go to 'Agata' and tell her her number.
aga = sim * las
hero.moveXY(41, 26)
hero.say(aga)

未知的距离

# 你的任务是告诉他兽人的距离。

# 这个函数寻找最近的敌人,并返回距离。
# If there is no enemy, the function returns 0.
def nearestEnemyDistance():
    enemy = hero.findNearestEnemy()
    result = 0
    if enemy:
        result = hero.distanceTo(enemy)
    return result

while True:
    # Call nearestEnemyDistance() and
    # save the result in the variable enemyDistance.
    enemyDistance = nearestEnemyDistance()
    # If the enemyDistance is greater than 0: 
    if enemyDistance:
        # Say the value of enemyDistance variable.
        hero.say(enemyDistance)
        

金币屑

# 跟随硬币的轨迹来到红色 X 标记的出口

while True:
    # 这能找到最近的敌人。
    item = hero.findNearestItem()
    if item:
        # 这将物品的 pos,就是坐标,存储在变量中。
        itemPosition = item.pos
        # 将物品的 X 和 Y 坐标放进变量。
        itemX = itemPosition.x
        itemY = itemPosition.y
        # Now, use moveXY to move to itemX and itemY:
        hero.moveXY(itemX, itemY)

返回荆棘农场

# 这个函数 “maybeBuildTrap” 定义了两个参数
def maybeBuildTrap(x, y):
    # 使用x和y作为移动的坐标。
    hero.moveXY(x, y)
    enemy = hero.findNearestEnemy()
    if enemy:
        pass
        # 使用 buildXY 在特定 x 和 y 处建造 "fire-trap".
        hero.buildXY("fire-trap", x, y)
while True:
    # 这会调用 maybeBuildTrap,并使用上方入口的坐标。
    maybeBuildTrap(43, 50)
    
    # 下面在左侧入口使用maybeBuildTrap!
    maybeBuildTrap(25, 35)
    # 在底部入口处使用“maybeBuildTrap” !
    maybeBuildTrap(43, 20)
    

金币草地

# 收集每片草地的所有金币。
# 使用旗子在草地间移动。
# 当你准备好放置旗子时点击“提交”

while True:
    flag = hero.findFlag()
    if flag:
        pass  # “pass”是一个占位符,它没有任何作用
        # Pick up the flag.
        hero.pickUpFlag(flag)
    else:
        # Automatically move to the nearest item you see.
        item = hero.findNearestItem()
        if item:
            position = item.pos
            x = position.x
            y = position.y
            hero.moveXY(x, y)
            

插旗子

# 在你想要建造陷阱的位置插旗
# 当你没有在建造陷阱的时候,收集金币!

while True:
    flag = hero.findFlag()
    if flag:
        # 我们该如何通过旗子的位置得到 flagX 和 flagY 呢?
        # (向下看如何得到物品的 x 和 y)
        flagPos = flag.pos
        flagX = flagPos.x
        flagY = flagPos.y
        hero.buildXY("fire-trap", flagX, flagY)
        hero.pickUpFlag(flag)
    else:
        item = hero.findNearestItem()
        if item:
            itemPos = item.pos
            itemX = itemPos.x
            itemY = itemPos.y
            hero.moveXY(itemX, itemY)

小心陷阱

# 如果你试图攻击一个远处的敌人,你的英雄会忽略掉所有的旗子而朝它冲过去。
# 你需要确保你只攻击靠近自己的敌人!

while True:
    flag = hero.findFlag()
    enemy = hero.findNearestEnemy()
    
    if flag:
        # 去拔旗子。
        hero.pickUpFlag(flag)
        hero.say("我应该去把旗子拔起来。")
    elif enemy:
        # 仅当敌人的距离小于10米时才攻击。
        distance = hero.distanceTo(enemy)
        if distance < 10:
            if hero.isReady("cleave"):
                hero.cleave(enemy)
            else:
                hero.attack(enemy)
            

通信尸体

# 你可以使用旗子来选择不同的策略
# 在这关,绿色旗子代表你要移动到旗子处。
# 遇到黑旗就意味着你要在旗子那使用cleave
# 医生会在红X处治疗你

while True:
    green = hero.findFlag("green")
    black = hero.findFlag("black")
    nearest = hero.findNearestEnemy()
    
    if green:
        hero.pickUpFlag(green)
    elif black and hero.isReady("cleave"):
        hero.pickUpFlag(black)
        # 劈斩!
        hero.cleave(nearest)
    elif nearest and hero.distanceTo(nearest) < 10:
        # 攻击!
        hero.attack(nearest)
        pass

丰富的觅食

# 使用 if 和 else if 来处理任何情况
# 放置它来防御敌人,收集金币
# 确保你从物品商店买到伟大的盔甲,建议400点以上的健康。

while True:
    flag = hero.findFlag()
    enemy = hero.findNearestEnemy()
    item = hero.findNearestItem()

    if flag:
        # 当我发现旗子的时候发生了什么?
        hero.pickUpFlag(flag)
    elif enemy:
        # 当我找到敌人的时候发生了什么?
        if hero.isReady("cleave"):
            hero.cleave(enemy)
        else:
            hero.attack(enemy)
    elif item:
        # 当我找到一个物品的时候,发生了什么?
        hero.moveXY(item.pos.x, item.pos.y)
        

围攻STONEHOLD

# 这里可能需要你升级一下装备才能打赢
# 帮助你的朋友击败索科塔派出的手下。
# 你需要更好的装备和策略去赢得战斗。
# 标记可能有用,不过这取决于你——要有创造性哦!
# 在围栏后有位医生。移动到 X 处得到治疗!

while True:
    # 创建旗子标识
    flag = hero.findFlag("green")
    # 发现周边敌人
    enemy = hero.findNearestEnemy()
    # 到达旗子的位置
    if flag:
        hero.pickUpFlag(flag)
    if enemy:
        if hero.isReady("cleave"):
            hero.cleave(enemy)
        else:
            hero.attack(enemy)
    

沙漠

强壮的沙牦牛

# 当牦牛靠近时向右移动10米来躲避
# 躲避4头牦牛完成此关

while True:
    # 使用你的灵石获取你当前的 x 和 y 位置。
    x = hero.pos.x
    y = hero.pos.y
    
    # 找到最近的耗牛。
    yak = hero.findNearestEnemy()
    
    # 使用 if 仅仅当牦牛少于10米距离的时候。
    if hero.distanceTo(yak) < 10:
        # 向右移动,添加10到你的x位置。
        newX = x + 10
        # 使用 moveXY 来移动!
        hero.moveXY(newX, y)
        pass
    

绿洲

# 向绿洲移动
# Move left to avoid nearby yaks.
while True:
    x = hero.pos.x
    y = hero.pos.y
    enemy = hero.findNearestEnemy()
    if enemy and hero.distanceTo(enemy) < 10:
        # 通过在你的X坐标上减去10来移动到左边
        newX = x - 10
        # Use moveXY to move to the new x, y position.
        hero.moveXY(newX, y)
        pass
    else:
        # 通过在你的X坐标上加上10来移动到右边
        plusX = x + 10
        # Use moveXY to move to the new x, y position.
        hero.moveXY(plusX, y)
        pass

盆地的践踏

# **如果发现代码执行有问题,可能需要换一个浏览器再试试**,别问我怎么知道的,我快被牛顶死了!!!
# Keep moving right, but adjust up and down as you go.

while True:
    enemy = hero.findNearestEnemy()
    xPos = hero.pos.x + 5
    yPos = 17
    
    if enemy:
        # Adjust y up or down to get away from yaks.
        if enemy.pos.y > hero.pos.y:
            # If the Yak is above you, subtract 3 from yPos.
            yPos = yPos - 3
            pass
        elif enemy.pos.y < hero.pos.y:
            # If the Yak is below you, add 3 to yPos.
            yPos = yPos + 3
            pass
    hero.moveXY(xPos, yPos)

萨文路

# 可能需要升级一下装备!!!
# 到达绿洲。小心新的敌人:食人魔侦察兵!
# 通过添加你当前的X位置和Y位置以向上向右走

while True:
    # If there's an enemy, attack.
    enemy = hero.findNearestEnemy()
    if enemy:
        if hero.isReady("cleave"):
            hero.cleave(enemy)
        else:
            hero.attack(enemy)
    else:
        xPos = hero.pos.x
        yPos = hero.pos.y
        # Else, keep moving up and to the right. 
        xPos = xPos + 5
        yPos = yPos +5
        hero.moveXY(xPos, yPos)
    pass
    

十字路口

# 使用  fire-trap 打败进攻的食人魔

while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        # If the enemy is to the left of the hero:
        if enemy.pos.x < hero.pos.x:
            # 如果敌人从左边进攻,在左边建一个fire-trap(火焰陷阱)
            hero.buildXY("fire-trap", 25, 34)
            pass
        # If the enemy is to the right of the hero:
        elif enemy.pos.x > hero.pos.x:
            # 如果敌人从右边进攻,在右边建一个fire-trap(火焰陷阱)
            hero.buildXY("fire-trap", 55, 34)
            pass
        # If the enemy is below the hero:
        elif enemy.pos.y < hero.pos.y:
            # 如果敌人从下边进攻,在下边建一个fire-trap(火焰陷阱)
            hero.buildXY("fire-trap", 40, 19)
            pass
        # If the enemy is above the hero:
        elif enemy.pos.y > hero.pos.y:
            # 如果敌人从上边进攻,在上边建一个fire-trap(火焰陷阱)
            hero.buildXY("fire-trap", 40, 49)
            pass
    # Move back to the center.
    hero.moveXY(40, 34)

雷蹄

# 到达绿洲,
# 用栅栏引导砂牦牛到你去的地方

while True:
    yak = hero.findNearestEnemy()
    if yak:
        # 如果它的 y 值大于你的,那么耗牛在你前面
        if yak.pos.y > hero.pos.y:
            # 如果耗牛在你前面,在它后面10米建立一个栅栏
            hero.buildXY("fence", yak.pos.x, yak.pos.y - 10)
        else: 
            hero.buildXY("fence", yak.pos.x, yak.pos.y + 10)
            # 如果耗牛在你后面,在它前面10m 建立一个栅栏
                
        pass
    else:
        # 向右移动10走向绿洲
        hero.moveXY(hero.pos.x + 10, hero.pos.y)
        pass

操作“杀鹿”

# Lure the ogres into a trap. These ogres are careful.
# They will only follow if the hero is injured.

# This function checks the hero's health 
# 并返回一个布尔型(Boolean)的值。
def shouldRun():
    if hero.health < hero.maxHealth / 2:
        return True
    else:
        return False

while True:
    # Move to the X only if shouldRun() returns True
    enemy = hero.findNearestEnemy()
    value = shouldRun()
    if value:
        hero.moveXY(75, 37)
    # Else, attack!
    else:
        if hero.isReady("cleave") and hero.distanceTo(enemy) < 5:
            hero.cleave(enemy)
        else:
            hero.attack(enemy)
    

医疗注意

# 当你生命值少于一半时,请求医疗人员的治疗。

while True:
    currentHealth = hero.health
    # 我的装备不好,就改动了一下零界值
    healingThreshold = (hero.maxHealth * 4) / 5
    # 如果你当前的健康值少于下限,
    # move to the healing point and say, "heal me".
    # 否则的话,攻击。你需要战斗的更狠点!
    enemy = hero.findNearestEnemy()
    if currentHealth > healingThreshold:
        if enemy:
            distance = hero.distanceTo(enemy)
            if hero.isReady("cleave") and distance < 5:
                hero.cleave(enemy)
            else:
                hero.attack(enemy)
    else:
        hero.moveXY(65, 46)
        hero.say("heal me")
    

跟上时间

# 使用你的新技能来选择你要做什么 hero.time

while True:
	# 需要买一件衣服来抵挡伤害!!!
    # 如果是头十秒,进攻。
    if hero.time < 10:
        enemy = hero.findNearestEnemy()
        if enemy:
            distance = hero.distanceTo(enemy)
            if hero.isReady("cleave") and distance < 9:
                hero.cleave(enemy)
            else:
                hero.attack(enemy)
        pass
    # 反之,如果是前35秒,收集金币。
    elif hero.time < 35:
        coin = hero.findNearestItem()
        if coin:
            hero.moveXY(coin.pos.x, coin.pos.y)
        pass
    # 后35秒,加入救助。
    else:
        enemy = hero.findNearestEnemy()
        if enemy:
            distance = hero.distanceTo(enemy)
            if hero.isReady("cleave") and distance < 9:
                hero.cleave(enemy)
            else:
                hero.attack(enemy)
        pass

囤积金币

# 收集25金币,然后告诉 Naria 总数
# 当金币总数大于25,使用 break 来停止收集金币。

totalGold = 0
while True:
    coin = hero.findNearestItem()
    if coin:
        # 捡起金币
        hero.moveXY(coin.pos.x, coin.pos.y)
        # 将金币的价值加进 totalGold.(查看帮助了解更多.)
        # 使用以下方法得到它的价值::  coin.value
        totalGold += coin.value
        pass
    if totalGold >= 25:
        # 这会中断循环并且执行循环下面的语句
        # The loop ends, code after the loop will run.
        break

# 完成收集金币!
hero.moveXY(58, 33)
# 去告诉 Naria 你收集了多少金币。
hero.say("你好 Naria, 我收集了 " + totalGold + " 枚金币")

诱饵钻

# 我们在测试一个新的战斗单位:诱饵。
# 创建4个诱饵,然后汇报给 Naria

decoysBuilt = 0
while True:
    coin = hero.findNearestItem()
    
    if coin:
        # 掠夺金币!
        hero.moveXY(coin.pos.x, coin.pos.y)
        pass
    # 每个诱饵消费25个金币。
    # 让它知道当你有超过25个金币的时候
    if hero.gold >= 25:
        # buildXY a "decoy"
        hero.buildXY("decoy", hero.pos.x, hero.pos.y)
        # 当你一直走的时候,保持统计你创建的诱饵的数量。
        decoysBuilt += 1
    if decoysBuilt == 4:
        # 当你创建了4个诱饵时跳出循环
        break
        pass
    
hero.say("完成创建诱饵!")
hero.moveXY(14, 36)
# 去找 Naria 并告诉她你创建了多少个诱饵。
hero.say("I built " + decoysBuilt +' decoies!')

复查

# 第一点,打败6位ogres~
# Then collect coins until you have 30 gold.

# 变量用来对ogres计数
defeatedOgres = 0

# 没打败6位ogres,就继续打
while defeatedOgres < 6:
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.attack(enemy)
        defeatedOgres += 1
    else:
        hero.say("Ogres!")

# Move to the right side of the map.
hero.moveXY(49, 36)

# 钱没攒够30块,就继续捡
while hero.gold < 30:
    # 寻找并收集金币
    coin = hero.findNearestItem()
    hero.moveXY(coin.pos.x, coin.pos.y)
    # 去掉这行 say()。
    # hero.say("我应该收集金币!")

# 移动到出口。
hero.moveXY(76, 32)

沙漠战役

# while循环重复直到条件为否。
# 得去提升自己的护甲

ordersGiven = 0
while ordersGiven < 5:
    # 在站场上移动和排列你的盟友。 (如果你是直接在他们面前,他们只能听到你的。)
    hero.moveXY(hero.pos.x, hero.pos.y - 10)
    # Order your ally to "Attack!" with hero.say
    # They can only hear you if you are on the X.
    hero.say("Attack!")
    # Be sure to increment ordersGiven!
    ordersGiven += 1

while True:
    enemy = hero.findNearestEnemy()
    # 当你下达完命令,立即加入战斗!
    maxhealth = hero.maxHealth
    if enemy:
        distance = hero.distanceTo(enemy)
        if hero.isReady("cleave") and distance < 9:
            hero.cleave(enemy)
        else:
            hero.attack(enemy)
        if hero.health < hero.maxHealth / 2:
            hero.moveXY(10, 34)

尘埃

# 使用循环直到你有足够的击杀10个芒奇金人 

attacks = 0
while attacks < 10:
    # 攻击最近的敌人!
    enemy = hero.findNearestEnemy()
    if enemy:
        if hero.isReady("cleave"):
            hero.cleave(enemy)
        else:
            hero.attack(enemy)
    # Incrementing means to increase by 1.
    # 增加你的攻击统计量。
    attacks += 1

# 当你完成后,撤退到伏击点。
hero.say("I should retreat!") #∆ Don't just stand there blabbering!
hero.moveXY(79, 33)

别冲过去,安静点

# Dodge the cannons and collect 8 gems.
# Watch out, cannons are ready to fire!
# 以一个特殊的方式缓慢移动去迷惑敌人

# This function returns a value from 0 to 30 (0 <= n < 30)
def mod30(n):
    if n >= 30:
        return n - 30
    else:
        return n

# 这一功能将会返回一个从0到40的值
def mod40(n):
    # 使用一个 “if” 语句去返回正确的值
    if n >= 40:
        return n - 40
    else:
        return n

# You don't need to change the following code:
while True:
    time = hero.time
    x = mod30(time) + 25
    y = mod40(time) + 10
    hero.moveXY(x, y)

ZIG ZAG ANG ZOOM

# 从死亡峡谷逃出!
# 使用真正的求余函数走出Z字形路线。

# This function returns a value from 0 to 15:
def mod15(n):
    while n >= 15:
        n -= 15
    return n

# 这个函数应该会反馈一个从0到9的值
def mod9(n):
    # 在返回前使用 while 循环修改参数。
    while n > 9:
        n -= 9
    return n

# Don't change the following code:
while True:
    time = hero.time
    if time < 30:
        y = 10 + 3 * mod15(time)
    else:
        y = 20 + 3 * mod9(time)
    x = 10 + time
    hero.moveXY(x, y)

沙漠三角形

# 只攻击在敌军名称(enemyNames)数组中的敌人
# Be sure to attack in order! 0 -> 1 -> 2 -> 3
enemyNames = ["Kog", "Godel", "Vorobun", "Rexxar"]

hero.attack(enemyNames[0])
hero.attack(enemyNames[1])
# 攻击 enemyNames[2]
hero.attack(enemyNames[2])
# 攻击最后一个元素。
hero.attack(enemyNames[3])

SARVEN 救世主

# 一个数组(Array)就是物品的数列。

# 这个数组是一个朋友名字的数列。
friendNames = ['Joan', 'Ronan', 'Nikita', 'Augustus']

# 数组从零开始计数,不是1!
friendIndex = 0

# 循环该数组中的每一个名字
# 使用 len()方法来得到列表的长度。
while friendIndex < len(friendNames):
    # 使用方括号来获得数组中的名字。
    friendName = friendNames[friendIndex]
    
    # 告诉你的朋友回家。
    # 使用+来连接两个字符串。
    hero.say(friendName + ', go home!')
    
    # 增加索引来获取数组中的下一个名字
    friendIndex += 1
    
# 回去建造栅栏让食人魔远离。
# 这里要先往左边走一点,不然会把自己挡在外面
hero.moveXY(25, 30)
hero.buildXY("fence", 30, 30)

BANK RAID

# Wait for ogres, defeat them and collect gold.

while True:
    enemies = hero.findEnemies()
    # enemyIndex 用于迭代数组。
    enemyIndex = 0
    # While enemyIndex is less than len(enemies)
    while enemyIndex < len(enemies):
        # Attack the enemy at enemyIndex
        enemy = enemies[enemyIndex]
        hero.attack(enemy)
        # 给 enemyIndex 加上 1。
        enemyIndex += 1
    coins = hero.findItems()
    # coinIndex is used to iterate the coins array.
    coinIndex = 0
    while coinIndex < len(coins):
        # 用 coinIndex 从 coins 数组得到一个金币。
        # 这里加上:如果敌人出现,则停止收集金币,优先攻击敌人
        # 发现运行会超时,所以还是买厚一点的护甲吧,避免被砍死
        # enemyOccur = hero.findNearestEnemy()
        # if enemyOccur:
        #     break
        coin = coins[coinIndex]
        # 收集那个金币。
        hero.moveXY(coin.pos.x, coin.pos.y)
        # 给 coinIndex 的值增加 1。
        coinIndex += 1

潜伏

# 用findEnemies把敌人存在数组enemies中
# 只攻击萨满巫师,不要攻击牦牛!

enemies = hero.findEnemies()
enemyIndex = 0

# 把这段代码用一个while loop 功能循环遍历所有的敌人
# 当 enemyIndex 小于 enemies 的长度时:
while enemyIndex < len(enemies):
    enemy = enemies[enemyIndex]
    if enemy.type == 'shaman':
        while enemy.health > 0:
            hero.attack(enemy)
    # Remember to increment enemyIndex
    enemyIndex += 1
    

SARVEN 牧羊人

# 使用 while 循环来对付食人魔。

while True:
    enemies = hero.findEnemies()
    enemyIndex = 0
    # 将攻击逻辑放到 while 循环里来攻击所有的敌人。
    # Find the array's length with:  len(enemies)
    while enemyIndex < len(enemies):
        enemy = enemies[enemyIndex]
        # "!=" 意思是 "不等于"
        if enemy.type != "sand-yak":
            # 当敌人的健康值大于0,攻击它!
            while enemy.health > 0:
                hero.attack(enemy)
            pass
        enemyIndex += 1
    # 在两波敌人之间,移动回中央。
    hero.moveXY(40, 32)
    

捡闪亮东西的人

# 很快的获取最多的金币

while True:
    coins = hero.findItems()
    coinIndex = 0
    
    # 把这个封装进循环里枚举所有的硬币
    while coinIndex < len(coins):
        coin = coins[coinIndex]
        # 金币价值3点。
        if coin.value == 3:
            # 只捡金币。
            hero.moveXY(coin.pos.x, coin.pos.y)
            pass
        coinIndex += 1

疯狂的MAXER

# 优先杀掉最远的敌人。

while True:
    farthest = None
    maxDistance = 0
    enemyIndex = 0
    enemies = hero.findEnemies()
    # 查看全部敌人,找出最远的那个。
    while enemyIndex < len(enemies):
        target = enemies[enemyIndex]
        enemyIndex += 1
        # 是不是存在远得看不到的敌人?
        distance = hero.distanceTo(target)
        if distance > maxDistance:
            maxDistance = distance
            farthest = target
    if farthest:
        # 干掉最远的敌人!
        # 如果敌人血量大于0就保持攻击。
        while farthest.health > 0:
            hero.attack(farthest)
        pass

克隆冲突

# 你需要更好的策略和好的装备来赢得这关。
# 你的克隆体将会拥有和你一样的装备
# 但是,他们没有经验,不会用特殊技能。
# 自己提出的要求和思路:
# 注意:不要杀牛和thoktar
# 1.先杀死所有射箭的
def killBowman(enemies):
    enemyIndex = 0
    while enemyIndex < len(enemies):
        enemy = enemies[enemyIndex]
        if enemy.type == 'archer':
            while enemy.health > 0:
                if hero.isReady("cleave") and hero.distanceTo(enemy) < 5:
                    hero.cleave(enemy)
                else:
                    hero.attack(enemy)
        enemyIndex += 1
# 2.再来杀其他人
def killsoldiers(enemies):
    enemyIndex = 0
    while enemyIndex < len(enemies):
        enemy = enemies[enemyIndex]
        if enemy.type != 'sand-yak':
            while enemy.health > 0:
                if hero.isReady("cleave"):
                    hero.cleave(enemy)
                else:
                    hero.attack(enemy)
        enemyIndex += 1![在这里插入图片描述](https://img-blog.csdnimg.cn/20190107125106487.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0dlb2ZmcmV5X1pmbHllZQ==,size_16,color_FFFFFF,t_70)

while True:
    enemies = hero.findEnemies()
    killBowman(enemies)
    killsoldiers(enemies)

峭壁追逐

# 抓住 Pender Spellbane 去了解她的秘密。

while True:
    # Pender是这里唯一的朋友,所以她总是在最近的位置。
    pender = hero.findNearest(hero.findFriends())
    if pender:
        # moveXY()将移动到 Pender 在的位置,
        # 但是她会向远离你的位置移动。
        # hero.moveXY(pender.pos.x, pender.pos.y)
        
        # move()只一次移动一步。
        # 所以你可以用它来追踪你的目标。
        hero.move(pender.pos)

激流涡旋

# 使用对象枚举来走安全的路,并收集宝石。
# 在本关你不能够使用 moveXY()方法!使用 move()来移动
gems = hero.findItems()

while hero.pos.x < 20:
	# move()移动物体通过 x 和 y 的属性,不仅仅是数字。
	hero.move({'x': 20, 'y': 35})

while hero.pos.x < 25:
	# 一个宝石的位置是一个对象,有 x 和 y 属性。
	gem0 = gems[0]
	hero.move(gem0.pos)

# 当你的 x 小于30的时候,
# 使用物体移动到30,35位置
while hero.pos.x < 30:
    hero.move({'x':30, 'y':35})
# 当你的 x 小于35的时候
# 移动到宝石[1]的位置
while hero.pos.x < 35:
    gem1 = gems[1]
    hero.move(gem1.pos)

# 拿到最后一对宝石!
while hero.pos.x < 40:
    hero.move({'x': 40, 'y':35})
    
while hero.pos.x < 45:
    gem2 = gems[2]
    hero.move(gem2.pos)
    
while hero.pos.x < 50:
    hero.move({'x': 50, 'y':35})
    
while hero.pos.x < 55:
    gem3 = gems[3]
    hero.move(gem3.pos)

食人魔山谷挖宝

# 一大群食人魔来之前你只有20秒时间!
# 尽可能去捡金币,然后你撤退到你栅栏后面的基地里!

# 如果方法一和方法二都没有凑齐60枚金币,那可能就是英雄移动速度太慢了,得换英雄。
# 方法一:只收集最近的金币
def findNearestCoin(coins):
    nearestCoin = None
    distance = 999
    Value = 0
    itemIndex = 0
    while itemIndex < len(coins):
        Value = hero.distanceTo(coins[itemIndex])
        if Value < distance:
            nearestCoin = coins[itemIndex]
            distance = Value
        itemIndex += 1
    return nearestCoin
    

# 方法二:只收集面值最大的金币
def findBiggestCoin(coins):
    biggestCoin = None
    Value = 0
    cost = 0
    itemIndex = 0
    while itemIndex < len(coins):
        cost = coins[itemIndex].value
        if Value < cost:
            Value = cost
            biggestCoin = coins[itemIndex]
        itemIndex += 1
    return biggestCoin


while hero.time < 20:
    # 收集金币
    # hero.say("我应该捡点金币")
    items = hero.findItems()
    # 方法一:只收集最近的金币
    coin = findNearestCoin(items)
    # 方法二:只收集面值最大的金币
    # coin = findBiggestCoin(items)
    hero.move(coin.pos)
    
    
while hero.pos.x > 16:
    # 撤退到栅栏后面
    # hero.say("我应该撤退")
    hero.moveXY(16, 38)
    
# 建立栅栏挡住食人魔
hero.buildXY("fence", 21, 38)

安息之云指挥官

# 召唤一些士兵,然后引导他们去你的基地。

# 每个士兵消耗20金币。
while hero.gold > hero.costOf("soldier"):
    hero.summon("soldier")
    
soldiers = hero.findFriends()
soldierIndex = 0
# 添加一个while 循环来命令所有的士兵。
while soldierIndex < 5:
    soldier = soldiers[soldierIndex]
    hero.command(soldier, "move", {"x": 50, "y": 40})
    soldierIndex += 1
# 去加入你的朋友!
hero.moveXY(50,36)

佣兵山

# 收集金币招募士兵,指挥他们攻击敌人。

while True:
    # 走到最近的金币处。
    # 使用 move 取代 moveXY,以便于你可以不断发出命令。
    item = hero.findNearest(hero.findItems())
    if item:
        hero.move(item.pos)
    # hero.say("我需要金币!") # 删掉这一行以避免卡顿
    # 如果钱够了就招募士兵。
    if hero.gold > hero.costOf("soldier"):
        hero.say("我应该召集些什么帮手!")
        hero.summon("soldier")
    enemy = hero.findNearest(hero.findEnemies())
    if enemy:
        # 遍历你所有的士兵,命令他们攻击。
        soldiers = hero.findFriends()
        soldierIndex = 0
        while soldierIndex < len(soldiers):
            soldier = soldiers[soldierIndex]
            # 使用 attack 命令让你的士兵们攻击。
            hero.command(soldier, "attack", enemy)
            soldierIndex += 1

            
       

木材守卫

while True:
    # 收集金子
    item = hero.findNearestItem()
    if item:
        hero.move(item.pos)
    # 如果你有足够的金币,召唤一个士兵。
    if hero.gold > hero.costOf("soldier"):
        hero.summon("soldier")
    # 使用 for 循环来命令每个士兵。
    # for 循环有两个部分『for X in Y』
    # Y 是被循环的数组结构
    #  Y 中的每个元素都会执行,X 会被设置称当前循环的个体
    for friend in hero.findFriends():
        if friend.type == "soldier":
            hero.command(friend, "move", {'x': 70, 'y' :45})
            enemy = friend.findNearestEnemy()
            # 如果这有一个敌人,命令她攻击。
            # 否则的话,移动她到地图的右边。
            if enemy:
                hero.command(friend, "attack", enemy)
            

零和

# 在两分钟内击退敌人。
hero.cast("goldstorm")


while True:
    enemies = hero.findEnemies()
    nearestEnemy = hero.findNearest(enemies)
    
    
    item = hero.findNearest(hero.findItems())
    hero.move(item.pos)
    # 你的英雄能收集金币,召唤部队。
    if hero.gold > hero.costOf("soldier"):
        hero.summon("soldier")
        
        
        
    # 在站场上,她也可以命令你的盟友。
    friends = hero.findFriends()
    for friend in friends:
        hero.command(friend, "attack", friend.findNearest(enemies))
    
    # 使用你的英雄的能力力挽狂澜。
    
    

动物园的管理员

# 保护笼子。
# 放一个士兵在每一个 X 的位置
points = []
points[0] = {"x": 33, "y": 42}
points[1] = {"x": 47, "y": 42}
points[2] = {"x": 33, "y": 26}
points[3] = {"x": 47, "y": 26}

# 1.收集80金币。
while hero.gold < 80:
    item = hero.findNearest(hero.findItems())
    hero.move(item.pos)

# 2.建造4个士兵。
for i in range(4):
    hero.summon("soldier")
    
# 3.派你的士兵到特定的位置上。
while True:
    friends = hero.findFriends()
    for j in range(len(friends)):
        point = points[j]
        friend = friends[j]
        enemy = friend.findNearestEnemy()
        if enemy and enemy.team == "ogres" and friend.distanceTo(enemy) < 5:
            # 命令友方攻击。
            hero.command(friend, "attack", enemy)
        else:
            # 命令的朋友移动到特定点上。
            hero.command(friend, "move", point)
        
            
            

战略祭品

# 收集80金币
while hero.gold < 80:
    item = hero.findNearestItem()
    hero.move(item.pos)

# 建造4个士兵用来做诱饵
for i in range(4):
    hero.summon("soldier")
# 派你的士兵到指定位置。
points = []
points[0] = { "x": 13, "y": 73 }
points[1] = { "x": 51, "y": 73 }
points[2] = { "x": 51, "y": 53 }
points[3] = { "x": 90, "y": 52 }
friends = hero.findFriends()

# 使用范围来在数组中循环
# 让friends去指定地点,命令他们移动
for j in range(len(friends)):
    point = points[j]
    friend = friends[j]
    hero.command(friend, "move", point)
    

狩猎派对

# 命令你的部队向东移动,攻击任何看到的食人魔。
# 使用 for 循环和 findFriends方法。
# 你能在你的士兵上使用findNearestEnemy()来获取他们的而不是你的最近的敌人。

while True:
    friends = hero.findFriends()
    for i in range(len(friends)):
        friend = friends[i]
        newX = friend.pos.x + 0.5
        newY = friend.pos.y
        enemy = friend.findNearestEnemy()
        if enemy:
            hero.command(friend, "attack", enemy)
        else:
            hero.command(friend, "move",{'x': newX, 'y': newY} )
            

维他力量

# 这关会教你怎么定义你自己的函数。
# 放在函数内的代码并不会立刻执行, 而是先保存好, 以备后用.
# 这个函数会让你的英雄收集最近的金币。
def pickUpNearestCoin():
    items = hero.findItems()
    nearestCoin = hero.findNearest(items)
    if nearestCoin:
        hero.move(nearestCoin.pos)

# 这个函数会让你的英雄召唤一个士兵。
def summonSoldier():
    # 在这里写下代码:当你有足够金币时召唤士兵
    if hero.gold > hero.costOf("soldier"):
        hero.summon("soldier")
    


# 这个函数会命令你的士兵攻击最近的敌人
def commandSoldiers():
    for soldier in hero.findFriends():
        enemy = soldier.findNearestEnemy()
        if enemy:
            hero.command(soldier, "attack", enemy)
        else:
            hero.command(soldier, "move", hero.pos)
        


while True:
    # 在你的循环里,你可以"调用"你在上面定义的函数
    # 下面几行代码会让 "pickUpNearestCoin" 函数里的代码被执行。
    pickUpNearestCoin()
    # 在这里调用 summonSoldier
    summonSoldier()
    # 在这里调用 commandSoldiers
    commandSoldiers()

双生花

# 如果花匠受伤了,双生花会缩小!

def summonSoldiers():
    if hero.gold >= hero.costOf("soldier"):
        hero.summon("soldier")

# 定义函数:commandSoldiers
def commandSoldiers():
    for friend in hero.findFriends():
        if friend.type == "soldier":
            enemy = friend.findNearestEnemy()
            peasant = hero.findByType("peasant")[0]
            if enemy:
                hero.command(friend, "attack", enemy)
            else:
                hero.command(friend, "move", peasant.pos)
                    
# 定义函数:pickUpNearestCoin
def pickUpNearestCoin():
    items = hero.findItems()
    nearestCoin = hero.findNearest(items)
    if nearestCoin:
        hero.move(nearestCoin.pos)

while True:
    summonSoldiers()
    commandSoldiers()
    pickUpNearestCoin()
    

花的几何学

# 你现在有花环! 你可以做:
# toggleFlowers(true/false) - 打开或关闭鲜花。
# setFlowerColor("random") - 也可以是 "pink", "red", "blue", "purple", "yellow", or "white"。

# 以下是绘制图形的一些函数:
# x,y - 图形的中心
# size - 图形的大小(半径,边长)
def drawCircle(x, y, size):
    angle = 0
    hero.toggleFlowers(False)
    while angle <= Math.PI * 2:
        newX = x + (size * Math.cos(angle))
        newY = y + (size * Math.sin(angle))
        hero.moveXY(newX, newY)
        hero.toggleFlowers(True)
        angle += 0.2

def drawSquare(x, y, size):
    hero.toggleFlowers(False)
    cornerOffset = size / 2
    hero.moveXY(x - cornerOffset, y - cornerOffset)
    hero.toggleFlowers(True)
    hero.moveXY(x + cornerOffset, y - cornerOffset)
    hero.moveXY(x + cornerOffset, y + cornerOffset)
    hero.moveXY(x - cornerOffset, y + cornerOffset)
    hero.moveXY(x - cornerOffset, y - cornerOffset)


redX = {"x": 28, "y": 36}
whiteX = {"x": 44, "y": 36}

# 选择一种颜色。
hero.setFlowerColor("red")
# 在redX上绘制一个大小为10的圆圈。
drawCircle(redX.x, redX.y, 10)
# 改变颜色!
hero.setFlowerColor("blue")
# 在whiteX上绘制一个大小为10的正方形。
drawSquare(whiteX.x, whiteX.y, 10)
# 现在尝试绘制任何你想要的!

# 你现在有花环! 你可以做:
# toggleFlowers(true/false) - 打开或关闭鲜花。
# setFlowerColor("random") - 也可以是 "pink", "red", "blue", "purple", "yellow", or "white"。

# 以下是绘制图形的一些函数:
# x,y - 图形的中心
# size - 图形的大小(半径,边长)
def drawCircle(x, y, size):
    angle = 0
    hero.toggleFlowers(False)
    while angle <= Math.PI * 2:
        newX = x + (size * Math.cos(angle))
        newY = y + (size * Math.sin(angle))
        hero.moveXY(newX, newY)
        hero.toggleFlowers(True)
        angle += 0.2

def drawSquare(x, y, size):
    hero.toggleFlowers(False)
    cornerOffset = size / 2
    hero.moveXY(x - cornerOffset, y - cornerOffset)
    hero.toggleFlowers(True)
    hero.moveXY(x + cornerOffset, y - cornerOffset)
    hero.moveXY(x + cornerOffset, y + cornerOffset)
    hero.moveXY(x - cornerOffset, y + cornerOffset)
    hero.moveXY(x - cornerOffset, y - cornerOffset)


redX = {"x": 28, "y": 36}
whiteX = {"x": 44, "y": 36}

# 选择一种颜色。
hero.setFlowerColor("red")
# 在redX上绘制一个大小为10的圆圈。
drawCircle(redX.x, redX.y, 10)
# 改变颜色!
hero.setFlowerColor("blue")
# 在whiteX上绘制一个大小为10的正方形。
drawSquare(whiteX.x, whiteX.y, 10)
# 现在尝试绘制任何你想要的!

山花林

# 这个关卡是制作花卉艺术的地方。
# 真正的目标是尝试并获得乐趣!
# 如果你画了至少1000朵花的东西,那么你将在这个关卡上"succeed"。
def drawCircle(x, y, size):
    while size < 50:
        angle = 0
        hero.toggleFlowers(False)
        while angle <= Math.PI * 2:
            newX = x + (size * Math.cos(angle))
            newY = y + (size * Math.sin(angle))
            hero.moveXY(newX, newY)
            hero.toggleFlowers(True)
            angle += 0.2
        size += 5
        

centre = {'x':85, 'y':70}
hero.setFlowerColor("random")
drawCircle(centre.x, centre.y, 1)

猎手和猎物

# 食人魔正试图除掉你的驯鹿!
# 当召唤士兵进攻时,让弓箭手回来。

def pickUpCoin():
    # 收集硬币。
    item = hero.findNearest(hero.findItems())
    if item.type == 'coin' or item.type =='gem':
        hero.move(item.pos)
    pass

def summonTroops():
    # 如果你有黄金就召唤士兵。
    if hero.gold > hero.costOf("archer"):
        hero.summon("archer")
    #if hero.gold > hero.costOf("soldier"):
    #    hero.summon("soldier")
    
# 这个函数有一个名为士兵的参数。
# 参数就像变量一样。
# 调用函数时确定参数的值。
def commandSoldier(soldier):
    # 士兵要攻击敌人。
    enemy = soldier.findNearestEnemy()
    if enemy:
        hero.command(soldier, "attack", enemy)
    else:
        hero.command(soldier, "move", hero.pos)
    

# 编写一个命令弓箭手的函数来告诉你的弓箭手怎么做!
# 它应该有一个参数将表示在被调用时传递给函数的射手。
# 弓箭手应该只攻击距离25米以内的敌人,否则原地待命。
def commandArcher(archer):
    enemy = archer.findNearestEnemy()
    if enemy and archer.distanceTo(enemy) <= 25:
        hero.command(archer, "attack", enemy)
    else:
        hero.command(archer, "move", hero.pos)
            

while True:
    pickUpCoin()
    summonTroops()
    friends = hero.findFriends()
    for friend in friends:
        if friend.type == "soldier":
            # 这位朋友将被分配给commandSoldier函数中的士兵变量
            commandSoldier(friend)
        elif friend.type == "archer":
            # 务必指挥你的弓箭手。
            commandArcher(friend)
            

图书馆的谋士

# Hushbaum已被食人魔伏击!
# 她正在忙着医治她的士兵,你应该命令他们去战斗!
# 如果食人魔认为他们可以攻击到Hushbaum或弓箭手,那么他们会派出更多的部队,所以将他们放在圈子里面!

# 士兵们围成一圈防守起来。
def commandSoldier(soldier, soldierIndex, numSoldiers):
    angle = Math.PI * 2 * soldierIndex / numSoldiers
    defendPos = {"x": 41, "y": 40}
    defendPos.x += 10 * Math.cos(angle)
    defendPos.y += 10 * Math.sin(angle)
    hero.command(soldier, "defend", defendPos);

# 找到最强大的目标(生命值最高)
# 该函数返回一些东西! 当你调用函数时,你会得到一些回报。
def findStrongestTarget():
    mostHealth = 0
    bestTarget = None
    enemies = hero.findEnemies()
    # 找出哪个敌人的生命值最高,并将bestTarget设置为该敌人。
    for enemy in enemies:
        if enemy.health > mostHealth:
            mostHealth = enemy.health
            bestTarget = enemy
    # 如果有大食人魔的话,只关注弓箭手的火力。
    if bestTarget and bestTarget.health > 15:
        return bestTarget
    else:
        return None


# 如果最强大的目标拥有超过15的生命值,则攻击该目标。 否则,攻击最近的目标。
def commandArcher(archer):
    nearest = archer.findNearestEnemy()
    if archerTarget:
        hero.command(archer, "attack", archerTarget)
    elif nearest:
        hero.command(archer, "attack", nearest)

archerTarget = None

while True:
    # 如果射手目标被击败或不存在,那就找一个新的。
    if not archerTarget or archerTarget.health <= 0:
        # 将archerTarget设置为findStrongestTarget()返回的目标
        archerTarget = findStrongestTarget()
    
    friends = hero.findFriends()
    soldiers = hero.findByType("soldier")
    # 创建一个包含弓箭手的变量。
    archers = hero.findByType("archer")
    for i in range(len(soldiers)):
        soldier = soldiers[i]
        commandSoldier(soldier, i, len(soldiers));
    # 使用commandArcher()命令你的弓箭手
    for j in range(len(archers)):
        archer = archers[j]
        commandArcher(archer)

我们中的间谍

# 内门可以撑很长时间。
# 然而,其中一个农民是食人魔的间谍!
# 有一个提示!间谍的名字中有一个字母是"z"。

# 这个函数可以检查单词中的特定字母。
# 一个字符串只是一个数组! 像数组一样循环它。
def letterInWord(word, letter):
    for i in range(len(word)):
        character = word[i]
        # 如果字符等于字母,则返回 True
        if character == "z" or character == "Z":
            return True
    # 因为字母不在单词里,所以返回 False
    return False


spyLetter = "z"
friends = hero.findFriends()

for friend in friends:
    friendName = friend.id
    if letterInWord(friendName, spyLetter):
        # 揭露间谍!
        hero.say(friendName + " is a spy!")
    else:
        hero.say(friendName + " is a friend.")

冰猎人

# 追捕4只牦牛。 只选择小的。
# 小牦牛名称包含一个"bos"子字符串。

# 这个函数检查一个单词是否包含一个子字符串。
def isSubstring(word, substring):
    # 我们通过迭代开始索引。
    rightEdge = len(word) - len(substring)
    # 循环访问单词的索引。
    for i in range(rightEdge + 1):
        # 对于它们中的每一个循环通过子字符串
        for j in range(len(substring)):
            # 为单词的索引使用偏移量。
            shiftedIndex = i + j
            # 如果字母不一样:
            if word[shiftedIndex] != substring[j]:
                # 检查Word中的下一个开始索引。
                break
            # 如果它是子字符串中的最后一个字母:
            if j == len(substring) - 1:
                # 然后子字符串在单词中。
                return True
    # 我们还没有找到这个词的子字符串。
    return False

# 循环通过所有敌人。
enemies = hero.findEnemies()
for e  in range(len(enemies)):
    enemy = enemies[e]
    # 使用函数isSubstring来检查
    #  37/5000 如果敌方名称(id)包含“"bos":
    if enemy and isSubstring(enemy.id, "bos"):
        # 然后打败它。
        while enemy.health > 0:
            hero.attack(enemy)

模拟侵略

# 保护村庄免受食人魔侵害。
# 注意食人魔,农民,其中有食人魔伪装成“农民”。

# 该功能检查文本是否以该词开头。
def startsWith(text, word):
    # 如果这个词更长,那么文本:
    if len(word) > len(text):
        return False
    # 循环访问单词和文本的索引。
    for index in range(len(word)):
        # 如果具有相同索引的字符不同:
        if word[index] != text[index]:
            # 然后这个词与文本不一致。
            return False
    # 我们检查了所有的文本,它们都是一样的。
    return True

ogreNameStart = "Zog"

while True:
    enemy = hero.findNearestEnemy()
    suspect = hero.findNearest(hero.findFriends())
    #if hero.gold > hero.costOf("archer"):
    #    hero.summon("archer")
    #if suspect.type == "archer":
    #    soldier = suspect
    # 使用函数“startsWith”来检查
    # 如果有嫌疑者的名字(id)以“Zog”开头,则攻击:
    if enemy:
        # 否则,如果有敌人,则攻击它:
        while enemy.health > 0:
    #        hero.command(soldier, "attack", suspect)
            hero.attack(enemy)
    #        hero.command(soldier, "attack", enemy)
            # 其他情况返回红色的X标记:
    if startsWith(suspect.id, ogreNameStart):
        while suspect.health > 0:
            hero.attack(suspect)
    #        hero.command(soldier, "attack", suspect)
    hero.move({"x": 27, "y": 27})
    #    hero.command(soldier, "move", {"x": 27, "y": 27})

吵闹 安静

# 把英雄和他们的宠物移到出口处

def onHear(event):
    # 获取音量和口令。
    words = event.message.split(" ")
    volume = words[0]
    password = words[1]
    # 口令是否应该大声:
    if volume == "Loud":
        # 宠物用大写字母重复它。
        pet.say(words[1].toUpperCase())
    # 口令是否应该保持安静:
    if volume == "Quiet":
        # 宠物以小写字母重复。
        pet.say(words[1].toLowerCase())
    pet.moveXY(pet.pos.x+ 24, pet.pos.y)

def passDoor():
    guard = hero.findNearest(hero.findFriends())
    password = guard.password
    # 口令是否应该大声:
    if guard.isLoud:
        # 在口令上使用.toUpperCase()方法。
        hero.say(password.toUpperCase())
        pass
    # 口令是否应该保持安静:
    elif guard.isQuiet:
        # 在口令上使用.toLowerCase()方法。
        hero.say(password.toLowerCase())
        pass
    hero.moveXY(hero.pos.x+ 24, hero.pos.y)

# 让宠物听到警卫的声音。
pet.on("hear", onHear)
# 英雄通过门的代码。
hero.moveXY(10, 14)
passDoor()
passDoor()

方便敌方

# Ogres are hiding in woods. Protect the peasants.
# The last word in the peasants' messages are a hint.

for x in range(8, 73, 16):
    hero.moveXY(x, 22)
    # 农民知道需要召唤谁。
    peasant = hero.findNearest(hero.findFriends())
    message = peasant.message
    if message:
        # 单词由空格分隔。
        words = message.split(" ")
        # "words"是来自"message"的一组单词。
        # 最后一句话。这是必需的单位类型。
        soldierName = words[1]
        # 召唤所需的单位类型。
        hero.summon(soldierName)

while True:
    
    for i in range(len(hero.built)):
        unit = hero.built[i]
        # 命令单位保卫单位的阵地。
        enemy = unit.findNearestEnemy()
        if enemy:
            hero.command(unit, "attack", enemy)
    
    # 捍卫你最后一个点:
    hero.moveXY(72, 22)
    enemy = hero.findNearestEnemy()
    if enemy and hero.distanceTo(enemy)<10:
        while enemy.health > 0:
            if hero.isReady("cleave"):
             hero.cleave(enemy)
            else:
                hero.attack(enemy)
    
    

钢爪间隙

# 这个关卡介绍了%操作符,也称为模操作符。
# a % b返回除以b的余数
# 当索引可能大于长度时,这可以用于环绕数组的开头。

defendPoints = [{"x": 35, "y": 63},{"x": 61, "y": 63},{"x": 32, "y": 26},{"x": 64, "y": 26}]

summonTypes = ["soldier","soldier","soldier","soldier","archer","archer","archer","archer"]

# 你用360金开始建造一个士兵和弓箭手的混合体。
# Self.Bug是你曾经建造的一个部队数组。
# 在这里,我们使用"len(self.built) % len(summonTypes)"来环绕召唤类型数组。
def summonTroops():
    type = summonTypes[len(hero.built) % len(summonTypes)]
    if hero.gold >= hero.costOf(type):
        hero.summon(type)

def commandTroops():
    friends = hero.findFriends()
    for i in range(len(friends)):
        friend = friends[i]
        # 根据friendIndex使用%来环绕防卫点
        friendIndex = defendPoints[i % len(defendPoints)]
        # 命令你的手下捍卫防卫点
        hero.command(friend, "move", friendIndex)
        enemy = friend.findNearestEnemy()
        if enemy:
            if friend.distanceTo(enemy) < 25:
                hero.command(friend, "attack", enemy)
        if friend.health < friend.maxHealth / 3:
            hero.command(friend, "move", {"x":50, "y":50})
        
        

while True:
    summonTroops()
    commandTroops()

无暇的宝石对

# 收集4对宝石。
# 每一对都必须包含相同的宝石。

# 该函数返回两个具有相同值的项目。
def findValuePair(items):
    # 检查数组中的每个可能的对。
    # 迭代索引'i'从0到最后一个。
    for i in range(len(items)):
        itemI = items[i];
        # 从0到最后迭代索引'j'。
        for j in range(len(items)):
            # 如果它是相同的元素,则跳过它。
            if i == j:
                continue
            itemJ = items[j];
            # 如果我们发现一对有两个相同的宝石,则返回它们。
            if itemI.value == itemJ.value:
                return [itemI, itemJ]
    # 如果没有存在配对,则返回一个空数组。
    return None

while True:
    gems = hero.findItems()
    gemPair = findValuePair(gems)
    # 如果发现宝石对存在,则收集宝石!
    if gemPair:
        gemA = gemPair[0]
        gemB = gemPair[1]
        # 移动到第一个宝石处。
        hero.moveXY(gemA.pos.x, gemA.pos.y)
        # 返回从向导中得到加速。
        hero.moveXY(40,44)
        # 然后移动到第二个宝石处。
        hero.moveXY(gemB.pos.x, gemB.pos.y)
        # 返回从向导中得到加速。
        hero.moveXY(40,44)
        pass

驯鹿苏醒

# 这个数组包含每个驯鹿的状态。
deerStatus = [ 'asleep', 'asleep', 'asleep', 'asleep', 'asleep' ]

# 这个数组包含了我们的驯鹿。
friends = hero.findFriends()

# 循环每只驯鹿,找到醒着的:
for deerIndex in range(len(friends)):
    reindeer = friends[deerIndex]
    if reindeer.pos.y > 30:
    # Y位置>30的驯鹿不在笔下。
    # 如果是这样,把驯鹿的条目设置为"awake"。
        deerStatus[deerIndex] = 'awake'

    pass

# 循环历遍每只鹿状态并报告给Melek。
for statusIndex in range(len(deerStatus)):
    # 告诉Merek驯鹿索引及其位置。
    # 比如说“驯鹿2是睡着了”。
    hero.say('reindeer ' + statusIndex + ' ' +deerStatus[statusIndex])
    pass

大炮陆战队

# 我们应该派士兵去保卫村庄。
# 我们还需要清除旧的陷阱。
# 对于这两个目标,我们将使用炮兵!
# 炮兵可以发射士兵和反陷阱。

# 侦察兵准备了着陆区的地图。
# 该地图是单元格为字符串的二维数组。
landingMap = hero.findNearest(hero.findFriends()).landingMap

# 向大炮显示行,列和目标类型。
# 要获取元素,请使用array [i] [j]
# 首先,让我们看看第0行和第0列。
cell = landingMap[0][0]
# 接下来,说出坐标和有什么。
hero.say("行 0 列 0 " + cell)

# 下一个单元格是第3行和第2列.
hero.say("行 3 列 2 " + landingMap[3][2])

# 现在就为下一点做好准备:
# 第二行和第一列。
hero.say("行 2 列 1" + landingMap[2][1])
# 第1行和第0列。
hero.say("行 1 列 0" + landingMap[1][0])
# 第0行和第2列。
hero.say("行 0 列 2" + landingMap[0][2])
# 第一行和第三列。
hero.say("行 1 列 3" + landingMap[1][3])

力量的源点

# 你需要找到并摧毁3个骷髅。
# 骨骼和物品在力量的源点召唤。
# 移动到某一点并说出咒语:"VENI"。
# 若要找到所需的点,请使用巫师的地图。
# 0是不好的点。 正数是好的。

spell = "VENI"
# 地图的点是一个二维数组的数字。
wizard = hero.findNearest(hero.findFriends())
powerMap = wizard.powerMap

# 该函数将网格转换为x-y坐标。
def convert(row, col):
    return {'x': 16 + col * 12, 'y': 16 + row * 12}

# 通过PoPMAP循环查找正数。
# 首先,循环遍历行的索引。
for i in range(len(powerMap)):
    # 每一行都是一个数组。 遍历它。
    for j in range(len(powerMap[i])):
        # 获取i行和j列的值。
        pointValue = powerMap[i][j]
        # 如果是正数:
        if pointValue > 0:
            # 使用convert来获取XY坐标。
            position = convert(i, j)
            # 移动到那里,说"VENI"并做好准备!
            hero.moveXY(position.x, position.y)
            hero.say(spell)
        # 找到并攻击敌人
        enemy = hero.findNearestEnemy()
        if enemy:
            while enemy.health > 0:
                hero.attack(enemy)
            

周界防御

# 我们需要在村子周围建哨塔。
# 每个农民都可以建造一座塔。
# 向他们展示建造的地方。
# 这些塔是自动的,会攻击城外所有的单位。

# 首先随着步骤20,沿着北边界(y = 60)从x = 40移动到x = 80。
# `range` 不包括第二个边缘。
for x in range(40, 81, 20):
    # 在每个点上移动并说点什么。
    hero.moveXY(x, 60)
    hero.say("Here")
# 接着负步骤-20,沿着东边界(x=80)从y=40到y=20。
for y in range(40, 19, -20):
    hero.moveXY(80, y)
    hero.say("Here")
# 继续其余两个边界。
# 接下来是反步骤-20.从x = 60到x = 20的南方边界(y = 20),0。
for x in range(60, 19, -20):
    # 在每个点上移动并说点什么。
    hero.moveXY(x, 20)
    hero.say("Here")
# 接下来是步骤20,从y = 40到y = 60的西边界(x = 20)。
for y in range(40, 61, 20):
    hero.moveXY(20, y)
    hero.say("Here")

# 别忘了藏在村子里。
hero.moveXY(50, 40)

网格雷区

# 食人魔在村子里行进。
# 我们有90秒的时间建造雷区。
# 我们将用他们严格的队形来对付他们。

# 使用嵌套循环来构建网格雷区。
# 首先用步骤8迭代x从12到60的坐标。
for x in range(12, 12 + 8 * 6, 8):
    # 用步骤8,对于每一个X迭代,Y从12到68。
    for y in range(12, 12 + 8 * 7, 8):
        # 对于每个点建立"fire-trap"。
        hero.buildXY("fire-trap", x, y)
        pass
    # 每列后,最好避免陷入自己的陷阱。
    hero.moveXY(hero.pos.x + 8, hero.pos.y)

# 现在等待并注意即将到来的食人魔。
# 当他们靠近(距离英雄约20米)时,与你的英雄一起引爆地雷。
# 只要在最近的地雷移动即可。
while True:
    enemy = hero.findNearestEnemy()
    if enemy and hero.distanceTo(enemy) < 20:
        hero.moveXY(hero.pos.x - 8, y)


联合作战(绝对防御)

# 练习用取模从数组中循环取值
defendPoints = [{'x':66, 'y':48},{'x':66, 'y':38},{'x':66, 'y':28},{'x':56, 'y':48}, {'x':56, 'y':38}, {'x':56, 'y':28}, {'x':46, 'y':48}, {'x':46, 'y':38}, {'x':46, 'y':28}]
# 在数组array中编排好兵种组合
summonTypes = ["archer", "soldier", "archer", "soldier", "archer", "soldier", "archer", "soldier"]


def summonTroops():
    # 用%取模来循环预设的征兵方案 len(self.built)
    type = summonTypes[len(hero.built) % len(summonTypes)]
    if hero.gold >= hero.costOf(type):
        hero.summon(type)

def commandTroops():
    for i in range(len(hero.built)):
        friend = hero.built[i]
        if friend.type != 'palisade':
            # 用friendIndex使用%来环绕防卫点
            friendIndex = defendPoints[i % len(defendPoints)]
            hero.command(friend, "move", friendIndex)
            enemy = friend.findNearestEnemy()
            if enemy:
                    hero.command(friend, "attack", enemy)
            
    
def collectionCoins():
    items = hero.findItems()
    item = hero.findNearest(items)
    enemy = hero.findNearestEnemy(enemy)
    if enemy and hero.distanceTo(enemy) < 10:
        while enemy.health > 0:
            if hero.isReady("bash"):
                hero.bash(enemy)
            else:
                hero.attack(enemy)
    else: 
        if item.type == 'coin' or item.type == 'gem':
            hero.move(item.pos)
    
        
            
    
    
while True:
    collectionCoins()
    summonTroops()
    commandTroops()

# 目标是生存30秒,并且保持地雷完好至少30秒。
# 有一定概率失败

defendPoints = [{'x':75, 'y':65}, {'x':75, 'y':45}, {'x':75, 'y':25}]

def summonTroops():
    if hero.gold >= hero.costOf('griffin-rider'):
        hero.summon('griffin-rider')

def commandAttack():
    # 命令你的狮鹫骑士攻击食人魔。
    for i in range(len(hero.built)):
        friend = hero.built[i]
        if friend.type != 'palisade':
            # 用friendIndex使用%来环绕防卫点
            friendIndex = defendPoints[i % len(defendPoints)]
            hero.command(friend, "move", friendIndex)
            enemy = friend.findNearestEnemy()
            if enemy and enemy.type != 'fangrider':
                    hero.command(friend, "attack", enemy)
            
    
    
def pickUpCoin():
    # 收集硬币
    item = hero.findNearestItem()
    if item.type == 'coin' or item.type == 'gem':
        hero.move(item.pos)
        
    
    
def heroAttack():
    # 你的英雄应该攻击对方的骑士,跨过雷区的那些。
    enemies = hero.findEnemies()
    enemy = hero.findNearest(enemies)
    if enemy and enemy.pos.x < 38:
        while enemy.health > 0:
            hero.attack(enemy)
        
    
while True:
    # 调用一个函数,取决于目前决定要做什么。
    summonTroops()
    pickUpCoin()
    commandAttack()
    heroAttack()
        
        

劳心劳力

# 食人魔巫师为您准备了一堆惊喜。

# 定义一个 chooseTarget 函数,让它接受 friend 参数的输入
def chooseStrategy(friend):
    # 根据士兵的类型返回要攻击的目标。
    # 士兵应该攻击巫师,弓箭手应该攻击最近的敌人。
    if friend.type == 'soldier':
        hero.command(friend, "move", {'x':60, 'y':40})
        witches = hero.findByType("witch")
        witch = friend.findNearest(witches)
        if witch:
            hero.command(friend, "attack", witch)
        else:
            enemy = friend.findNearestEnemy()
            if enemy:
                hero.command(friend, "attack", enemy)
    if friend.type == 'archer':
        enemy = friend.findNearestEnemy()
        if enemy:
            hero.command(friend, "attack", enemy)



while True:
    orges = hero.findByType("ogre")
    orge = hero.findNearest(orges)
    friends = hero.findFriends()
    for friend in friends:
        # 用你的 chooseTarget 函数决定要攻击什么。
        chooseStrategy(friend)
    
    

多少钱

# 计算花园的周长和面积
# 并为此支付合理的价格。

# 栅栏和草坪的价格。
fencePrice = 3 # 每米。
lawnPrice = 2 # 每平方米。
# 你需要工头。
foreman = hero.findNearest(hero.findFriends())
corners = foreman.corners
# 获取有关花园的信息。
bottomLeft = corners.bottomLeft
topRight = corners.topRight
# 计算花园的尺寸。
width = topRight.x - bottomLeft.x
height = topRight.y - bottomLeft.y
# 找到花园的周边(米):
perimeter = (width + height) * 2
# 使用fencePrice计算围栏成本:
fenceCost = fencePrice * perimeter
# 查找花园面积(平方米):
area = width * height
# 使用lawnPrice计算草坪成本:
lawnCost = area * lawnPrice

# 总成本是栅栏和草坪成本的总和
totalCost = fenceCost + lawnCost
hero.say("The total price is " + totalCost)
# 支付账单。
foreman.bill(totalCost)

火山战士

# 完成圣骑士矩阵以保护村庄。

# 该函数找到最左边的单位。
def findMostLeft(units):
    if len(units) == 0:
        return None
    mostLeft = units[0]
    for unit in units:
        if unit.pos.x < mostLeft.pos.x:
            mostLeft = unit
    return mostLeft

# 这个函数找到最底部的单位:
def findMostBottom(units):
    if len(units) == 0:
        return None
    mostBottom = units[0]
    for unit in units:
        if unit.pos.y < mostBottom.pos.y:
            mostBottom = unit
    return mostBottom

paladins = hero.findByType("paladin")
# 使用findMostLeft函数查找左上角的圣骑士:
left = findMostLeft(paladins)
# 用findMostBottom函数查找右下角的圣骑士:
bottom = findMostBottom(paladins)

# 使用左上角圣骑士的X坐标:
# 以及右下角圣骑士的Y坐标:
x = left.pos.x
y = bottom.pos.y
# 移到上一步中的{X,Y}点:

hero.moveXY(x, y)
# 在火山爆发时形成护盾:
while True:
    hero.shield()


矩形形态

# 在矩形队形中形成士兵和弓箭手。

# 单位之间的距离。
step = 8

# 首先组建士兵。
sergeant = hero.findNearest(hero.findByType("soldier"))
# 左下角的坐标。
soldierX = 8
soldierY = 8
# 地层的宽度和高度。
width = sergeant.rectWidth
height = sergeant.rectHeight

for x in range(soldierX, soldierX + width + 1, 8):
    for y in range(soldierY, soldierY + height + 1, 8):
        hero.summon("soldier")
        lastUnit = hero.built[len(hero.built)-1]
        # 使用x / y变量命令最后一个内置单元:
        hero.command(lastUnit, "move", {'x':x, 'y':y})

# 接下来组建弓箭手。
sniper = hero.findNearest(hero.findByType("archer"))
# 左下角的坐标。
archerX1 = 48
archerY1 = 8
# 右上角的坐标。
archerX2 = sniper.archerX2
archerY2 = sniper.archerY2

for x in range(archerX1, archerX2 + 1, 8):
    for y in range(archerY1, archerY2 + 1, 8):
        # 召唤一个射手。
        hero.summon("archer")
        # 查找最后构建的单位。
        lastUnit = hero.built[len(hero.built) - 1]
        
        # 使用x / y变量命令最后一个内置单元:
        hero.command(lastUnit, "move", {'x':x, 'y':y})
        pass

人神

# 形成围绕农民的单位矩形。
# 你需要2个弓箭手和2个士兵。

# 这个函数可以帮助你。
def summonAndSend(type, x, y):
    hero.summon(type)
    unit = hero.built[len(hero.built)-1]
    hero.command(unit, "move", {"x": x, "y": y})

# 矩形应该围绕农民形成。
centerUnit = hero.findNearest(hero.findFriends())
# 它是矩形的中心。
center = centerUnit.pos
# 你也需要高度和宽度。
rectWidth = centerUnit.rectWidth
rectHeight = centerUnit.rectHeight

# 第一名士兵到矩形的左下角。
leftBottomX = center.x - rectWidth / 2
leftBottomY = center.y - rectHeight / 2
summonAndSend("soldier", leftBottomX, leftBottomY)

# 弓箭手在左上角。
leftTopX = center.x - rectWidth / 2
leftTopY = center.y + rectHeight / 2
summonAndSend("archer", leftTopX, leftTopY)

# 召唤并派遣一名士兵到右上角。
rightTopX = center.x + rectWidth / 2
rightTopY = center.y + rectHeight /2
summonAndSend("soldier", rightTopX, rightTopY)
# 召唤并派遣一名弓箭手到右下角。
rightBottomX = center.x + rectWidth / 2
rightBottomY = center.y - rectHeight /2
summonAndSend("archer", rightBottomX, rightBottomY)


# 现在躲起来或战斗。
# hero.moveXY(68, 59)
while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        while enemy.health > 0:
            hero.attack(enemy)
            




笨拙的圆

# 找到那些不在圆内的士兵。

# 所有的士兵都应该在半径范围内:
circleRadius = 20

# 函数检查单元是否放置在圆上。
# 以半径为中心的英雄。
def onCircle(unit, radius):
    distance = hero.distanceTo(unit)
    # 我们检查近似值。
    inaccuracy = 2
    minDistance = radius - inaccuracy
    maxDistance = radius + inaccuracy
    return distance <= maxDistance and distance >= minDistance

while True:
    soldiers = hero.findByType("soldier")
    for soldier in soldiers:
        # 使用循环函数查找
        # 如果士兵不在圈子里:
        distance = onCircle(soldier, circleRadius)
        if not distance:
            # 然后说出他们的名字(id)以去掉那个:
            hero.say(soldier)
        pass

牦牛行径

# 计算牦牛行径圆周的周长。

# 第一个牦牛圈。
yak1 = hero.findNearestEnemy()
# 到牦牛的距离是半径。
radius1 = hero.distanceTo(yak1)
# 周长按以下方式计算:
circumference1 = 2 * Math.PI * radius1
# 我们来说出结果。
hero.say(circumference1)

# 移动到下一个标记。
hero.moveXY(60, 34)
# 从第二个圈子里找到牦牛。
yak2 = hero.findNearestEnemy()
# 找到第二个圆的半径。
radius2 = hero.distanceTo(yak2)
# 计算第二圆的周长:
circumference2 = 2 * Math.PI * radius2
# 我们来说出结果。
hero.say(circumference2)

严峻的决心

# 你的目标是保护 Reynaldo
def getboss():
    boss=None
    for target in hero.findEnemies():
        if target.type=='warlock':
            boss = target
    return boss

# 找到生命值最低的武士
def lowestHealthPaladin():
    lowestHealth = 99999
    lowestFriend = None
    friends = hero.findFriends()
    for friend in friends:
        if friend.type != "paladin":
            continue
        if friend.health < lowestHealth and friend.health/friend.maxHealth < 0.8:
            lowestHealth = friend.health
            lowestFriend = friend
    return lowestFriend

def commandPaladin(paladin):
    # 使用函数 lowestHealthPaladin() 找到生命值最低的武士,并治疗
    weaker = lowestHealthPaladin()
    if weaker and paladin.canCast('heal',weaker):
        hero.command(paladin, 'cast',"heal", weaker)
    # if paladin.health/paladin.maxHealth<0.3:
    #    hero.comlmand(paladin, "shield")
    else:
        hero.command(paladin, "attack", friend.findNearestEnemy())
        
    # 你能使用 paladin.canCast("heal") 和 command(paladin, "cast", "heal", target)
    # 武士也能防御:command(paladin, "shield")
    # 不要忘了他们还能攻击
def commandPeasant(friend):
    hero.command(friend, "move", friend.findNearestItem().pos)

def commandGriffin(friend):
    # boss=getboss()
    # if boss:
    #     hero.command(friend, "attack", boss)
    # else:
    #     hero.command(friend, "attack", friend.findNearestEnemy())
    hero.command(friend, "attack", friend.findNearestEnemy())
    

def commandFriends():
    # 指挥你的队友
    friends = hero.findFriends()
    for friend in friends:
        if friend.type == "peasant":
            commandPeasant(friend)
        elif friend.type == "griffin-rider":
            commandGriffin(friend)
        elif friend.type == "paladin":
            commandPaladin(friend)

while True:
    commandFriends()
    if hero.gold>hero.costOf('griffin-rider'):
        hero.summon("griffin-rider")
    # 召唤 格里芬骑士

寻找开始

# Senick试图找到难以捉摸的Burleous Majoris!
# 但他不知道Burleous Majoris会有多大......
# 找到这个树妖人口的平均大小作为基线!

# 该函数返回数组中所有树妖的平均大小。
def averageSize(burls):
    sum = sumSize(burls)
    # 记住平均值是零件总和除以量!
    return sum / len(burls)

# 这个函数应该返回所有尺寸的总和。
def sumSize(burls):
    # 使用burls'size'实现sum函数:
    sum = 0
    #hero.say(len(burls))
    for i in range(len(burls)):
        burl = burls[i]
        sum = sum + burl.size
    
    return sum

while True:
    # 通过调用'averageSize'函数来查找树妖的平均大小。
    monsters = hero.findEnemies()
    averagesize = averageSize(monsters)
    # 说出看到的树妖的平均大小!
    if averagesize:
        hero.say(averagesize)
        pass
    else:
        hero.say("I do not get averagesize!")

峰会之门

花了一段时间的峰会之门代码公布出来,其中有些地方参考了国外大神。
如有bug,欢迎反馈。

summonTypes = ['griffin-rider']
tactick = 'hold'
stage = 1

# 这里定义如何召唤士兵
def summonTroops():
    type = summonTypes[len(hero.built) % len(summonTypes)]
    if hero.gold > hero.costOf(type):
        hero.summon(type)

# 让战士发现最低血量的友军
def lowestHealthPaladin():
    lowestHealth = 99999
    lowestFriend = None
    # 遍历循环友军
    friends = hero.findFriends()
    for friend in friends:
	    # 找到血量小于lowestHealth,并且进行赋值操作
        if friend.health < lowestHealth and friend.health < friend.maxHealth:
	        # 改变血量最低值
            lowestHealth = friend.health
            # 赋值给血量最低的友军
            lowestFriend = friend
    return lowestFriend

# 命令战士进行补血或攻击
def commandPaladin(paladin):
    if (paladin.canCast("heal")):
        # 优先治疗英雄
        if (hero.health < hero.maxHealth * 0.8):
            target = self
        else:
            target = lowestHealthPaladin()
        if target:
            hero.command(paladin, "cast", "heal", target)
    elif (paladin.health < 100):
        # 再治疗战士
        hero.command(paladin, "shield")
    elif stage < 4:
        # 如果关卡小于4,让战士在这里进行驻守
        hero.command(paladin, "move", {'x': 94, 'y': 34})
    elif stage == 5:
        # 如果关卡等于5,让战士到达这里,只进行辅助加血而不攻击
        hero.command(paladin, "move", {'x': 284, 'y': 33})
    else:
        # 优先攻击warlock,如果warlock已死,攻击其他的enemy
        target = hero.findNearestEnemy()
        if (warlock):
            target = warlock
        if (target):
            hero.command(paladin, "attack", target)

# 命令士兵
def commandSoldier(soldier):
    
    target = hero.findNearestEnemy()
    if (warlock):
        target = warlock
    if stage == 3:
        hero.command(soldier, "move", {'x': 84, 'y': 34})
    elif (target):
        hero.command(soldier, "attack", target)

# 控制友军的函数
def commandFriends():
    friends = hero.findFriends()
    for friend in friends:
        if tactick == 'hold':
            hero.command(friend, "defend", {'x': 1, 'y': 40})
        elif friend.type == "paladin":
            commandPaladin(friend)
        else:
            commandSoldier(friend)

# 英雄移动的函数模块
def moveTo(position):
    if (hero.isReady("jump")):
        hero.jumpTo(position)
    else:
        hero.move(position)

# 英雄攻击模块
def attack(target):
    if target:
        if (hero.distanceTo(target) > 10):
            moveTo(target.pos)
        elif hero.canCast("chain-lightning", target):
            hero.cast("chain-lightning", target)
        else:
            hero.attack(target)
        

# 寻找金币的模块
def pickUpNearestItem():
    nearestItem = hero.findNearestItem()
    if nearestItem:
        moveTo(nearestItem.pos)


commandFriends()
hero.moveXY(31, 56)
while True:
    # 找到最近的投石车
    catapult = hero.findNearest(hero.findByType('catapult'))
    # 找到最近的男巫
    warlock = hero.findNearest(hero.findByType('warlock'))
    # 找到最近的女巫
    witch = hero.findNearest(hero.findByType('witch'))
    # 找到最近的敌人
    target = hero.findNearestEnemy()
    # 找到最近的物品
    nearestItem = hero.findNearestItem()
    # 记录英雄花费的时间
    now = hero.time
    # 逻辑如下,依次进行
    if catapult:
        stage = 1
        attack(catapult)
    elif now < 20:
        tactick = 'defend'
        stage = 2
        moveTo({"x": 50, "y": 33})
    elif stage < 4:
        if target:
            stage = 3
            attack(target)
        else:
            moveTo({"x": 172, "y": 46})
        if hero.pos.x > 170:
            stage = 4
    elif stage < 5:
        if hero.pos.x < 240:
            moveTo({"x": 274, "y": 35})
            tactick = 'defend'
        elif nearestItem and hero.distanceTo(nearestItem) < 10:
            pickUpNearestItem()
            tactick = 'attack'
        elif (warlock):
            target = warlock
            summonTroops()
            attack(target)
        elif target and target.type != 'gates':
            attack(target)
        elif nearestItem and hero.distanceTo(nearestItem) < 45:
            pickUpNearestItem()
            tactick = 'defend'
            summonTroops()
        else:
            attack(target)
        if hero.pos.x > 290:
            stage = 5
            # 如果女巫存在,优先攻击女巫
            if (witch):
                attack(witch)
        tactick = 'attack'
    else:
        summonTroops()
        attack(target)
    commandFriends()


冰川

绕圈

#############################################################################
#镜像你的盟友围绕X移动。
# 向量可以当成是x,y位置。
# Vectors 可以反映两个位置之间的距离和方向。

# 使用Vector.subtract(vector1,vector2)来查找从vector2到vector1的方向和距离
# 使用 Vector.add(vector1, vector2) 找到你从 vector1 到 vector2 的位置
################################# 程序逻辑 ###################################
# 1. 确定中心的位置
# 2. 找到农民的位置
# 3. 得到农民到中心的向量 vector
# 4. 中心向量加上vector就是英雄应该要去的位置moveToPos
# 5. 让英雄移动到moveToPos(注意:moveToPos是矢量,包含着坐标,后面不要加.pos)
##############################################################################
# 在 X 点的中心创建一个新的 Vector
center = Vector(40, 34)

# 一个单位的位置实际是一个 Vector!
partner = hero.findByType("peasant")[0]

while True:
    # 第一,您要找到伙伴位置到 X 中心的 Vector(距离和方向)。
    vector = Vector.subtract(center, partner.pos)
    # 第二,找到你的英雄应该移动的位置,从中心开始,然后跟随向量。
    moveToPos = Vector.add(center, vector)

    # 第三,移动到moveToPos位置
    hero.move(moveToPos)
    pass


滑走

# Move to the red X mark while avoiding the yaks.
# use Vector.normalize(vector1) to create a vector in the same direction as vector1, but with a distance of 1
# use Vector.multiply(vector1, X) to create a vector in the same direction as vector1, but with its distance multiplied by X
#################################################################
###########################程序思路##############################
# 1. 得到目标与英雄间的向量
# 2. 向量归一化
# 3. 归一向量矢量化
# 4. 检测英雄到牦牛的距离向量
# 5. 如果距离小于10,将牦牛到英雄的向量添加到英雄行走的向量中,避开牦牛。
##################################################################
# The point you want to get to.
goalPoint = Vector(78, 34)
while True:
    goal = Vector.subtract(goalPoint, hero.pos)
    goal = Vector.normalize(goal)
    goal = Vector.multiply(goal, 10)
    yak = hero.findNearestEnemy()
    distance = hero.distanceTo(yak)
    if distance < 10:
        yak_vector = Vector.subtract(hero.pos, yak.pos)
        yak_vector = Vector.normalize(yak_vector)
        yak_vector = Vector.multiply(yak_vector, 10)
        goal = Vector.add(yak_vector, goal)
    moveToPos = Vector.add(hero.pos, goal)
    hero.move(moveToPos)

轰炸行动

轰炸行动求弧度在示意图如下所示:
示意图

# Incoming oscars!(这是食人魔的军事言论)。
# 你需要计算它们的攻击的角度。
# 用这个角度来指挥你的狮鹫轰炸机!
#####################################################################
#############################程序思路################################
# 1. 找到食人魔与英雄坐标之间的差值:(enemy.pos.y - hero.pos.y, enemy.pos.x - hero.pos.x)
# 2. 求其反正切函数
# 3. 将反正切函数转换为度数
# 4. 说出度数。
# 5. 狮鹫获取度数,进行轰炸(系统自动运行。)
#####################################################################
while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        # 找到攻击的向量
        raw = Math.atan2(enemy.pos.y - hero.pos.y, enemy.pos.x - hero.pos.x)
        # 使用三角法找出弧度中的角度!
        # 答案必须是度数!
        # 用 (180 / Math.PI)把弧度变换成度数
        degree = raw * (180 / Math.PI)
        # 说出角度!
        hero.say(degree)

调剂团(练习)

# 在Omarn 10米范围内任何地方为他投掷药水。
# 在它降落之前,站立靠近它,抓住药水。
# 别让药水掉在地上!

#########################################################################
#################################程序思路################################
# 整体思路: 让omarn扔药,如果有药,则去捡药;如果没有,就返回到omarn身边。
# 有药下:
#   (1)找到药到英雄的位置向量,归一化向量,到达药的位置。
#   (2)发现途中的地雷,并且避开地雷(关键)。
# 无药下:
#   (1)找到Omarn到英雄的位置向量,归一化向量,到达Omarn的位置。
#   (2)发现途中的地雷,并且避开地雷(关键)。
###########################################################################
def safePath(para1,para2):
    goal = Vector.subtract(para1, hero.pos)
    goal = Vector.normalize(goal)
    goal = Vector.multiply(goal, 10)
    distance = hero.distanceTo(para2)
    if distance < 5:
        fire_vector = Vector.subtract(hero.pos, para2.pos)
        fire_vector = Vector.normalize(fire_vector)
        fire_vector = Vector.multiply(fire_vector, 10)
        goal = Vector.add(fire_vector, goal)
    moveToPos = Vector.add(hero.pos, goal)
    return moveToPos

while True:
    potion = hero.findFriendlyMissiles()[0]
    firetraps = hero.findHazards()
    
    # 请记住,如果您移动距离超过3米,则会触发火灾陷阱!
    omarn = hero.findByType("potion-master")[0]
    if potion:
        dest = potion.targetPos;
        # 去拿药水。
        firetrap = hero.findNearest(firetraps)
        destination = safePath(dest, firetrap)
        hero.move(destination)
        pass
    else:
        if omarn and hero.distanceTo(omarn) > 10:
            # 移回Omarn
            firetrap = hero.findNearest(firetraps)
            destination = safePath(omarn.pos, firetrap)
            hero.move(destination)
            # 警告:isPathClear不适用于危险!
            pass
        else:
            hero.say("Hup, hup!")

冰上的雪花

# 对于这个关卡,我们需要对地面进行线分形和由6条线分形组成的六角形雪花。 检查指南以获取所需输出的图像。

def degreesToRadians(degrees):
    # 所有向量运算都需要用弧度来工作,而不是度。
    return Math.PI / 180 * degrees
    
# 这个函数创建了一个线分形。阅读它,让你了解递归概念。
def line(start, end):
    # 首先,我们需要得到完整的向量和它的大小来确定我们是否低于我们的最小阈值。
    full = Vector.subtract(end, start)
    distance = full.magnitude()
    if distance < 4:
        # 如果在我们的阈值距离下,我们将简单地沿着向量画一条线并完成(返回告诉我们退出函数)。
        hero.toggleFlowers(False)
        hero.moveXY(start.x, start.y)
        hero.toggleFlowers(True)
        hero.moveXY(end.x, end.y)
        return
        
    # 否则,我们将创建一个向量的半个数量级的分形。
    half = Vector.divide(full, 2)
    
    # 我们将创建4行分形(开始-> A,A -B,B -> A和->结束),因此我们需要计算中间位置A和B。
    A = Vector.add(half, start)
    
    # 为了得到B,我们需要将向量旋转90度,乘以2/3(因此它是原始大小的1/3),然后将其添加到A。
    rotate = Vector.rotate(half, degreesToRadians(90))
    rotate = Vector.multiply(rotate, 2 / 3)
    B = Vector.add(rotate, A)

    # 现在使用直线函数绘制4行。
    line(start, A)
    line(A, B)
    line(B, A)
    line(A, end)


def flake(start, end):
    # 要创建六角片,我们需要创建每次旋转60度的6条线分形。
    side = Vector.subtract(end, start)
    a = start
    b = end
    for i in range(6):
        line(a, b)
        # 为了得到下一条边,我们需要旋转60度的边。
        margin = Vector.subtract(b, a)
        a = Vector.add(margin, a)
        rotate = Vector.rotate(margin, degreesToRadians(60))
        # 现在需要重新设置A和B的开始和结束点的新的一面。
        b = Vector.add(rotate, b)
        

whiteXs = [Vector(12, 10), Vector(60, 10)]
redXs = [Vector(64, 52), Vector(52, 52)]

# 您需要用每个函数的起始和结束向量来调用函数。
line(whiteXs[0], whiteXs[1])
# 一定要使用实际的向量对象——简单对象不能工作。
flake(redXs[0], redXs[1])
# Refresh often to avoid a memory leak and crash (working on it)

================================================================================================

帮助不大,可以联系作者进行线上解决哦~

既然拯救不了世界,就拿你的打赏买喵粮,去拯救楼下的流浪喵吧(✿◡‿◡)

我的咖啡厅~

  • 23
    点赞
  • 93
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Better_Zflyee

交个朋友,多多交流~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值