【网易官方】极客战记(codecombat)攻略-森林-平常的一天-usual-day Python

兽人,金币,布尔…… 看这么多次都腻了。最起码我们得把他们简化一点。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

简介

使用 与 (AND) 操作符时,如果第一个条件 (在 AND 左边那个) 为假,第二个条件 (右边那个) 永远不会执行。

你可以好好利用这点!

这些代码有可能出错:

enemy = hero.findNearestEnemy() # 如果 enemy 为 None,那么 AND 就是 False # 所以 enemy.type 不会执行,避开了错误。 if enemy and enemy.type == "munchkin":     hero.attack(enemy)

下面带有与操作符的代码不会有这个问题:

enemy = hero.findNearestEnemy() # 如果 enemy 为 None,获取 enemy.type 时会出错! if enemy.type == "munchkin":     hero.attack(enemy)

默认代码

# 打败食人魔,收集金币。一切都那么平常。 # 使用 与(AND) 在同一行检查存在性和类型。 while True:     enemy = hero.findNearestEnemy()     # 有了与(AND),只在敌人存在时检查类型     if enemy and enemy.type == "munchkin":         hero.attack(enemy)     # 寻找最近的物品

 

    # 如果有名为 “coin” (金币)的物品存在,那就快去收集它!

 

概览

与 (AND) 操作符具有短路求值 (short-circuit evaluation) 特性。

这句话的意思是,如果在 and 前面的表达式为 假 (或者 null), 那么在操作符后面的表达式不执行或不求值。

我们可以应用到对象属性的读取中,尤其是不确定对象是否存在的情况下。 比如,我们想读取敌人的类型,首先我们得确保那个敌人存在,否则会得到一个错误:

enemy = hero.findNearestEnemy() if enemy:     if enemy.type == "burl":         ## 做点啥

But we can make it shorter:

enemy = hero.findNearestEnemy() if enemy and enemy.type == "burl":         ## 做点啥

我们不需要担心敌人不存在的引用错误 (reference error),因为这种情况下第二部分不会执行

平常的一天 解法

# 打败食人魔,收集金币。一切都那么平常。 # 使用 与(AND) 在同一行检查存在性和类型。 while True:     enemy = hero.findNearestEnemy()     # 有了与(AND),只在敌人存在时检查类型     if enemy and enemy.type == "munchkin":         hero.attack(enemy)     # 寻找最近的物品     item = hero.findNearestItem()     # 如果有名为 “coin” (金币)的物品存在,那就快去收集它!     if item and item.type == "coin":         hero.moveXY(item.pos.x, item.pos.y)   本攻略发于极客战记官方教学栏目,原文地址为: https://codecombat.163.com/news/jikezhanji-senlinpingchangdeyitian 极客战记——学编程,用玩的!  
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄