Python如何“重新随机化”变量?

2024-04-18 01:32:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我在玩21点游戏,我想知道如何让随机变量一次又一次地出现。另外,如何在去掉列表中的变量后将其重置为原始形式。你知道吗

下面是我在小范围内得到的:

card1 = random.randint(0, 3)
deck_of_cards = [A_hearts, 2_diamonds, Queen_hearts, 5_spades]
value = [11, 2, 10, 5]
def dealcards():
     print deck_of_cards[card1]
     print value[card1]
     print 'This is your first card and it's value.'

这是非常小的规模,考虑到我在真正的游戏中使用了一整副牌。 我要问的是,我怎么才能让它一次叫红心王牌,下一次叫钻石王牌。你知道吗

如果您也知道,在使用del或list.pop?你知道吗

谢谢您的帮助。你知道吗


Tags: of游戏列表valuerandom形式重置cards
2条回答

用21点来正确回答这个问题需要比下面的代码更复杂的东西,因为你通常会有多副牌在玩。您可能还需要一个生成器来yield这些卡,而不是使用整个预先确定的牌组。你知道吗

然而,它演示了如何随机抽取一副牌,并一张一张地将其用尽,同时使用字典来保存牌的值。要创建一个新的组,只需再次调用create_fresh_deck()。你知道吗

import random
import time

def create_fresh_deck():
    suits = [' of Hearts', ' of Diamonds', ' of Spades', ' of Clubs']

    # Below uses "list concatenation"
    cards = ['Ace'] + list(map(str, range(2, 11))) + ['Jack', 'Queen', 'King']
    values = list(range(1, 11)) + [10, 10, 10]

    # Dictionary comprehension to knit them together
    deck = {cards[x] + suits[y]: values[x] 
            for y, _ in enumerate(suits) for x, _ in enumerate(cards)}

    return deck

deck = create_fresh_deck()
deck_cards = list(deck.keys())
random.shuffle(deck_cards) # randomise your deck in place

for card in deck_cards:
    if 'ace' not in card.lower():
        print("The card is {} with value {}".format(card, deck[card]))
    else:
        print("The card is {} with value 1 or 11".format(card))
    time.sleep(0.5) # Just to slow down the print outputs a bit

你可以试试这个。。。你知道吗

“重新随机化”变量的唯一方法是使用随机.randint()再次。你知道吗

我不知道你是否可以“重置”一个列表,但是通过将列表作为参数给一个函数,你可以让你的原始列表不受伤害。你知道吗

希望这对你有帮助。你知道吗

import random

deck_of_cards_original = ["A_hearts", "2_diamonds", "Queen_hearts", "5_spades"]
value_original = [11, 2, 10, 5]


playerCardsNames = []
playerCardsValues = []

def dealcards(deck_of_cards, value): #give lists as parameters so you can keep the original card list

   card1 = random.randint(0, 3)    #all cards still avaiable so randint(0, 3)
   print(deck_of_cards[card1])
   print(value[card1])
   print('''This is your first card and it's value.''')
   playerCardsNames.append(value[card1])   #saves the card names and values of the players in a new list
   playerCardsValues.append(value[card1])  #
   del deck_of_cards[card1]    #the card is out of the deck now so delete it
   del value[card1]

   print("")

   card2 = random.randint(0, 2)    #randint with one card less because the player has it now
   print(deck_of_cards[card2])
   print(value[card2])
   print('''This is your second card and it's value.''')
   playerCardsNames.append(value[card2])   #same thing as before
   playerCardsValues.append(value[card2])
   del deck_of_cards[card2]
   del value[card2]


dealcards(deck_of_cards_original, value_original)

相关问题 更多 >

    热门问题