Sorry I'm new to python, sorry, if the question is too basic. I am trying to write a code for a card game called pishti or bastra. Shortly, two players (in my case a user and a computer) have hands consisting of 4 cards each and there are some cards in the middle one of which is on top and visible to the players (others are closed). Shortly I was able to deal cards for the user with a list of four card objects. However, after the user plays one of his/her cards, I can't remove the card from the list as it cannot be found. (I tried to use .remove() and del) However, I can access the cards with list[index] Here's my code (shortened to the parts related to this question):
import random
class Card:
def __init__(self,value,suit):
self.value = value
self.suit = suit
def __repr__(self):
return f"{self.suit} {self.value}"
def execute(self):
return None
class Deck:
def __init__(self):
suits = ["Hearts","Spades","Clubs","Diamonds"]
values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
self.cards = [Card(value,suit) for value in values for suit in suits]
def __repr__(self):
return f"Deck of {self.count()}"
def count(self):
return len(self.cards)
def shuffle(self):
if self.count() < 52:
raise ValueError ("Sorry only complete decks can be shuffled.")
random.shuffle(self.cards)
return self
def _deal(self,num_of_cards_to_be_dealt):
if self.count() == 0:
raise ValueError ("Sorry, all of the cards have been dealt.")
actual = min(self.count(),num_of_cards_to_be_dealt)
dealt_cards = self.cards[-actual:]
self.cards = self.cards[:-actual]
return dealt_cards
def deal_hand(self,hand_size = 4):
return self._deal(hand_size)
deste = Deck()
kar_deste = deste.shuffle()
orta = (kar_deste.deal_hand())
print(f"The card in the middle: {orta[-1]}")
user_score = 0
comp_score = 0
while kar_deste.count() != 0:
computer_hand = kar_deste.deal_hand()
user = kar_deste.deal_hand()
print(f"Your cards: {user}")
while len(user) != 0:
card_suit = input("Choose a suit: ")
card_val = input("Choose a value: ")
print(str(Card(card_val,card_suit)))
user_turn = Card(card_val,card_suit)
card_index = user.index(user_turn)
del user[card_index]
print(user)
When I run this code I encounter a value error(in the line with user.index()), stating the card is not in the list. However I can access to it by manually using it's index. Thus I don't know why this doesn't work. Do you have any idea, what might be the reason behind this? Thanks in advance.