Python 3:获取IndexError:在shuffle方法上列出索引超出范围

时间:2018-06-12 01:20:00

标签: python

我正在建立一个二十一点命令行游戏,但我遇到了麻烦。我的甲板类对象上的随机播放功能不断出现IndexError:列表索引超出第29行的范围。这是一个零星的错误,id大概有50%的时间出现。 这是代码:

import random

#class constructor for cards
class card:
    def __init__(self, suit, card_name, card_value):
        self.suit = suit
        self.card_name = card_name
        self.card_value = card_value

#class constructor for the deck
class deck:
    def __init__(self):
        self.current_deck = []
        self.suits = ['hearts', 'diamonds','spades','clubs']
        self.cards = ['ace','2','3','4','5','6','7','8','9','10','jack','queen','king']
    def initialize(self):
        for i in range(len(self.suits)):
            for j in range(len(self.cards)):
                if (self.cards[j]=='2' or self.cards[j]=='3' or self.cards[j]=='4' or self.cards[j]=='5' or self.cards[j]=='6' or self.cards[j]=='7' or self.cards[j]=='8' or self.cards[j]=='9'):
                    self.current_deck.append(card(self.suits[i], self.cards[j], int(self.cards[j])))
                elif (self.cards[j]=='10' or self.cards[j]=='jack' or self.cards[j]=='queen' or self.cards[j]=='king'):   
                    self.current_deck.append(card(self.suits[i], self.cards[j], 10))
                else:
                    self.current_deck.append(card(self.suits[i], self.cards[j], 11))
    def shuffle(self):
        for card in self.current_deck:
            j = random.randint(0, len(playing_deck.current_deck))
            temp = card
            card = self.current_deck[j]
            self.current_deck[j] = temp

class dealer:
    def __init__(self):
        self.money = 10000
        self.hand = []
    def hit(self, deck_):
        self.hand.append(deck_.pop())
    def deal(self, deck_, player_):
        self.hand.append(deck_.pop())

class player: 
    def __init__(self, name):
        self.name = name
        self.money = 200
        self.hand = []
    def hit(self, deck_):
        self.hand.append(deck_.pop())

josh = player('josh')

playing_deck = deck()

playing_deck.initialize()
playing_deck.shuffle()

josh.hit(playing_deck.current_deck)


for i in range(len(playing_deck.current_deck)):
    print(vars(playing_deck.current_deck[i]))

1 个答案:

答案 0 :(得分:1)

您正在致电randint

  

返回一个随机整数 N ,使MainActivitya <= N <= b的别名。

如果不明白为什么这是一个问题,让我们使用一个更小的例子:

randrange(a, b+1)

这就是为什么Python通常使用半开放范围,而>>> a = ['x', 'y'] >>> len(a) 2 >>> a[0] 'x' >>> a[1] 'y' >>> a[2] IndexError: list index out of range >>> randint(0, 2) 1 >>> randint(0, 2) 2 # oops 代替a <= N < b。以及为什么您通常希望使用randrange代替a <= N <= b

或者,甚至更常见的是,当您发现自己达到randintrandint时,您很有可能需要randrange(它将一次性对整个列表进行随机重新排序) ,或shuffle(将从列表中选择一个值,而不需要先选择索引)等,所以浏览文档以查看是否已经编写了所需内容。