0

我目前正在做一个随机纸牌游戏项目,程序应该向用户显示 5 张随机纸牌,(第一个问题):我不知道如何随机排列字母列表,这是我的代码:

def play():
    hand = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"]

    for i in range(len(hand)):
        card = random.choice[{hand},4]   

    print "User >>>> ",card
    return card

第二个问题:如果用户想改变卡片的位置。用户应输入编号。的位置变化,那么程序应该随机改变卡。例如:AJ891,用户输入:1,--> A2891。我应该怎么办?这是我的原始代码,但它不起作用

def ask_pos():
    pos_change = raw_input("From which position (and on) would you want to change? (0 to 4)? ")
    while not (pos_change.isdigit()):
        print "Your input must be an integer number"
        pos_change = raw_input("From which position (and on) would you want to change? (0 to 4)? ")
        if (pos_change > 4) :
            print "Sorry the value has to be between 0 and 4, please re-type"
            pos_change = raw_input("From which position (and on) would you want to change? (0 to 4)? ")
    return pos_change

    hand = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"]

    for i in range(len(hand)):
        card = random.choice[{hand},4]
        new = random.choice[{hand},1]

            for i in range(len(card)):
                if (card[i] == pos_change):
                    card = card + new

    return card
4

3 回答 3

2

1)

random.choice[{hand},4]

那行不通,语法错误。选择也不会奏效,样品就是你想要的:

random.sample(hand, 5)

2)

pick = random.sample(hand, 5)

change = 2  # Entered by the user

pick[change] = random.choice([x for x in hand if x not in pick])
于 2013-04-03T05:16:08.370 回答
1

要回答您的第一个问题:

import random
hands = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"]
def play():
    cards = random.sample(hands,5)
    print "User >>>> ", cards
    return cards

random.choice[{hand},4]应该会导致语法错误。首先,调用函数时使用括号()而不是方括号[]。另外,我不明白你为什么需要{}在手边放大括号,因为它已经是一个列表,所以不需要做任何事情。

我重写了你的第二个问题:

def ask_pos(hand):
    while 1:
        pos_change = raw_input("From which position (and on) would you want to change? (0 to 4)? ")
        if int(pos_change) < 0 or int(pos_change) > 4:
            continue
        else:
            break
    hand[int(pos_change)] = random.choice(hands)
    return hand

运行时:

>>> myhand = play()
User >>>>  ['6', '8', 'A', '9', '4']

>>> ask_pos(myhand)
From which position (and on) would you want to change? (0 to 4)? 0
['Q', '8', 'A', '9', '4']
于 2013-04-03T05:24:42.480 回答
0

You could use random.randrange(number), and then pull out the index at that position.

于 2013-04-03T04:49:30.750 回答