0

誰かがこのプリントを正しく取得するのを手伝ってくれますか?

class Deck(object):
    def __init__(self):
        self.cards = []
        from random import shuffle
        shuffle(self.cards)

    #views all cards in the deck
    def view_deck(self):
        for x in self.cards:
            print(x.name)

    #takes in an (x) integer and views the top x cards of the deck
    def view_number_of_cards(self, cards_to_view):
        for x in self.cards[:cards_to_view]:
            print(x.name)

class Player(object):
    def __init__(self):
        self.hand = []
        self.row_1 = []
        self.row_2 = []
        self.row_3 = []
        self.row_4 = []
        self.row_5 = []
        self.rows = []
        self.rows.append(self.row_1)
        self.rows.append(self.row_2)
        self.rows.append(self.row_3)
        self.rows.append(self.row_4)
        self.rows.append(self.row_5)
        self.graveyard = []
        self.deck = Deck()

    #draw a card from deck to hand
    def draw_card(self):
        c = self.deck.cards
        cardDrawn = c.pop(0)
        self.hand.append(cardDrawn)

    #shuffle deck
    def shuffle_deck(self):
        from random import shuffle
        shuffle(self.deck.cards)

    def play_card(self, card, row):
        self.rows[row-1].append(card)
        self.graveyard.append(card)
        self.hand.remove(card)

    def update(self):
        i = 1
        for x in self.rows:
            print "Lane "+str(i)+": "+str(x[0]),
            i = i+1

これを試すと:

x = Player()
x.deck.cards = [1, 2, 3, 4]
x.draw_card()
x.play_card(x.hand[0], 1)
x.rows
[[1], [], [], [], []]
x.update()

これが起こる

Lane 1: 1

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    x.update()
  File "C:/Users/Carl/Desktop/try.py", line 53, in update
    print "Lane "+str(i)+": "+str(x[0]),
IndexError: list index out of range

コンソールで "Lane 1: "+rows[0][0] などを印刷しようとすると、正しく動作しているように見えますが、何らかの理由でこの IndexError を取得し続けます。 x-list 範囲のリスト。最悪の場合、リストが事前定義されているため (row_2 = [])、"Lane 2: " と出力されるはずですが、それも起こりません。助けてくれてありがとう!

4

1 に答える 1

2

問題は、あなたが言うように、row_2 = []. 空なので、インデックス 0 には要素がありません。

空白の "Lane x:" 行を取得するには、update を次のように書き換えます。

def update(self):
    for x in self.rows:
        for i in range(5):
            print("Lane {}: ".format(i), end='')
            if len(x):
                print(x[0])
            else:
                print()

ファイルの先頭に import を追加して、print ステートメントの代わりに print 関数を取得する必要もあります。

from __future__ import print_function
于 2012-12-08T04:17:02.920 に答える