Cookie Jar - 2 years ago 77
Python Question

# Sorting Cards played in each trick according to a certain set of rules

Say I have a tuple of cards. Each of them represents a card played by a player.

``````('9D',   '9S',   '3S',   '0D')
Player0 Player1 Player2 Player3
``````

I wish to find the winning card in it and record who is the winner.

And the rules for deciding the winner is quite messy...

First I have a trump card used to determine the trump suit.
Say I have
`2D`
as a trump card. Then the suit Diamond becomes trump suit.

Secondly, the first card in the tuple means the leading card and all other players should attempt to follow the suit of that card, if not then the card being played by that player virtually lost.

I wish to compare the face value of those cards. 0 stands for 10 in this case. The card with the highest value and also follows the suit wins. Below is my code and I have not gotten even close to the goal. I know the what is the goal for me to achieve. But my code definitely contains redundancy. Is there a better way to accomplish this?

Any advice on how to implement a neat solution are greatly appreciated.

My code:

``````    tricks = ('9D', '9S', '3S', '0D')
counter = 1
for i in tricks:
while counter < len(i):
if max_score[1] == deck_top[1]:
# Check if it is in trump suit.
if int(i[counter-1][0]) < int(i[counter][0]):
# Compare face value
if i[counter-1][0] == i[counter][0]:
# Compare the suit.
if i[counter][1] == i[counter][1]:
``````

You can do it with a list comprehension, max() and a custom sort key. I'm not positive I correctly understand the problem but I interpreted it as: the winner is the card with the highest value and the same suit as the trump card

``````def getCardValue(inputVal): #custom key func that calculates zero as a 10
num = int(inputVal[:-1])
if num == 0:
return 10
return num

trumpCard = '2D'
tricks = ('9D', '9S', '3S', '0D')
potentialWinners = [x for x in tricks if x[-1] == trumpCard[-1]] #remove cards that don't have same suit as trumpCard
print(max(potentialWinners, key=getCardValue)) #get max card value while calculating zero as 10
``````

# Modifications to getCardValue to use J, Q, K, A

``````def getCardValue(inputVal): #custom key func that calculates zero as a 10
inputVal = inputVal[:-1]
specialValues = {"J": 11, "Q": 12, "K": 13, "A": 14}
if inputVal in specialValues.keys():
return specialValues[inputVal]

num = int(inputVal)
if num == 0:
return 10
return num
``````

# Modifications to get the index of the winner

Change the last two lines to:

``````winner = max(potentialWinners, key=getCardValue) #get max card value while calculating zero as 10
print("player", tricks.index(winner), "wins with the card", winner)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download