作为新程序员避免Python中的全局变量

时间:2014-07-12 18:23:14

标签: python variables global

我刚刚开始使用Python,通过LPtHW工作。我正在练习36,你可以设计自己的游戏。我正在尝试制作一个非常基本的游戏,但我在避免全局变量时遇到了麻烦。例如,为了对抗怪物,它会检查你是否有剑。目前我首先通过创建全局变量剑来实现此目的 剑= 0,然后当你获得剑时它的值变为1,那么当你对抗怪物时你就赢了全球剑== 1.我怎样才能改变我的编码以避免使用全局变量?

2 个答案:

答案 0 :(得分:2)

使用类是避免使用全局变量的主要方法。

例如,您可以创建一个 Player 类,而不是在程序开始时为 sword 声明一个全局变量,而该类的属性表示是否球员有一把剑。

在这个课程中,您可以创建一个方法,该方法返回玩家是否有剑,避免使用类 Player 之外的变量。

class Player():
    def __init__(self, sword):
        self.sword = sword
    def playerHasSword():
        return self.sword

答案 1 :(得分:0)

这是一个非常简单的课程......(包括战斗!!!)

import random
class PlayerKilled(Exception): #player died
     pass #just a mechanism to detect killing a player

DAMAGE_TABLE = { #how much damage for weapons
   "MACE":6,
   "SWORD":8,
   "DAGGER":5,
   "FISTS":3
}
class MOB:
    def __init__(self,name,hp,weapon="FISTS"):
        self.name = name
        self.hp = hp
        self.ac = 3 # defense
        self.level = 1
        self.weapon = weapon
        self.dead = False
    def battle(self,MOB2):
        attacker,defender = self, MOB2
        if random.random() > 0.5:
            print "%s Attacks First!"%MOB2.name
            attacker,defender = defender,attacker
        while not self.dead and not MOB2.dead:
            attacker.attack(defender)
            attacker,defender = defender,attacker
        return defender
    def attack(self,MOB2):
        dmg = sum(random.randint(1,DAMAGE_TABLE[self.weapon]) for _ in range(self.level))
        print "%s Attacks with %s for %s DMG!"%(self.name,self.weapon,dmg)
        try:
           MOB2.defend(dmg)
        except PlayerKilled:
           print "%s has killed %s"%(self.name,MOB2.name)

    def defend(self,dmg):
        if sum(random.randint(0,self.ac) for _ in range(self.level)) > dmg:
            print "%s blocks the attack"%self.name
            return 
        self.hp = self.hp - dmg
        if self.hp < 0:
            print "%s has died!"%self.name
            self.hp = 0
            self.dead = True
            raise PlayerKilled

p1 = MOB("player",20,"DAGGER")
p2 = MOB("vampire",20,"FISTS")
winner = p1.battle(p2)
print "%s WINS with %s HP left!"%(winner.name,winner.hp)