Cookie Jar - 1 year ago 68

Python Question

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`

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.

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]:

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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
```

```
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
```

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)
```