我目前正在作为一个类项目在python中开发一个内存游戏。我正在尝试生成0到3之间的随机数,这将对应于某张卡。问题是,我只需要每张卡片出现两次。不多也不少。
这是我当前的代码:
import random
cards = ["___TI___", "___GK___", "___QW___", "___KJ___"]
boardTemp1 = ['1', '2',
'3', '4',
'5', '6',
'7', '8']
def shuffle():
cardChoose = random.randint(0, 3)
boardChoose = random.randint(0, 7)
randCard = 9
randCard = cards[cardChoose]
boardTemp1[boardChoose] = cards[cardChoose]
return randCard
boardTemp1[0] = shuffle()
boardTemp1[1] = shuffle()
boardTemp1[2] = shuffle()
boardTemp1[3] = shuffle()
boardTemp1[4] = shuffle()
boardTemp1[5] = shuffle()
boardTemp1[6] = shuffle()
boardTemp1[7] = shuffle()
print(boardTemp1)
谢谢你的帮助
最佳答案
当你有一组特定的项目在你周围游荡时,做独立的随机选择不是一个好方法。请改为:
import random
cards = ["___TI___", "___GK___", "___QW___", "___KJ___"]
boardTemp1 = cards * 2
random.shuffle(boardTemp1)
print(boardTemp1)
关于python - 如何限制生成特定随机数的次数python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43786104/