为什么我的python函数sum_points总是返回相同的结果?

时间:2020-05-11 18:09:50

标签: python python-3.x

为什么我的程序总是输出相同的结果? (5)。 通过功能sum_points,我试图对分数求和,以检查玩家的分数是否大于21,以检查他是否仍然安全或输了。

我不知道为什么,但是我总是得到5作为函数sum_points的输出,即使它应该将faces数组的索引处的值求和,所以2个被选牌值的总和< / p>

import random

card_values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
suits = ["spades", "clubs", "hearts", "diamonds"]
       # 2  3  4  5  6  7  8  9  10  J   Q   K   A
faces = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
faces_display = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]


class Card:
    def __init__(self, face, suit):
        self.face = face
        self.suit = suit

def create_deck():
    cards = []
    for x in range(2):
        for suit in suits:
            for face in faces_display:
                c = Card(face, suit)
                cards.append(c)

    random.shuffle(cards)
    return cards

def display_cards(cards_list):
    for card in cards_list:
        print(card.face +"\t"+ card.suit)

def sum_points(cards):
    tot = 0
    for card in cards:
        tot += faces[cards.index(card)]

    return tot


def play_hand():
    cards = create_deck()

    dealer_cards = []
    player_cards = []

    # deal initial cards
    dealer_cards.append(cards.pop(0))
    dealer_cards.append(cards.pop(0))
    player_cards.append(cards.pop(0))
    player_cards.append(cards.pop(0))

    dealer_score = sum_points(dealer_cards)
    player_score = sum_points(player_cards)

if __name__ == "__main__":
    cards = create_deck() 
    c = []
    c.append(cards.pop(0))
    c.append(cards.pop(0))

    display_cards(c)
    print(sum_points(c))

5 个答案:

答案 0 :(得分:1)

是的,就像其他人所说的那样,//loop through this if you want data of all objects in the 2nd item i.e data[1][0...n] var objectData = data[1][0] var personID = objectData.personID var img = objectData.img var img_path = objectData.img_path 仅返回您传递给tot += faces[cards.index(card)]函数的卡列表的索引。

有了您的代码,我想您想要的就是这样

sum_points

更好的是,我认为拥有包含面部显示和诸如tot += faces[faces_display.index(card.face)] 之类的面部值的字典会更容易,因此您可以使用

face_dict = {"J" : 10, "Q" : 10}

我认为哪个更具可读性。

答案 1 :(得分:0)

您总是在抓卡2和3。您并没有在create_deck()函数中随机选择卡。

答案 2 :(得分:0)

问题是您实际上是从仅包含这两张牌的列表中获得这些牌的。

当您致电false时,sum_points。在c = [cards[0], cards[1]内部,您正在请求作为参数收到的同一列表中的元素的索引;因此,索引将为sum_points0

一个例子是:

1

希望有帮助!

答案 3 :(得分:0)

您的>>> data = ["Third-Degree Assault", "Assault", "Foobar"] >>> [1 if x == "Battery" or x == "Assault" else 0 for x in data] [0, 1, 0] >>> [1 if "Battery" in x or "Assault" in x else 0 for x in data] [1, 1, 0] 函数不是随机的,它总是在create_deck()中生成数字0, 1,因此选择2和3,因为它们是索引range(2)和{{ 1}}个卡片清单。

此后确实会洗牌,但是当您将它们添加到一起时,这不会改变任何内容。

答案 4 :(得分:0)

        tot += faces[cards.index(card)]

这里您要遍历一个数组,然后访问cards.index(card),它是数组中卡的索引,在您的情况下,因为有两张卡,所以第一张卡始终为0,第二。因此,您将始终访问faces [0]和faces [1]并对它们求和,从而得到2 + 3 =5。