python - 列表中的可变变量
问题描述
我正在尝试创建一个简单的 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 工作呢?
解决方案
您不更改变量的值,而是调整求和函数:
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
推荐阅读
- android - 未调用 Android onNewIntent
- databricks - 将数据写入 Azure 数据块中的 Delta Lake 时出现问题(检测到不兼容的格式)
- angularjs - 表单 $dirty 在 typeahead 选择时为假
- typescript - 是否可以将 Lerna 用于在 api 边界上使用 rxjs(例如)的多个打字稿项目?
- python - 使用 TensorFlow 的对象检测 API
- javascript - 如何构建对 API 的异步调用?
- printing - 如何在python3中创建打印对话框
- swift - tableView 内的 collectionView 在滚动时返回到第一个索引
- javascript - 将构造函数中的默认值设置为未定义是一种好习惯吗?
- python - 如何通过标记现有数据框的内容来创建新的数据框?