Python21点游戏

2024-04-19 20:49:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为学校的一个项目制作一个关于Python的21点游戏。我已经把游戏的主要部分做了,但是我一直有语法错误。我试过调试它,但不知道出了什么问题。

这是我的密码-

def total(hand):
    aces = hand.count(11)
    t = sum(hand)
    if t > 21 and aces > 0:
        while aces > 0 and t > 21:
            t -= 10
            aces -= 1
    return t

cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
cwin = 0  
pwin = 0  

while True:
    player = []
    player.append(rc(cards))
    player.append(rc(cards))
    pbust = False  
    cbust = False  
    while True:
        tp = total(player)
        print "The player has these cards %s with a total value of %d" % (player, tp)
        if tp > 21:
            print "--> The player is busted!"
            pbust = True
            break
        elif tp == 21:
            print "\a BLACKJACK!!!"
            break
        else:
            hs = raw_input("Hit or Stand/Done (h or s): ").lower()
            if 'h' in hs:
                player.append(rc(cards))
            else:
                break
    while True:
        comp = []
        comp.append(rc(cards))
        comp.append(rc(cards))

        while True:
            tc = total(comp)                
            if tc < 18:
                comp.append(rc(cards))
            else:
                break
        print "the computer has %s for a total of %d" % (comp, tc)

        if tc > 21:
            print "--> The computer is busted!"
            cbust = True
            if pbust == False:
                print "The player wins!"
                pwin += 1
        elif tc > tp:
            print "The computer wins!"
            cwin += 1
        elif tc == tp:
            print "It's a draw!"
        elif tp > tc:
            if pbust == False:
                print "The player wins!"
                pwin += 1
            elif cbust == False:
                print "The computer wins!"
                cwin += 1
        break
    print
    print "Wins, player = %d  computer = %d" % (pwin, cwin)
    exit = raw_input("Press Enter (q to quit): ").lower()
    if 'q' in exit:
        break
print "Thanks for playing blackjack with the computer!"

我运行3.3.2,我已经稍微编辑了一下,现在得到这个。


Tags: thetrueifcomputertotaltccardsrc