我正在制作一個紙牌游戲,pygame并且我將使用的卡片存盤在一個串列中,該串列從回圈訪問檔案存盤的 for 回圈接收元素。我想防止同一張卡片被抽取兩次,所以我想如果卡片已經被抽取,請將其作為選項從串列中洗掉以防止它。但是 list removes 方法給了我一個錯誤,說該元素不在 中cards_list,但它確實在。
cards_list = []
cards_tpye_1 = ['D', 'H', 'C', 'S']
cards_tpye_2 = ['Q', 'K', 'A', 'J']
for card in cards_tpye_1:
for x in range(2, 11):
img = pygame.image.load(f'img\cards\{card}{x}.png')
img = pygame.transform.scale(img, (img.get_width() * 2, img.get_height() * 2))
cards_list.append(img)
for card in cards_tpye_2:
for suit in cards_tpye_1:
img = pygame.image.load(f'img\cards\{card}{suit}.png')
img = pygame.transform.scale(img, (img.get_width() * 2, img.get_height() * 2))
cards_list.append(img)
dealer_card_1 = random.choice(cards_list)
card_1 = random.choice(cards_list)
card_2 = random.choice(cards_list)
cards_dealt = False
dealer_cards_list = []
player_cards_list = []
if cards_dealt is True:
screen.blit(dealer_card_1, (width//3, 50))
dealer_cards_list.append(dealer_card_1)
screen.blit(card_1, (width//3, height//2))
screen.blit(card_2, (width//3 140, height//2))
player_cards_list.append(card_1)
player_cards_list.append(card_2)
cards_list.remove(card_1)
cards_list.remove(card_2)
cards_list.remove(dealer_card_1)
ValueError: list.remove(x): x 不在串列中
我嘗試創建已發牌的新串列,但是當我嘗試移除牌時,它給出了相同的錯誤。
uj5u.com熱心網友回復:
random.choice不知道以前選擇的專案,因此您的代碼可能多次選擇同一張卡片。當您要移除卡片時,重復選擇的第二次移除將失敗。
通過使用 sample for 3 而不是呼叫 choice 3 次,您可以在一次操作中獲得 3 張不同的卡片:
dealer_card_1, card_1, card_2 = random.sample(cards_list,3)
這將確保 3 張卡不同,并且您的其余代碼可以保持原樣。
另一種選擇可能是撰寫一個函式來抽取一張牌并立即將其從牌組中移除。您可以在任何地方呼叫此函式(而不是 random.choice),而無需將洗掉散布到所有地方:
def drawCard(deck):
card = random.choice(deck)
deck.remove(card)
return card
...
dealer_card_1 = drawCard(cards_list)
card_1 = drawCard(cards_list)
card_2 = drawCard(cards_list)
...
# no need for the cards_list.remove() later on ...
uj5u.com熱心網友回復:
為防止同一張牌被抽兩次,您可以在抽完牌后立即將其從串列中洗掉。
dealer_card_1 = random.choice(cards_list)
cards_list.remove(dealer_card_1)
card_1 = random.choice(cards_list)
cards_list.remove(card_1)
card_2 = random.choice(cards_list)
cards_list.remove(card_2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/396512.html
上一篇:在串列中查找最舊并回傳最舊的串列
下一篇:生成器物件阻止串列理解
