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條經驗 獲得超14個贊
看來您復制了以前的代碼塊,并且該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 關注
- 192 瀏覽
添加回答
舉報