无法在Python中从Euchre手牌中移除卡牌

0 投票
1 回答
668 浏览
提问于 2025-04-17 21:51

我正在用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

到目前为止,我已经能做到的是创建一副牌,并给四个玩家发五张牌。然后询问玩家想打出哪张牌。一旦他们打出一张牌,其他三个玩家(两个对手和一个搭档)也会打出他们的牌。接着,我随机决定谁赢得这一轮,以检查分数是否正确。

我现在面临的问题是,当一个玩家打出一张牌后,下一轮开始时,他们的手牌应该少一张,但我无法把之前打出的那张牌移除,所以玩家的手里仍然有五张牌。

你们知道我哪里出错了吗?我该如何把选中的牌移除呢?谢谢大家的帮助。

1 个回答

1

你遇到的 IndexError 错误是因为你用了多个 if 语句,而不是用 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__ 来进行比较。

撰写回答