将字符串视为整数

时间:2015-06-07 21:44:04

标签: python string int

我正在尝试制作非常简单的二十一点游戏。当你得到两张牌时,如果它们都是整数或字符串,一切都没问题,但如果两张牌都是字符串和整数,我会收到错误。

我怎样才能这样做,如果你得到一个7和一个女王,女王将被视为10,总共17?

#imports
import random

Jack = 10
Queen = 10
King = 10
Ace = 1 or 11

Cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']
#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
Card1 = random.choice(Cards)
Card2 = random.choice(Cards)
Total = Card1 + Card2
print(Card1,'and a', Card2, '. Your total is', Total)






#print(int(Jack + Ace))

3 个答案:

答案 0 :(得分:2)

使用这样的卡片映射: -

import random

Jack = 10
Queen = 10
King = 10
Ace = 1 or 11

Cards_map = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 'Jack': 10, 'Queen': 11, 'King': 12, 'Ace': 13}
Cards=list(Cards_map)
#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
Card1 = random.choice(Cards)
Card2 = random.choice(Cards)
Total = Cards_map[Card1] + Cards_map[Card2]
print(Card1,'and a', Card2, '. Your total is', Total)

答案 1 :(得分:2)

使用dict映射卡来表示值:

Cards = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
         "10": 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 10}

#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
keys = list(Cards)
Card1 = random.choice(keys)
Card2 = random.choice(keys)
Total = Cards[Card1] + Cards[Card2]
print(Card1, 'and a', Card2, '. Your total is', Total)

或者使用.items:

Cards = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
         "10": 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 10}

#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
c = list(Cards.items())
Card1 = random.choice(c)
Card2 = random.choice(c)
Total = Card1[1] + Card2[1]
print(Card1[0], 'and a', Card2[0], '. Your total is', Total)

答案 2 :(得分:1)

使用字典:

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

print('Welcome to Blackjack!\n\nHere are your cards: \n ')
Card1 = random.choice(Cards.keys())
Card2 = random.choice(Cards.keys())
Total = Card1 + Card2
print(Cards[Card1],'and a', Cards[Card2], '. Your total is', Total)