我想知道是否有人愿意帮助我解决这个问题。背景故事是创建一个纸牌游戏,当您随机抽出6张纸牌时,如果一张纸牌是一张ace,则玩家会赢得一美元,否则就会输掉一美元。这种情况一直持续到玩家要么将其资金翻倍,要么全部输光。该游戏运行了1000次,初始费用为10美元。这是我的代码:
import random
faceValues = ['ace', '2', '3', '4', '5', '6',
'7', '8', '9', '10', 'jack',
'queen', 'king']
suits = ['clubs', 'diamonds', 'hearts',
'spades']
def shuffledDeck():
deck = []
for faceValue in faceValues:
for suit in suits:
deck.append(faceValue + ' of ' + suit)
random.shuffle(deck)
return deck
def faceValueOf(card):
return card.split()[0]
def suitOf(card):
return card.split()[2]
d = shuffledDeck()
def game(initial):
counts = 0
bankroll = initial
while 0 < bankroll < 2*initial:
ace = 0
table = random.sample(shuffledDeck(),6)
counts += 1
for cards in table:
if faceValueOf (cards) == 'ace':
ace += 1
if ace >= 1:
bankroll += 1
else:
bankroll -= 1
return counts
initial = float(input('Enter initials: '))
totalcounts = 0
for x in range(1000):
totalcounts += game(initial)
print('Average number of rounds: ', totalcounts/1000)
我想知道如何更改此程序,因此可以使用random.shuffle而不是使用random.sample。我尝试了多种方法来更改此程序,但是无论何时,最终结果都是不一样的。我只是想更改我必须画卡的部分。当从头10开始运行此程序时,答案是按回合数计,大约为45至50。编辑:尝试使程序保持相对不变,只想更改我真正需要的内容。
我认为您可以采用更简单的方法来掌握游戏机制。用numpy
取1到52之间的6个随机整数。将ace定义为1-4。因此,如果已排序数组的第一个元素为<5,则您已绘制了一个ace。
import numpy as np
# simulates six cards
draw = np.sort(np.random.randint(1, 52, 6))
if draw[0] < 5:
print('drew an ace')
else:
print('did not draw an ace')
您可以在需要进行另一回合时在循环中重复绘制。
[如果需要保留卡名,则构建一次卡片组,并在每次迭代中从卡片组数组中采样六项。无需洗牌。