2 回答
TA贡献1847条经验 获得超7个赞
如果你有Python 3.6+,你也可以尝试secrets
try:
import secrets as random
except ModuleNotFoundError:
import random
# Use system resources for randomization
rnd = random.SystemRandom()
# Set available card options
AVAILABLE_CARDS = [1,2,3,]
# Set number of cards per hand.
NUMBER_OF_CARDS = 3
# Create a simple key-value collection.
players = dict(
p_1_human_cards = None,
p_2_ai_cards = None,
p_3_ai_cards= None,
)
# Define a shuffler() function. Parameters are number of cards and available cards.
def shuffler(n_cards=NUMBER_OF_CARDS , available_cards = AVAILABLE_CARDS ):
return tuple([rnd.choice(available_cards) for _ in range(n_cards)])
# Iterate through players to set each hand
for hand in players:
players[hand] = shuffler()
# Print result
for player, hand in players.items():
print(f"{player}: {hand}")
输出:
p_1_human_cards: (2, 1, 3)
p_2_ai_cards: (3, 2, 1)
p_3_ai_cards: (2, 3, 3)
TA贡献2065条经验 获得超13个赞
看来您复制了以前的代码块,并且该return
部分保持不变。:) 尝试尽可能地编写 DRY 代码。你也可以这样做:
import random
def shuffle_p1():
p_1_human_cards=[random.randint(1,3) for _ in range(3)]
return p_1_human_cards
def shuffle_p2():
p_2_ai_cards=[random.randint(1,3) for _ in range(3)]
return p_2_ai_cards
def shuffle_p3():
p_3_ai_cards=[random.randint(1,3) for _ in range(3)]
return p_3_ai_cards
- 2 回答
- 0 关注
- 112 浏览
添加回答
举报