【问题标题】:Can't remove card from Euchre hand in Python无法在 Python 中从 Euchre 手中移除卡片
【发布时间】:2014-03-11 22:12:55
【问题描述】:

我正在尝试用 Python 编写纸牌游戏 Euchre,但遇到了一些错误。我将在下面发布我的代码,然后解释我当前的问题:

import random

class Card(object):
    '''defines card class'''
    RANK=['9','10','J','Q','K','A']      #list of ranks & suits to make cards
    SUIT=['c','s','d','h']

    def __init__(self,rank,suit):
        self.rank=rank
        self.suit=suit

    def __str__(self):
        rep=self.rank+self.suit
        return rep
    #Next four definitions haven't been used yet. Goal was to use these
    #to define a numerical vaule to each card to determine which one wins the trick        
    def getSuit(self):
        return self.suit

    def value(self):
        v=Card.RANK.index(self.rank)
        return v

    def getValue(self):
        print(self.value)

    def changeValue(self,newValue):
        self.value=newValue
        return self.value

class Hand(object):
    def __init__(self):
        self.cards=[]

    def __str__(self):
        if self.cards:
            rep=''
            for card in self.cards:
                rep+=str(card)+'\t'
        else:
            rep="EMPTY"
        return rep

    def clear(self):
        self.cards=[]

    def add(self,card):
        self.cards.append(card)

    def give(self,card,other_hand):
        self.cards.remove(card)
        other_hand.add(card)

    def remove(self,card):
        self.cards.remove(card)

class Deck(Hand):
    def populate(self):
        for suit in Card.SUIT:
            for rank in Card.RANK:
                self.add(Card(rank,suit))

    def shuffle(self):
        random.shuffle(self.cards)

    def reshuffle(self):
        self.clear()
        self.populate()
        self.shuffle()

    def deal(self,hands,hand_size=1):
        for rounds in range(hand_size):
            for hand in hands:
                if self.cards:
                    top_card=self.cards[0]
                    self.give(top_card,hand)
                else:
                    print("Out of cards.")

#These two are the total scores of each team, they haven't been used yet
player_score=0
opponent_score=0

#These keep track of the number of tricks each team has won in a round
player_tricks=0
opponent_tricks=0

deck1=Deck()

#defines the hands of each player to have cards dealt to
player_hand=Hand()
partner_hand=Hand()
opp1_hand=Hand()
opp2_hand=Hand()
trump_card=Hand()      #This is displayed as the current trump that players bid on

played_cards=Hand()    #Not used yet. Was trying to have played cards removed from
                  #their current hand and placed into this one in an attempt to
                  #prevent  playing the same card more than once. Haven't had
                  #success with this yet
hands=[player_hand,opp1_hand,partner_hand,opp2_hand]

deck1.populate()
deck1.shuffle()
print("\nPrinting the deck: ")
print(deck1)
deck1.deal(hands,hand_size=5)
deck1.give(deck1.cards[0],trump_card)

def redeal():      #just to make redealing cards easier after each round
    player_hand.clear()
    partner_hand.clear()
    opp1_hand.clear()
    opp2_hand.clear()
    trump_card.clear()
    deck1.reshuffle()
    deck1.deal(hands,hand_size=5)
    deck1.give(deck1.cards[0],trump_card)

print("\nPrinting the current trump card: ")
print(trump_card)

while player_tricks+opponent_tricks<5:
#Converts players hand into a list that can have its elements removed
Player_hand=[str(player_hand.cards[0]),str(player_hand.cards[1]),str(player_hand.cards[2]),\
str(player_hand.cards[3]),str(player_hand.cards[4])]


print("\nYour hand: ")
print(Player_hand)

played_card=str(raw_input("What card will you play?: "))#converts input into a string
if played_card==Player_hand[0]:         #crudely trying to remove the selected card
    Player_hand.remove(Player_hand[0])  #from player's hand
if played_card==Player_hand[1]:
    Player_hand.remove(Player_hand[1])
if played_card==Player_hand[2]:
    Player_hand.remove(Player_hand[2])
if played_card==Player_hand[3]:
    Player_hand.remove(Player_hand[3])
if played_card==Player_hand[4]:         #received the 'list index out of range' error
    Player_hand.remove(Player_hand[4])  #here. Don't know why this is an error since
                                        #Player_hand has 5 elements in it.

opp1_card=opp1_hand.cards[0]  #just having a card chosen to see if the game works
                              #will fix later so that they select the best card
                              #to play


partner_card=partner_hand.cards[0]


opp2_card=opp2_hand.cards[0]


print("First opponent plays: ")
print(opp1_card)
print("Your partner plays: ")
print(partner_card)
print("Second opponent plays: ")
print(opp2_card)

trick_won=[0,1]   #Just used to randomly decide who wins trick to make sure score is
                  #kept correctly
Trick_won=random.choice(trick_won)
if Trick_won==0:
    print("\nYou win the trick!")
    player_tricks+=1
if Trick_won==1:
    print("\nOpponent wins the trick!")
    opponent_tricks+=1
if player_tricks>opponent_tricks:
print("\nYou win the round!")
if opponent_tricks>player_tricks:
print("\nOpponont wins the round!")

print("\nGOOD GAME") #Just to check that game breaks loop once someone wins the round

到目前为止,我能够完成的是创建了一个套牌,四个玩家中的每一个都得到了一张五张牌,然后让玩家问他们想玩什么牌。一旦他们打出一张牌,其他三个玩家(两个对手和一个伙伴)打出他们的牌,然后我随机决定谁赢得了“把戏”,只是为了看看分数是否保持正确。

我目前正在尝试解决的问题是,一旦玩家打出一张牌并打出戏法,在下一个戏法中,当牌显示出来时,他们手中应该少一张牌,但我无法做到移除之前打出的牌,这样玩家手上仍有五张牌。

你们有谁知道我做错了什么以及如何删除选定的卡?感谢您的帮助。

【问题讨论】:

  • 与其发布整个游戏的代码然后询问如何实现下一个功能,而是尝试将问题归结为如何您已尝试实现所述功能,以便我们对其进行调试。现在 IMO 太大了。
  • 很抱歉,我担心我不会包含足够的代码来提供帮助,但看起来我无意中走到了另一个极端。我的问题在于以“raw_input”开头的代码块。我当前删除所选卡的尝试列在我的代码中。我尝试的另一种方法是在 raw_input 提示后立即输入“Player_hand.remove(played_card)”,不包括我目前拥有的任何 if 条件。我的想法是,既然我现在已经定义了 play_card,我可以将它与 Player_hand 中的正确部分匹配并删除它,但这也不起作用。

标签: python list playing-cards


【解决方案1】:

您得到的IndexError 是因为您使用了多个ifs 而不是elif

if played_card==Player_hand[0]:
    Player_hand.remove(Player_hand[0])
# The next if is still evaluated, with the shortened Player_hand
if played_card==Player_hand[1]:
    Player_hand.remove(Player_hand[1])

使用:

if played_card==Player_hand[0]:
    Player_hand.remove(Player_hand[0])
elif played_card==Player_hand[1]:
    Player_hand.remove(Player_hand[1])

但是,是的,使用您创建的那些类,并使用__eq__ 进行比较。

【讨论】:

  • 另外,有时间结帐PEP8,值得一读。
  • 如果我按照您的建议将接下来的四个“ifs”更改为“elifs”,我的代码仍然不会删除所选卡。如果在 raw_input 提示之前我有 Player_hand.remove(Player_hand[0]) 或其他任何索引,我可以毫无问题地移除该卡。出于某种原因,如果我尝试移除玩家输入的特定卡片,程序将无法识别要移除的任何内容,并且他们仍然会说我手里有五张卡片。
  • 嗯,是吗?如果您删除永远不会满足的while 条件,这就是您的程序遇到的错误。您可以通过在删除后打印Player_hand 列表来验证这一点。
  • 抱歉我的困惑。我正在从手上取出卡片,但是当循环再次开始时,我打印的是原来的五张手牌,而不是带有已移除卡片的更新手牌。感谢您的帮助。
猜你喜欢
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多