随机纸牌游戏

时间:2013-04-03 04:39:36

标签: python random

我目前正在做一个随机卡片游戏项目,该程序应该向用户显示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

3 个答案:

答案 0 :(得分: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])

答案 1 :(得分: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']

答案 2 :(得分:0)

您可以使用random.randrange(number),然后在该位置拉出索引。