纸牌游戏"Go Fish"功能,用于检查玩家的手牌是否有对手猜出的牌



我正试图弄清楚如何设置一个功能来检查和看看他们的对手是否有他们想要的牌。

我试图设置函数返回True,如果他们的函数找到一对并删除它,返回False,如果它不删除一对。

这样,我就可以设置一个if语句,根据函数返回的内容确定下一步要做什么。有人能帮我一下吗?

def check_guess(player_hand, player_hand_2, guess, player_pairs):
'''
This checks a player's hand for the guessed card and 
if the guessed card is in the hand it removes the card from both
player's hands
'''
num = 0
card1 = guess
size = len(player_hand)
while num <= size:
card2 = player_hand[num]
if card1[:-1] == card2[:-1]:
player_pairs.append(card1)
player_pairs.append(card2)
player_hand.remove(card2)
player_hand_2.remove(card1)
return True
elif card1[:-1] != card2[:-1]:
num += 1
return False   #I added this at the end and when the guess is right it works but when the guess is wrong, I get an error message.

您的问题后,使"返回false ";加法只是一个循环索引问题。您的num变量从0增加到size,但列表只有从0到size-1的索引。并且假定列表不为空。

与while循环相比,更安全、更简单地遍历列表:

def check_guess(player_hand, player_hand_2, guess, player_pairs):
'''
This checks a player's hand for the guessed card and 
if the guessed card is in the hand it removes the card from both
player's hands
'''
for card in player_hand:
if card[:-1] == guess[:-1]:
player_pairs.extend([card, guess])
player_hand.remove(card)
player_hand_2.remove(guess)
return True
return False
my_hand = ['4h']
other_hand = ['4s','4c']
my_pairs = list()
check_guess(other_hand, my_hand, '4h', my_pairs)
print(my_pairs)

相关内容

最新更新