我试图创建一个简单的Pontoon游戏(类似于二十一点),我已经制作了一张牌作为牌组。如果我给ACE一个值为1或14,那么我当前构建的游戏是有效的,但我需要它同时具有这两个值,所以如果一只手超过21,ACE将返回到1。
deck = [ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
所以基本上卡片选择就像这样:
while True:
hand = []
hand.extend(random.sample(deck, 1))
print(hand)
while True:
hit = input("new card? (k/e)")
if hit == "k":
hand.extend(random.sample(deck, 1))
print("")
print("HAND:")
print(hand)
a = sum(hand)
print("")
print("SUM:")
print(a)
if a > 21:
print("")
print("OVER")
break
elif a == 21:
print("")
print("Pontoon")
break
else:
continue
我试图将ACE作为一个函数,但random.sample并不适用
def ACE():
if a > 21:
A = 1
else:
A = 14
return int(A)
那么我如何让ACE作为1和14?
工作答案 0 :(得分:0)
您不会更改变量的值,而是调整求和函数:
import random
ACE = 14
deck = [ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
import copy
def sumHand(hand):
""" calculates the sum of cards in hand. if over 21 it will substitute
14 with 1 as ACE can be both. If no 14 in hand or below 21 will return value"""
k = hand.copy() # copy hand into k, so it will still show 14 but
# you can sum up as few ACE as needed to be 1 wehn
# calculating this sum
# maybe change 14th to 1 if neeed be
while sum(k) > 21 and ACE in k:
k.remove(ACE) # remove a 14
k.append(1) # replace by 1
return sum(k)
while True:
hand = [ACE,ACE] # start with 2 aces already for testing purposes
hand.extend(random.sample(deck, 1))
print(hand)
while True:
hit = input("new card? (k/e)")
if hit == "k":
hand.extend(random.sample(deck, 1))
print("")
print("HAND:")
print(hand)
a = sumHand(hand)
print("")
print("SUM:")
print(a)
if a > 21:
print("")
print("OVER")
break
elif a == 21:
print("")
print("Pontoon")
break
else:
continue
输出:
[14, 14, 8]
new card? (k/e)
HAND:
[14, 14, 8, 7]
SUM:
17
new card? (k/e)
HAND:
[14, 14, 8, 7, 5]
SUM:
22
OVER
答案 1 :(得分:-1)
您可以通过将ACE定义为类
来完成此操作class ACE():
value = 1
def set_value(self, value):
self.value = value
然后你可以像这样改变数组元素的值
ace = ACE() # in this step you have ace value = 1
array = [ace, 1, 2, 3, ...]
for a in array:
if type(a) == type(ACE):
# Your desired conditions
a.set_value(14)