将字符串视为整数 [英] Treating a string as an integer

查看:132
本文介绍了将字符串视为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a very simple Blackjack game. When you get dealt two cards, everything's okay if they're both integers or strings, but I get an error if the two cards dealt are a string and an integer.

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

How can I make it so that if you get dealt a 7 and a Queen, the Queen will be treated as 10, giving you a total of 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))


推荐答案

使用dict映射卡值:

use a dict mapping cards to values:

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)

这篇关于将字符串视为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆