随机将列表项添加到另一个列表中

时间:2015-10-20 11:04:59

标签: python

我正在为大学作业制作二十一点,我需要从牌组中附加2张随机牌到玩家名单(他的手)。

到目前为止,这是我的代码。

import random
import time

Ace=1
Jack=10
Queen=10
King=10

deck=[2,3,4,5,6,7,8,9,10,"Ace","Jack","Queen","King"]
player=[]
dealer=[]



def welcome():
    start=input("Hi there - Fancy a game of Blackjack? yes or no ")
    if start == "yes":
        print ("The game will begin now...")
        time.sleep(2)
        startgame()

def startgame():
    print ("Dealing...")
    time.sleep(1)
    for i in range (2):
        player = random.randint(1,13)
        print (player)





welcome()
startgame()

谢谢

肖恩

2 个答案:

答案 0 :(得分:1)

您应该可以执行类似

的操作
hand=[]
for i in range(2):
  card=random.choice(deck)
  hand.append(card)
  deck.pop(card)

这将为您提供2张牌,并确保您无法复制牌。重新创建套牌是很重要的,因为它在每场比赛开始时都会再次拥有52张牌,或者调整逻辑以使其更像是:

hand=[]
for i in range(2):
  card=random.choice(deck)
  if card in hand: #Note you will need to check every hand here
    continue
  else:
    hand.append(card)

答案 1 :(得分:1)

你在真正的纸牌游戏中做了什么?您不会选择随机数,看看哪个卡与该号码对应,以及是否已经使用了该号码。你只需shuffle牌组,然后pop牌从牌组进入玩家'手。

>>> cards = list(range(52)) # your actual cards    
>>> random.shuffle(cards)
>>> hand = [cards.pop() for _ in range(5)] # pop first 5 card from shuffled deck
>>> hand
[29, 34, 25, 3, 46]

这与现实生活最接近,也保证不会两次拍摄卡片。您可以使用相同的方法处理更多卡片:只需从仍然洗牌的牌组再次拨打pop,然后将卡片添加到相应的牌中。