-2

每个人。我正在尝试为模拟游戏编写一个非常基本的“随机事件”类。我收到错误 UnboundLocalError: local variable (?) is referenced before assignment ((?) 表示我使用随机数的任何变量)

population = 5
happiness = 5
order = 5

import random
class Event(object):
    def __init__(self, sort, pop, ordr, hap): 
        self.sort = sort
        self.pop = pop
        self.ordr = ordr
        self.hap = hap
    def event_type(self):
        if self.sort == 1:
            print "A hurricane has blasted through a major city."
            print "-2 Population."
            pop -= 2

        elif self.sort == 2:
            print "A parade for your nation has spontaneously"
            print "occured in the Capital. +2 Order. +1 Happiness"
            ordr += 2
            hap +=1

        elif self.sort == 3:
            print "A major civil rights movement has succeded in"
            print "getting citizens more rights. -2 Order. +2 Happiness"
            ordr -= 2 
            hap += 2

        elif self.sort == 4:
            print "Refugees from a warstricken country have flooded into"
            print "your land. +2 Population"
            pop += 2

        elif self.sort == 5:
            print "A new surveillance program has been put into place."
            print "+3 Order"
            ordr += 3

        else:
            print "-" * 10
randnum = random.randint(1, 10)
event1 = Event(radnum, population, order, happiness)
Event.event_type()
print population
print happiness
print order
4

1 回答 1

1

您需要引用您的类的属性, as popordr并且hap不是局部变量。self.在它们前面添加:

if self.sort == 1:
    print "A hurricane has blasted through a major city."
    print "-2 Population."
    self.pop -= 2

elif self.sort == 2:
    print "A parade for your nation has spontaneously"
    print "occured in the Capital. +2 Order. +1 Happiness"
    self.ordr += 2
    self.hap +=1

elif self.sort == 3:
    print "A major civil rights movement has succeded in"
    print "getting citizens more rights. -2 Order. +2 Happiness"
    ordr -= 2 
    hap += 2

elif self.sort == 4:
    print "Refugees from a warstricken country have flooded into"
    print "your land. +2 Population"
    self.pop += 2

elif self.sort == 5:
    print "A new surveillance program has been put into place."
    print "+3 Order"
    self.ordr += 3
于 2013-08-13T09:44:59.053 回答