首页 > 解决方案 > 列表中的可变变量

问题描述

我正在尝试创建一个简单的 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 工作呢?

标签: pythonpython-3.xblackjack

解决方案


您不更改变量的值,而是调整求和函数:

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

推荐阅读