我无法弄清楚如何在每次调用 random.choice 时生成新的随机值以及为什么不调用该函数

问题描述 投票:0回答:1
import random

# The card pool
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
# I created a list for the players cards bc that was the cleanest solution
players_cards = []
card_value = random.choice(cards)
sum = 0


def add(n1, n2):
    totals = n1 + n2
    return  totals

# I thought a function with a for loop in it to collect the players sum total of cards     was the cleanest solution
def player_total():
    for i in players_cards:
        sum += i


dictionary = {
    'total': player_total
}

should_continue = True
players_cards.append(card_value)
adding_players_total = dictionary['total']

# This is the while loop needed for the player to 'HIT' so to speak before passing the     computer
while should_continue == True:
    players_cards.append(card_value)
    print(f"Your cards are {players_cards}, current score: {adding_players_total}")
    print(f"The computer's first card is: {card_value}")
    players_choices = input("Type 'y' for another card, or 'n' to pass: ").lower()
    if players_choices == 'y':
        should_continue == True
    else:
        break

这仍然是一项正在进行的工作。我正在参加 Angela Yu 的 100 天代码训练营的第 11 天。我正在努力构建一款二十一点游戏。我估计已经完成了 35%。

我遇到的第一个问题是 PRNG,我只是不明白如何解决。根据我有限的理解,PRNG 基于系统时间,但如果需要多次调用 random.choice,例如在像本例这样的循环中,它将返回相同的值,事实也是如此。我不知道如何解决这个问题。我读过一些有关 random.seed 的内容,但这似乎与我想要的相反。它将确保 PRNG 每次生成相同的值。

第二个问题是这一行:{adding_players_total}"),在 while 循环中。我似乎无法调用这个函数。我想创建一个 For 循环来迭代列表或“卡片” ' 我认为这将是一个干净而优雅的解决方案来计算该游戏的扑克牌总价值,但我似乎不知道如何在程序中正确调用它。开始变得绝望并尝试诸如字典之类的东西。

python python-3.x
1个回答
0
投票

我认为在此之后您需要进行一些重构,以使游戏最终按照您想要的方式运行。

如果您在页面顶部随机调用一次,则会永久设置该值。如果你想要另一个随机数,你需要再次调用 random 。

不知道你带着字典要去哪里。 我调整了您的函数,然后将其添加到 f 字符串中,以便每次运行循环时都会调用(重新计算)。

import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
players_cards = []
computers_cards = []

def add(n1, n2):
    totals = n1 + n2
    return  totals

# I adjusted the function name for clarity
def caluclate_player_total(cards):
    total = 0
    for i in cards:
        total += i
    return total

should_continue = True
players_cards.append(random.choice(cards))
computers_cards.append(random.choice(cards))

while should_continue == True:
    players_cards.append(random.choice(cards))
    print(f"Your cards are {players_cards}, current score: {caluclate_player_total(players_cards)}")
    print(f"The computer's first card is: {computers_cards}")
    players_choices = input("Type 'y' for another card, or 'n' to pass: ").lower()
    if players_choices != 'y':
        break
© www.soinside.com 2019 - 2024. All rights reserved.