-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

としてクラスの属性を参照する必要があり、popはローカル変数ではありませんordr。それらの前に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 に答える