0

Python 3 と PySide を使用して新しいゲームを作成しています。このゲームは、ゲーム パスワードのシンプルな UI であり、基本的にはリストからランダムな値を取得して表示し、値 (単語) が処理されたら、その単語をリストから削除して、2 回使用しないようにします。奇妙な問題は、GUI では一度に 4 つの単語しか選択できず、リストが空であることを示す ValueError をスローすることです。これは明らかに誤りであり、エラーが発生する前に 4 つの単語しか選択できないことがわかります。

#!/usr/bin/python

import sys
from PySide import QtCore, QtGui
from random import *

from game_gui import Ui_main_window
from game_list import cards




class game_window(QtGui.QWidget, Ui_main_window):
    def __init__(self, parent=None):
        super(game_window, self).__init__(parent)

        self.setupUi(self)

        global password_label
        password_label = self.password_label

        global get_button
        get_button = self.get_button
        get_button.clicked.connect(self.button_clicked)


    def label_clear(self):
        password_label.setText('Push Button To Get New Word')
        get_button.setText('Push Me To Get A Word')
        get_button.clicked.connect(self.button_clicked)

    def button_rename(self):
        get_button.setText('Push To Clear Word')
        get_button.clicked.connect(self.label_clear)


    def button_clicked(self):
        card_to_play = choice(cards)

        password_label.setText(card_to_play)
        cards.remove(card_to_play)
        self.button_rename()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = game_window()
    window.show()
    sys.exit(app.exec_())

エラーは次のとおりです。

Traceback (most recent call last):
  File "/usr/lib/python3.3/random.py", line 249, in choice
    i = self._randbelow(len(seq))
  File "/usr/lib/python3.3/random.py", line 225, in _randbelow
    r = getrandbits(k)          # 0 <= r < 2**k
ValueError: number of bits must be greater than zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "game_code.py", line 58, in button_clicked
    card_to_play = choice(cards)
  File "/usr/lib/python3.3/random.py", line 251, in choice
    raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence

そして、これらのエラーは両方とも最大 50 回表示されます。

どんな助けでも大歓迎です。

編集:リクエストに応じて、ここにリストがあります。

cards = [
    'scripture',
    'miracle',
    'garment',
    'prophecy',
    'tomb',
    'staff',
    'spirit',
    'garden of eden',
    'heaven',
    'sulpher',
    'nephelim',
    'knowledge',
    'armageddon',
    'plague',
    'commandment',
    'sovereignty',
    'resurrection',
    'wine',
    'cherub',
    'sandals',
    'wilderness',
    'gehena',
    'famine',
    'temple',
    'passover',
    'baptism',
    'leprosy',
    'ark',
    'drachma',
    'pharaoh',
    'levites',
    'scroll',
    'chaff',
    'boils',
    'Holy Spirit',
    'dragon',
    'lots',
    'Babylon',
    'tent',
    'parable',
    'scales',
    'Urim & Thummim',
    'scarlet',
    'transfiguration',
    'flame',
    'wild beast',
    'straw',
    'Red Sea',
    'pearl',
    'emerald',
    'swine',
    'demon',
    'Tartarus',
    'wine',
    'turtledove',
    'gnat',
    'camel',
    'garment',
    'shroud',
    'tomb',
    'Most Holy',
    'curtain,'
    'olive branch',
    'dust',
    'Cherub',
    'bull',
    'scorpion',
    'Nephilim',
    'privy',
    'sacrifice',
    'earthquake',
    'abyss',
    'fasting',
    'stake',
    'sling',
    'Samson',
    'Goliath',
    'betrayer',
    'slanderer',
    'murderer',
    'circumcision',
    'astrologer',
    'Hades',
    'chariot',
    'cistern',
    'balsalm',
    'undergarment',
    'bruise',
    'shipwreck',
    'fish',
    'intestines',
    'conscience',
    'curtain',
    'hypocrisy',
    'whitewash',
    'grave',
    'spear',
    'breastplate',
    'helmet',
    'leviathan',    
    ]
4

1 に答える 1

1

cardsこれが発生すると、明らかに空です。

len(seq)であり0、 を引き起こしますが、心配しなければならないValueErrorのはもう 1 つの例外です。IndexError

コードは、後でではなく、同じ関数ですぐに単語button_clicked()を削除するため、 が呼び出されるたびに からランダムな要素を削除しますcards

空のリストで例外を示すデモ:

>>> from random import choice
>>> choice([])
Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/random.py", line 249, in choice
    i = self._randbelow(len(seq))
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/random.py", line 225, in _randbelow
    r = getrandbits(k)          # 0 <= r < 2**k
ValueError: number of bits must be greater than zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/random.py", line 251, in choice
    raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence

デバッグ ステートメントを使用して、リストが思ったよりも早く空になる理由を見つける必要があります。

グローバルリストを操作しているため、そのリストから選択肢を削除しても、ゲームを終了しても復元されないことに注意してください。単語が削除されると、リストは空になるまで縮小し続けます。

おそらく、代わりに使用した単語を追跡したいと思うでしょう。使用したカードをセットで保管する:

class game_window(QtGui.QWidget, Ui_main_window):
    def __init__(self, parent=None):
        super(game_window, self).__init__(parent)

        self.used = set()

        # rest of your `__init__`

    # ...

    def button_clicked(self):
        while True:
            card_to_play = choice(cards)
            if card_to_play not in self.used:
                break
            if not set(cards).difference(self.used):
                raise ValueError('Not enough cards, used {}, can pick from {}'.format(len(self.used), len(set(cards))))

        password_label.setText(card_to_play)
        self.used.add(card_to_play)
        self.button_rename()

cardsは手付かずのままで、それぞれの新しいものには、埋めるgame_window新しい空のセットがあります。または、ゲームを再開したいときはいつでもusedリセットできますused(新しい、新鮮な空のセットに設定します)。self.used = set()

于 2013-05-20T23:49:45.880 に答える