Python卡牌游戏:如何将Deck类弹出的卡牌对象添加至Player类手牌
Hey there! Let's get your player's hand working properly. The core issue here is that your take() method doesn't accept the card you're drawing from the deck, and your deck's draw() method doesn't return the popped card so you can pass it along. Here's how to fix it step by step:
Step 1: Update the Deck's draw() Method
Right now, your draw() method just removes the last card from the deck but doesn't give it back to us. We need it to return the popped card so we can send it to the player:
def draw(self): return self.cards.pop()
Step 2: Modify the Player's take() Method
Your current take() method doesn't take any arguments, so there's no way to pass the drawn card into it. Let's update it to accept a card parameter and add it to the player's hand:
def take(self, card): self.hand.append(card)
Step 3: Correct the Function Calls
When you want a player to take a card, you need to call draw() on the deck and pass that result directly to the player's take() method:
z.take(y.draw())
Full Corrected Code
Here's the complete working version of your code with all the fixes applied:
import random ranks = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"] suits = ["Spades", "Clubs", "Hearts", "Diamonds"] class Card: def __init__(self, rank, suit): self.rank = rank self.suit = suit def print(self): print(self.rank, "of", self.suit) class Deck: def __init__(self): self.cards = [] def build(self): for x in ranks: for y in suits: self.cards.append(Card(x,y)) def shuffle(self): random.shuffle(self.cards) def print(self): for x in self.cards: x.print() def draw(self): # Return the popped card so we can pass it to the player return self.cards.pop() y = Deck() y.build() y.shuffle() class Player: def __init__(self): self.hand = [] def take(self, card): # Accept a card parameter and add it to the hand self.hand.append(card) def print(self): for x in self.hand: x.print() z = Player() # Pass the drawn card from the deck to the player's take method z.take(y.draw()) z.print()
Now when you run this, the player will successfully take a card from the shuffled deck and print out their hand!
内容的提问来源于stack exchange,提问作者rc4868

