开发者

Python - Blackjack

def showCards():
    #SUM
    sum = playerCards[0] + playerCards[1]
    #Print cards
    print "Player's Hand: " + str(playerCards) + " : " + "sum"
    print "Dealer's Hand: " + str(compCards[0]) + " : " + "sum"


开发者_开发百科    compCards = [Deal(),Deal()]    
    playerCards = [Deal(),Deal()]

How can i add up the integer element of a list containing to values? under #SUM error is can combine lists like ints...


Aside from the comments mentioned above, sum is actually a built in function in Python that does just what you seem to be looking for - so don't overwrite it and use it as an identifier name! Instead use it.

Also there's a style guide that all Python programmers are meant to follow - it's what helps to further distinguish Python code from the inscrutable sludge often encountered in code written in other languages such as say Perl or PHP. There's a higher standard in Python and you're not meeting it. Style

So here's a rewrite of your code along with some guesses to fill in the missing parts.

from random import randint

CARD_FACES = {1: "Ace", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 
              9: "9", 10: "10", 11: "Jack", 12: "Queen", 13: "King"}

def deal():
    """Deal a card - returns a value indicating a card with the Ace
       represented by 1 and the Jack, Queen and King by 11, 12, 13
       respectively.
    """
    return randint(1, 13)

def _get_hand_value(cards):
    """Get the value of a hand based on the rules for Black Jack."""
    val = 0
    for card in cards:
        if 1 < card <= 10:
            val += card # 2 thru 10 are worth their face values
        elif card > 10:
            val += 10 # Jack, Queen and King are worth 10

    # Deal with the Ace if present.  Worth 11 if total remains 21 or lower
    # otherwise it's worth 1.
    if 1 in cards and val + 11 <= 21:
        return val + 11
    elif 1 in cards:
        return val + 1
    else:
        return val    

def show_hand(name, cards):
    """Print a message showing the contents and value of a hand."""
    faces = [CARD_FACES[card] for card in cards]
    val = _get_hand_value(cards)

    if val == 21:
        note = "BLACK JACK!"
    else:
        note = ""

    print "%s's hand: %s, %s : %s %s" % (name, faces[0], faces[1], val, note)


# Deal 2 cards to both the dealer and a player and show their hands
for name in ("Dealer", "Player"):
    cards = (deal(), deal())
    show_hand(name, cards)

Well ok so I got carried away and actually wrote the whole thing. As another poster wrote sum(list_of_values) is the way to go but actually is too simplistic for the Black Jack rules.


To find the value of a hand here you can just do something like

compSum = sum(compCards)

But it looks like you might have tried that from the second part of your post mentioning #SUM, I don't know what you were trying to say. This will only work if Deal() returns integers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜