0

如何将我删除的卡片添加到我的手单中?抽牌移除了卡片,但我不知道如何将这些移除的卡片添加到手牌列表中。

import random

deck = ["sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ",
"sK", "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ",
"dQ", "dK", "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10",
"cJ", "cQ", "cK", "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9",
"h10", "hJ", "hQ", "hK"]

def draw():
  if len(deck) == 52:
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
 

hand=[]
hand.append()


print ("cards in deck : " + str(deck))
draw()
print ("Deck after removal of cards : " + str(deck))
print ("Cards in hand : " + str(hand))
4

3 回答 3

2

对于“转移这些卡”的概念,您会遇到很多麻烦。洗牌并从顶部取出 5 张牌:

random.shuffle(deck)
player_hand, remaining_deck = deck[:5], deck[5:]

那会处理你的案子吗?

于 2020-11-11T03:14:12.957 回答
0

您可以启动一个空列表并使用它的.append()方法

>>> l = ['a', 'b', 'c']
>>> l.append('d')
>>> l
['a', 'b', 'c', 'd']

对于这种情况,您可能还会发现 aset在您只有其中之一时很实用,因为它具有方便的成员资格方法

>>> s = set(('a', 'b', 'c'))
>>> s.remove('a')
>>> s
{'c', 'b'}
>>> s - set(('a', 'c'))
{'b'}

然而,正如@Prune 所指出的,洗牌然后切片可能会更干净!

于 2020-11-11T03:16:31.307 回答
0

由于牌组中的所有牌都是唯一的,因此您可以使用它的索引先将其转移到手上,然后再将其移除。

代码 :

import random

deck = ["sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ",
    "sK", "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ",
    "dQ", "dK", "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10",
    "cJ", "cQ", "cK", "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9",
    "h10", "hJ", "hQ", "hK"]

hand = [] # define hand here

def draw():
  if len(deck) == 52:
    for i in range(4): # using a for loop to avoid repetition of statements
      random_item_from_deck = random.choice(deck)
      hand.append(deck[deck.index(random_item_from_deck)])
      deck.remove(random_item_from_deck)
        
print ("cards in deck : " + str(deck))
draw()
print ("Deck after removal of cards : " + str(deck))
print ("Cards in hand : " + str(hand))
于 2020-11-12T02:34:24.647 回答