循环函数在类中定义

时间:2017-10-20 14:02:30

标签: python arrays class loops

我在我的类的init函数中定义了一个列表。我想将它作为参数传递到同一个类中定义的函数内。这个函数循环,每次获取user_input,然后对定义为父类中其他函数的列表执行操作。

我该怎么做?每次程序采用新的列表而不是在每个循环后对旧的列表进行操作,或者存在语法错误。

这是父类和init函数:

class game:
def __init__(self):
    import random
    self.inducerlist=[0,1,2,3]
    self.myArray=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
    self.myArray[random.choice(self.inducerlist)][random.choice(self.inducerlist)]=2

这就是功能

def users_choice(self,user_input,self.myArray=self.myArray):
    if user_input=='u':
        game.up(self)
    elif user_input=='d':
        game.down(self)
    elif user_input=='l':
        game.left(self)
    elif user_input=='r':
        game.right(self)
    while True:
        print self.myArray[0][0],"\t",self.myArray[0][1],"\t",self.myArray[0][2],"\t",self.myArray[0][3],"\n"
        print self.myArray[1][0],"\t",self.myArray[1][1],"\t",self.myArray[1][2],"\t",self.myArray[1][3],"\n"
        print self.myArray[2][0],"\t",self.myArray[2][1],"\t",self.myArray[2][2],"\t",self.myArray[2][3],"\n"
        print self.myArray[3][0],"\t",self.myArray[3][1],"\t",self.myArray[3][2],"\t",self.myArray[3][3],"\n"
        user_input = raw_input("u for upward direction, d for downwards, l for left and r for Right")
        game.users_choice(self,user_input,self.myArray=self.myArray)
        self.listfori = []
        self.listforj = []
        count = 0
        for i in range(0,4):
            for j in range(0,4):
                if self.myArray[i][j]==0:
                    count+=1
                    self.listfori.append(i)
                    self.listforj.append(j)
        if count > 0:
            if count > 1:
                randomindex = listfori.index(random.choice(listfori))
                self.myArray[listfori[randomindex]][listforj[randomindex]]=2
            else:
                self.myArray[listfori[0]][listforj[0]]=2
        else: 
            break
            print "Game over"

0 个答案:

没有答案