Python - 当它不应该时,列表变空

时间:2017-11-22 21:01:55

标签: python arrays list indexing pop

我正在尝试编写用于玩纸牌游戏的程序War但是在运行程序时出现此错误:

File "____________", line 65, in playWar
    userCard = userCurrent.pop()
IndexError: pop from empty list

我使用pop功能比较每个玩家的两张牌并确定哪个更大但我不确定为什么userCurrent列表会为空,因为while循环不应该重复如果userCurrent或computerCurrent列表为空。任何帮助表示赞赏。

from math import*
import random

DECK_SIZE = 52
HALF_DECK = 26

def main():
    userGamesWon = 0
    compGamesWon = 0

    playGame = input(("Welcome to the game of war! Type X to begin a game. "))

    while (playGame == "X" or playGame == "x"):

        deck = []

        for i in range(int(DECK_SIZE/13)):
            deck.extend([2,3,4,5,6,7,8,9,10,11,12,13,14])

        shuffledDeck = shuffle(deck)

        userDeck, compDeck = split(shuffledDeck)

        game = playWar(userDeck,compDeck)

        if (game == True):
            userGamesWon = userGamesWon + 1
        else:
            compGamesWon = compGamesWon + 1

        playGame = input(("Type X to begin another game, or press any other key to stop playing. "))


    print("Thanks for playing!")
    print("You won: ", userGamesWon, "time(s). Computer won: ", compGamesWon, "time(s)." )








def playWar(userDeck,compDeck):
    gameWon = 0

    userCurrent = userDeck
    print("Your hand: ", userCurrent)
    userWinnings = []

    compCurrent = compDeck
    print("Computer hand: ", compCurrent)
    compWinnings = []


    while (gameWon == 0): #Need to figure out how to tell if game is over
        while (userCurrent != [] or compCurrent != []):
            compCard = compCurrent.pop()
            userCard = userCurrent.pop()

            if (userCard > compCard):
                userWinnings = userWinnings + [userCard + compCard]
            elif (compCard > userCard):
                compWinnings = compWinnings + [userCard + compCard]
            else:
                 userCurrent = userCurrent
        userCurrent = userCurrent + userWinnings
        userCurrent = shuffle(userCurrent)
        userWinnings = []

        compCurrent = compCurrent + compWinnings
        compCurrent = shuffle(compCurrent)
        compWinnings = []

        if (userCurrent == [] or compCurrent == []):
            gameWon = 1

    if (len(userCurrent) == DECK_SIZE):
         print("YOU WIN.\nGood Game!")
         return True
    else:
        print("COMPUTER WINS.\nGood Game!")
        return False





def shuffle(deck): #write a randomizing program that takes a list as a parameter
    shuffledDeck = []
    for i in deck:
        rand = random.randint(0, len(deck)-1)
        shuffledDeck.insert(rand,i)

    return shuffledDeck


def split(shuffledDeck):

    return shuffledDeck[0:HALF_DECK], shuffledDeck[HALF_DECK:]



main()

1 个答案:

答案 0 :(得分:2)

在你的声明中,我相信你需要'和'而不是'或'。所以,它应该是:

while (userCurrent != [] and compCurrent != []):