将字符串显示为卡值

时间:2014-05-06 23:37:19

标签: python string list python-2.7

所以我正在建造一副纸牌。对于二十一点游戏,我有一个问题显示卡然后分配一个值(The Facecards / Ace,令人不安)任何人都可以给我一个提取值的手,但仍然显示选择为字符串的卡

suits = 'cdhs'
ranks = '23456789TJQK'
deck = tuple(''.join(card) for card in itertools.product(ranks,suits))
usrhand = random.sample(deck,2)
#print usrhand

fval = (str(usrhand[0]))[:1]
sval = (str(usrhand[1]))[:1]
#Need to check out TJQKA
#Error here, because val could be T
value = int(fval) + int(sval)

print("Your Hand: " + str(usrhand[0:1]))
print(value)

2 个答案:

答案 0 :(得分:2)

rank_from_str = dict(zip("23456789TJQKA",[2,3,4,5,6,7,8,9,10,10,10,10,11]))
print rank_from_str['A']

hand = "TTA"
hand_rank = sum(rank_from_str[card] for card in hand)
if hand_rank > 21: # if our hand is bigger than 21
   for i in range(hand.count("A")): #convert aces'
       hand_rank -= 10 #change 11 to 1 (subtract 10)
       if hand_rank <= 21: break #until we have less than 21
       #or until we run out of aces

print "HAND RANK:",hand_rank

答案 1 :(得分:0)

# assumes Python 3
import random

suits = {
    "C":0,
    "D":13,
    "H":26,
    "S":39
}
ranks = {
    "2":2,
    "3":3,
    "4":4,
    "5":5,
    "6":6,
    "7":7,
    "8":8,
    "9":9,
    "T":10,
    "J":11,
    "Q":12,
    "K":13,
    "A":14
}

deck = tuple(''.join(card) for card in itertools.product(ranks,suits))
hand = random.sample(deck, 2)

value = sum(ranks[card[0]] + suits[card[1]] for card in hand)

print("Your hand:", str(hand))
print("Value:", str(value))