为什么我不能在while循环运行时将所有变量保留在列表中

时间:2018-06-09 23:48:20

标签: python list loops while-loop

while not endgame:

        cardsOnTable = OnTable()

        faceUp1 = player1.dequeue()
        cardsOnTable.place('player1',faceUp1,False)

        faceUp2 = player2.dequeue()
        cardsOnTable.place('player2',faceUp2,False)


        print(str(cardsOnTable))
        size1 = player1.size()
        size2 = player2.size()
        print('Player1 : '+str(size1),'Player2 : '+str(size2))

        result = compareCard(faceUp1,faceUp2)
                   elif result == 0:
            print('WAR STARTS!!!')


                i = 0
                player1war = [] #a list for placing player1's card in war(cards on table)
                player2war = [] #a list for placing player2's card in war(cards on table)

                while i < nbWarCards:
                    faceDown1 = player1.dequeue()
                    player1war.append(faceDown1)
                    faceDown2 = player2.dequeue()
                    player2war.append(faceDown2)

                    i += 1

                for card in player1war:
                    cardsOnTable.place('player1',card,True)

                player1war.clear()

                for card in player2war:
                    cardsOnTable.place('player2',card,True)

                player2war.clear()

                            if player1.size() == 0 or player2.size() == 0:
            endgame = True

我的问题发生在我第一次运行此while循环时我尝试print(str(cardOnTable))时,它会给我[AS | AH],这就是我想要的。但是,当此while循环第二次运行时,它应该打印[A3 XX XX XX AS | AH XX XX XX A5],它只打印[A3 | A5]

这是我的class OnTable()

class OnTable:
    def __init__(self):
        self.__cards = []
        self.__faceUp = []


    def place(self,player,card,hidden):

        if player == 'player2':
            self.__cards.append(card)
            if hidden == False:
                self.__faceUp.append(False)
            elif hidden == True:
                self.__faceUp.append(True)
        elif player == 'player1':
            self.__cards.insert(0,card)
            if hidden == False:
                self.__faceUp.insert(0,False)
            elif hidden == True:
                self.__faceUp.insert(0,True)            

        #return self.__cards   
    def cleanTable(self):
        self.__cards.clear()
        self.__faceUp.clear()    


    def __str__(self):

        for i in range(len(self.__faceUp)):
            if self.__faceUp[i] == True:
                self.__cards[i] = 'XX'

        list1 = '['
        for item in self.__cards:
            list1 += (str(item)+' ')

        list1 = re.sub(' ', ' ', list1.strip())
        half = int(len(list1)//2)      
        list1 = list1[:half] + ' |' + list1[half:]

        return list1 + ']'     

我试图跟踪我的代码,并且我发现self.__cards在第二次player1.dequeue()之前拥有所有变量,然后它会丢失所有以前的变量。

有人可以告诉我们如何解决这个问题吗?谢谢

0 个答案:

没有答案