在python中的战争卡片游戏模拟

时间:2012-08-23 17:01:39

标签: python simulation game-engine

嗨,如果你是常客,你可能还记得这个节目。我已经解决了许多错误,但我被一个人困扰了。错误是:

File "/Users/administrator/Desktop/war.py", line 62, in <module>
    player1.extend(player1[range(warcardvalue1)])
TypeError: list indices must be integers, not list

代码是:

import random

cards = ['ace', 'ace', 'ace', 'ace', '1', '1', '1', '1', '2', '2', '2', '2', '3', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5', '6', '6', '6', '6', '7', '7', '7', '7', '8', '8', '8', '8', '9', '9', '9', '9', '10', '10', '10', '10', 'jack', 'jack', 'jack', 'jack', 'queen', 'queen', 'queen', 'queen', 'king', 'king', 'king', 'king']

order = ['ace', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king'] 
warcardvalue0 = 0
warcardvalue1 = 0
print "shuffling cards" 
random.shuffle(cards)
print "lets play"

player0 = cards[1::2]

player1 = cards[::2]

while (len(player0) > 0 or len(player1) > 0):

    nextcard0 = player0[0]
    nextcard1 = player1[0]

    cardplayed0 = order.index(nextcard0)

    cardplayed1 = order.index(nextcard1)

    if cardplayed0 > cardplayed1:

        player0.append(nextcard0)
        player0.append(nextcard1)
        player0.remove(nextcard0)
        player1.remove(nextcard1)

    elif cardplayed0 < cardplayed1:

        player1.append(nextcard1)
        player1.append(nextcard0)
        player1.remove(nextcard1)
        player0.remove(nextcard0)

    elif cardplayed0 == cardplayed1:
        while warcardvalue0 == warcardvalue1:
            if len(player0) >= 3:
                        warcard0 = player0[3]
                elif len(player0) < 3:
                    warcard0 = player0[len(player0)-1]

            if len(player1) >= 3:
                        warcard1 = player1[3]
                elif len(player1) < 3:
                    warcard1 = player1[len(player1)-1]


            warcardvalue0 = order.index(warcard0)
            warcardvalue1 = order.index(warcard1)

            if warcardvalue0 > warcardvalue1:
                player0.extend(player0[range(warcardvalue0)])
                player0.extend(player1[range(warcardvalue1)])
                player0.extend(player0[range(warcardvalue0)])
                player1.extend(player1[range(warcardvalue1)]) 

            elif warcardvalue0 < warcardvalue1:
                player1.extend(player1[range(warcardvalue1)])
                player1.extend(player0[range(warcardvalue0)])
                player1.extend(player1[range(warcardvalue1)])
                player0.extend(player0[range(warcardvalue0)]) 
            else:
                print "another war!" 


if len(player1) == 0:
    print "player1 won!"
elif len(player0) == 0:
    print "player0 won!"

我认为问题是你不能在列表中使用范围,但我不确定。

1 个答案:

答案 0 :(得分:1)

  

我认为问题是你不能在列表中使用范围,但我不确定。

问题是您无法使用列表索引列表。

请改为尝试:

player1.extend(player1[:warcardvalue1])

虽然看起来有点奇怪......