TypeError:'str'对象不能解释为整数纸牌游戏

时间:2018-06-25 23:59:01

标签: python

当我使用python编写纸牌游戏时,出现此错误

Traceback (most recent call last):
   File "C:/Users/paulw/PycharmProjects/cardgame/war.py", line 53, in <module>
     playerA = deck1.pop(random.choice(deck1))
TypeError: 'str' object cannot be interpreted as an integer

请给我一些帮助。这是我的完整代码

total = {
  'winA':0,
  'winB':0
}


import random

def shuffleDeck():

deck = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']*4

random.shuffle(deck)        # Now shuffle the deck

return deck

def dealDecks(deck):
    global deck1
    global deck2
    deck1 = deck[:26]
    deck2 = deck[26:]

def total(hand):

    values = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '1':10,
          'J':11, 'Q':12, 'K':13,'A':14}


def war(playerA, playerB):
   if playerA==playerB:
      print("Tie")
   elif playerA > playerB:
      print("Winner:Player A")
      return 1
   else:
    print("Winner:player B")
    return -1

def process_game(playerA,playerB):
    result = game(p1c,p2c)
  if result == -1:
    total['winB'] += 1
  else:
    total['winA'] += 1

deck = shuffleDeck()

dealDecks(deck)

gameplay = input("Ready to play a round: ")

 while gameplay == 'y':
   playerA = deck1.pop(random.choice(deck1))
   playerB = deck2.pop(random.choice(deck2))
    print("Player A: {}. \nPlayer B: {}. \n".format(playerA,playerB))
 gameplay = input("Ready to play a round: ")


if total['winA'] > total['winB']:
    print("PlayerA won overall with a total of {} wins".format(total['winA']))
else:
    print("PlayerB won overall with a total of {} wins".format(total['winB']))

1 个答案:

答案 0 :(得分:0)

pop()取一个int的值,但是random.choice(deck1)返回一个deck1的元素,它是一个str。解决此问题的一种方法是通过选择deck1的随机索引来提取值:

deck1.pop(random.randint(0,len(deck1)-1))

其中random.randint(0,len(deck1)-1)返回随机索引deck1