• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python card game 'war' dictionary problems

computer

Active Coder
I am a kid that is taking videos on how to code in python. I am making the card game war as a project and have been stuck on a problem for weeks. if i use a dictionary to show the card suits, or the face cards, it ignores if the cards are eaqual. i dont know where the problem is, so i'll post the entire thing. also, I am working in pycharm.

ps: if I use this,⬇︎ ,instead of the dictionary, the code runs without a flaw.
↳ unconverted_deck =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,1,2,3,4,5,6,7,8,9,10,11,12,13,14,1,2,3,4,5,6,7,8,9,10,11,12,13,14,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
here




Python:
import random
import time
test_list2 = []
test_list1 = []

unconverted_deck = {'2❤️' : 2,
                    '3❤️' : 3,
                    '4❤️' : 4,
                    '5❤️' : 5,
                    '6❤️' : 6,
                    '7❤️' : 7,
                    '8❤️' : 8,
                    '9❤️' : 9,
                    '10❤️' : 10,
                    'J❤️' : 11,
                    'Q❤️' : 12,
                    'K❤️' : 13,
                    'A❤️' : 15,
                    '2♠️' : 2,
                    '3♠️': 3,
                    '4♠️': 4,
                    '5♠️': 5,
                    '6♠️': 6,
                    '7♠️': 7,
                    '8♠️': 8,
                    '9♠️': 9,
                    '10♠️': 10,
                    'J♠️': 11,
                    'Q♠️': 12,
                    'K♠️️': 13,
                    'A♠️️': 15,
                    '2♦️': 2,
                    '3♦️': 3,
                    '4♦️': 4,
                    '5♦️': 5,
                    '6♦️': 6,
                    '7♦️': 7,
                    '8♦️': 8,
                    '9♦️': 9,
                    '10♦️': 10,
                    'J♦️': 11,
                    'Q♦️': 12,
                    'K♦️': 13,
                    'A♦️': 15,
                    '2︎♣️': 2,
                    '3♣️': 3,
                    '4♣️': 4,
                    '5♣️': 5,
                    '6♣️': 6,
                    '7♣️': 7,
                    '8♣️': 8,
                    '9♣️': 9,
                    '10♣️': 10,
                    'J♣️': 11,
                    'Q♣️': 12,
                    'K♣️': 13,
                    'A♣️': 15}
oedokn = list(unconverted_deck)
random.shuffle(oedokn)

computer_primary = oedokn[1::2]
player_primary = oedokn[0::2]
#random.shuffle(player_primary)
#random.shuffle(computer_primary)
player_secondary = []
computer_secondary = []
turns = 5
play_card_index = 0
# ---------------------------------
print(player_primary)
print(computer_primary)
comp_card_index = 0
play_war_at_risk = []
comp_war_at_risk = []

while winner := ' ':
    play_win_round = False
    comp_win_round = False
    play_len = len(player_primary) + len(player_secondary)
    comp_len = len(computer_primary) + len(computer_secondary)
    #print('play len = ' + str(play_len))
    #print('comp len = ' + str(comp_len))
    print(' ')
    print(' ')
    ready = input("Ready?:  ")
    try:
        if ready.lower() == "":
            print("your card is: " + str(player_primary[play_card_index]))
            print("your opponent's is: " + str(computer_primary[comp_card_index]))
    # ------------------------------------
            if player_primary[play_card_index] > computer_primary[comp_card_index]:
                player_secondary.append(player_primary[play_card_index])
                player_secondary.append(computer_primary[comp_card_index])
                player_primary.remove(player_primary[play_card_index])
                computer_primary.remove(computer_primary[comp_card_index])
                print('player discard: '+str(player_secondary))
                play_win_round = True
                print('computer discard: [?,?,?...]')
            elif player_primary[play_card_index] < computer_primary[comp_card_index]:
                computer_secondary.append(player_primary[play_card_index])
                computer_secondary.append(computer_primary[comp_card_index])
                player_primary.remove(player_primary[play_card_index])
                computer_primary.remove(computer_primary[comp_card_index])
                print('player discard: '+str(player_secondary))
                print('computer discard: [?,?,?...]')
                comp_win_round = True
            elif play_win_round or comp_win_round == False:
                while len(comp_war_at_risk) < 4:
                    play_war_at_risk.append(player_primary[play_card_index])
                    player_primary.remove(player_primary[play_card_index])
                    comp_war_at_risk.append(computer_primary[comp_card_index])
                    computer_primary.remove(computer_primary[comp_card_index])
                # ------------------------------------
                print('player cards at risk: '+str(play_war_at_risk))
                print('computer cards at risk: [?,?,?...]'
                print(' ')
                input("⚔️ Ready for war⚔️?:  ")
                print(' ')
                print("your card is: " + str(player_primary[play_card_index]))
                print("your opponent's is: " + str(computer_primary[comp_card_index]))
                # ------------------------------------
                if player_primary[play_card_index] > computer_primary[comp_card_index]:
                    player_secondary.append(player_primary[play_card_index])
                    player_secondary.append(computer_primary[comp_card_index])
                    player_primary.remove(player_primary[play_card_index])

                    # ------------------------------------------
                    player_secondary.append(play_war_at_risk[0])
                    player_secondary.append(play_war_at_risk[1])
                    player_secondary.append(play_war_at_risk[2])
                    player_secondary.append(play_war_at_risk[3])
                    # -------------------------------------------
                    player_secondary.append(comp_war_at_risk[0])
                    player_secondary.append(comp_war_at_risk[1])
                    player_secondary.append(comp_war_at_risk[2])
                    player_secondary.append(comp_war_at_risk[3])
                    # -------------------------------------------
                    play_war_at_risk.clear()
                    comp_war_at_risk.clear()
                    # -------------------------------------------
                    computer_primary.remove(computer_primary[comp_card_index])
                    print('player discard: ' + str(player_secondary))
                    print('computer discard: [?,?,?...]')
                    # -------------------------------------------
                elif player_primary[play_card_index] < computer_primary[comp_card_index]:
                    computer_secondary.append(player_primary[play_card_index])
                    computer_secondary.append(computer_primary[comp_card_index])
                    player_primary.remove(player_primary[play_card_index])
                    computer_primary.remove(computer_primary[comp_card_index])
                    # --------------------------------------------
                    computer_secondary.append(play_war_at_risk[0])
                    computer_secondary.append(play_war_at_risk[1])
                    computer_secondary.append(play_war_at_risk[2])
                    computer_secondary.append(play_war_at_risk[3])
                    # -------------------------------------------
                    computer_secondary.append(comp_war_at_risk[0])
                    computer_secondary.append(comp_war_at_risk[1])
                    computer_secondary.append(comp_war_at_risk[2])
                    computer_secondary.append(comp_war_at_risk[3])
                    # -------------------------------------------
                    play_war_at_risk.clear()
                    comp_war_at_risk.clear()
                    print('player discard: ' + str(player_secondary))
                    print('computer discard: [?,?,?...]')
                elif player_primary[play_card_index] == computer_primary[comp_card_index]:
                    while len(comp_war_at_risk) < 4:
                        play_war_at_risk.append(player_primary[play_card_index])
                        player_primary.remove(player_primary[play_card_index])
                        comp_war_at_risk.append(computer_primary[comp_card_index])
                        computer_primary.remove(computer_primary[comp_card_index])
                    print(play_war_at_risk)
                    print(comp_war_at_risk)
                    print('your at risk = ' + str(play_war_at_risk))
                    print('COMP at risk = '+ str(comp_war_at_risk))
                    print(' ')
                    print(' ')
                    ready = input("⚔️ Ready for war⚔️?:  ")
    except IndexError:
        for u in computer_secondary:
            computer_primary.append(u)
            random.shuffle(computer_primary)
        for i in player_secondary:
            player_primary.append(i)
            random.shuffle(player_primary)
        computer_secondary.clear()
        player_secondary.clear()
        print('    new round ')
        print('    good luck')
        print('    👍🏻👍🏻👍🏻👍🏻👍🏻')
        print('    🤘🏻😁🤘🏻😁🤘🏻 ')
        print(' ')
        print(' ')
        print(' ')
        print(' ')
        print(' ')
        turns=turns+1
    if play_len == 0:
        for e in player_secondary:
            player_primary.append(e)
        print('end of the game!')
        print('the winner is...')
        print('💣🧨💣🧨')
        print(5)
        time.sleep(1)
        print(4)
        time.sleep(1)
        print(3)
        time.sleep(1)
        print(2)
        time.sleep(1)
        print(1)
        time.sleep(1)
        print('💥💥 you 💥💥')
        break
    elif comp_len == 0:
        for e in computer_secondary:
            computer_primary.append(e)
        print('end of the game!')
        print('the winner is...')
        print('💣🧨💣🧨')
        print(5)
        time.sleep(1)
        print(4)
        time.sleep(1)
        print(3)
        time.sleep(1)
        print(2)
        time.sleep(1)
        print(1)
        time.sleep(1)
        print('💥💥 computer 💥💥')
        break
 
Solution
Here is a working example of using classes. Not all the Player attributes are used. They are just for display examples.

Python:
# Do the imports
import random as rnd
from tabulate import tabulate
from sys import platform
import subprocess
from time import sleep
def clear():
    subprocess.call('cls' if platform == 'win32' else 'clear')

class Player:
    ''' Create the player class
        Set some class variables
        Return a string representation
    '''
    def __init__(self, player):
        self.player = player
        self.card = None
        self.cards = 0
        self.win = 0
        self.loss = 0
    def __repr__(self):
        return f'{self.player}: Cards:{self.cards} wins: {self.win} loss: {self.loss}'

class Card:
    '''...

cbreemer

King Coder
Well, that is quite a wad of code... I hope you don't expect anyone to try and understand all that, let alone debug it.
One thing I wonder about : you are using the same values 2..15 for all four suits of cards. Are you sure that is that the right thing to do ?
What I do when I can't find a problem is reduce the code gradually, stepwise removing everything that isn't essential to the problem. In this iterative process, either you find the problem or you end up with a minimal code set that reproduces the problem and that someone else can test and perhaps debug. This approach always works wonders for me.
 

computer

Active Coder
thanks for your help and I'll try to use your approach the problem your way. one of the things I am curious about, is that the code runs without a flaw when I use a list. But then again, I am new to coding and am just in 7'th grade and you probably know much more than me. I appreciate your advice! thanks:thumbsup::)
 

cbreemer

King Coder
thanks for your help and I'll try to use your approach the problem your way. one of the things I am curious about, is that the code runs without a flaw when I use a list. But then again, I am new to coding and am just in 7'th grade and you probably know much more than me. I appreciate your advice! thanks:thumbsup::)
Ah sorry, I missed the bit about it working fine with the list. So what you are saying it all works fine with the list, and it works sort of fine with the dictionary too, except that for instance 9 of spades is not recognized as equal value to 9 of clubs ? Then I guess you may be comparing key/value pairs rather than just the value, which will of course always be different. Just a hunch though.
 

computer

Active Coder
If that is the problem, what are some possible solutions? If you have anything that can help, please tell me. I have been grounded for almost a month because I have not finished this project. I would like to finish ASAP.
 

computer

Active Coder
Also, the exemple you gave was perfect, but one thing I left out was that 90% of the time, the normal comparisions (<, >) work exactly as planed. But somtimes, both cards are randomly assigned to either the computer, or the player. I have not Identified any pattern when this happens. I don't know if this will help clear up some of the problem, but one thing I have recently learned is that even the smallest thing can change the whole program. Thanks for any past and future help on this, or any other, matter!
 

cbreemer

King Coder
I'm not at all sure what the problem is ! Already the problem description is not clear to me.
But here's some things I notice in your code which you may want to address:

Syntax error at line 115 (no closing bracket)

Line 107 elif play_win_round or comp_win_round == False: looks suspicious to me. I'm not familiar with Python's boolean logic, but I have I have a feeling that you intended this:
elif (play_win_round == False) or (comp_win_round == False) :

Your variables play_card_index and comp_card_index are initialized to zero and subsequently never changed. Is that your intention ? If so, why not just use zero ? Or better still, assign variables for player_primary[0] and computer_primary[0]. o point in evaluating the same thing more than once.

The definitions for king and ace of spades contain a spurious character. This is not visible in the code you posted, but is visible after I pasted it into Visual Studio :
a.jpg

Inspection with a Hex editor revealed you have used one 3F byte too many there:

b.jpg
This may well be what is tripping you up in some special cases.

Also two observations on style :

Your long variable names create quite a "wall of text". I find code to be far more readable if names are a bit shorter, while still being descriptive. For example instead of computer_primary and computer_secondary I would use comp_1 and comp_2, and so on.

I don't like that you use a try block to check your index. Exceptions are to be used to handle external events, not to detect flaws in your program logic. Your code should take care the index remains within bounds.

I hope all this helps some.
 

menator01

Legendary Coder
You may want to consider using classes for your cards and deck. An example would be

Python:
import random as rnd

class Card:
    ''' Card with a suit and value '''
    suits = ['❤️', '♠️', '♦️', '♣️']
    values = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]

    def __init__(self, suit, value):
        self.suit = suit
        self.value = value

    # Return a string representation
    def __repr__(self):
        return f'{self.value} {self.suit}'

class Deck:
    ''' Card list that can shuffle '''
    def __init__(self, shuffle=False):
        self.cards = [Card(suit, value) for suit in Card.suits for value in Card.values]
        if shuffle:
            rnd.shuffle(self.cards)


deck = Deck()
# Shuffle deck
# deck = Deck(True)
print(deck.cards)

output

Code:
[Ace ❤️, 2 ❤️, 3 ❤️, 4 ❤️, 5 ❤️, 6 ❤️, 7 ❤️, 8 ❤️, 9 ❤️, 10 ❤️, Jack ❤️, Queen ❤️, King ❤️, Ace ♠️, 2 ♠️, 3 ♠️, 4 ♠️, 5 ♠️, 6 ♠️, 7 ♠️, 8 ♠️, 9 ♠️, 10 ♠️, Jack ♠️, Queen ♠️, King ♠️, Ace ♦️, 2 ♦️, 3 ♦️, 4 ♦️, 5 ♦️, 6 ♦️, 7 ♦️, 8 ♦️, 9 ♦️, 10 ♦️, Jack ♦️, Queen ♦️, King ♦️, Ace ♣️, 2 ♣️, 3 ♣️, 4 ♣️, 5 ♣️, 6 ♣️, 7 ♣️, 8 ♣️, 9 ♣️, 10 ♣️, Jack ♣️, Queen ♣️, King ♣️]
 

menator01

Legendary Coder
You could do comparison like

Python:
import random as rnd

class Card:
    ''' Card with a suit and value '''
    suits = ['❤️', '♠️', '♦️', '♣️']
    values = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]

    def __init__(self, suit, value):
        self.suit = suit
        self.value = value

    def __lt__(self, other):
        return self.value < other.value

    def __gt__(self, other):
        return self.value > other.value

    def __eq__(self, other):
        return self.value == other.value

    # Return a string representation
    def __repr__(self):
        return f'{self.value} {self.suit}'

class Deck:
    ''' Card list that can shuffle '''
    def __init__(self, shuffle=False):
        self.cards = [Card(suit, value) for suit in Card.suits for value in Card.values]
        if shuffle:
            rnd.shuffle(self.cards)

    def deal(self, count=1):
        cards = self.cards[:count]
        self.cards = self.cards[count:]
        return cards

# Shuffle deck
deck = Deck(True)
card = deck.deal()
card2 = deck.deal()


print(f'{card} > {card2} {card > card2}')
print(f'{card} < {card2} {card < card2}')
print(f'{card} = {card2} {card == card2}')

output
Code:
[Queen ♠️] > [10 ❤️] True
[Queen ♠️] < [10 ❤️] False
[Queen ♠️] = [10 ❤️] False
 

menator01

Legendary Coder
I've noticed in some instances that comparison gives false readings. You should consider what cbreemer said about the spurious characters.
Clearly 2 of spades is not greater than 10 of diamonds
output
Code:
[2 ♠️] > [10 ♦️] True
[2 ♠️] < [10 ♦️] False
[2 ♠️] = [10 ♦️] False
 

menator01

Legendary Coder
Making the values a tuple in the Card class seems to correct the issue and then change the dunder methods

Python:
values = [("Ace",14), ("2",2), ("3",3), ("4",4), ("5",5), ("6",6), ("7",7), ("8",8), ("9",9), ("10",10), ("Jack",11), ("Queen",12), ("King",13)]

Python:
    def __lt__(self, other):
        return self.value[1] < other.value[1]

    def __gt__(self, other):
        return self.value[1] > other.value[1]

    def __eq__(self, other):
        return self.value[1] == other.value[1]

    # Return a string representation
    def __repr__(self):
        return f'{self.value[0]} {self.suit}'
 

menator01

Legendary Coder
Here is a working example of using classes. Not all the Player attributes are used. They are just for display examples.

Python:
# Do the imports
import random as rnd
from tabulate import tabulate
from sys import platform
import subprocess
from time import sleep
def clear():
    subprocess.call('cls' if platform == 'win32' else 'clear')

class Player:
    ''' Create the player class
        Set some class variables
        Return a string representation
    '''
    def __init__(self, player):
        self.player = player
        self.card = None
        self.cards = 0
        self.win = 0
        self.loss = 0
    def __repr__(self):
        return f'{self.player}: Cards:{self.cards} wins: {self.win} loss: {self.loss}'

class Card:
    ''' Card with a suit and value '''
    suits = ['❤️', '♠️', '♦️', '♣️']
    values = [("Ace",14), ("2",2), ("3",3), ("4",4), ("5",5), ("6",6), ("7",7), ("8",8), ("9",9), ("10",10), ("Jack",11), ("Queen",12), ("King",13)]
    def __init__(self, suit, value):
        self.suit = suit
        self.value = value
    def __lt__(self, other):
        return self.value[1] < other.value[1]
    def __gt__(self, other):
        return self.value[1] > other.value[1]
    def __eq__(self, other):
        return self.value[1] == other.value[1]
    # Return a string representation
    def __repr__(self):
        return f'{self.value[0]} of {self.suit}'

class Deck:
    ''' Card list that can shuffle '''
    def __init__(self, shuffle=False):
        self.cards = [Card(suit, value) for suit in Card.suits for value in Card.values]
        if shuffle:
            rnd.shuffle(self.cards)
    # For getting how many cards are in the deck
    def __len__(self):
        return len(self.cards)
    # Deal cards Default is one
    def deal(self, count=1):
        cards = self.cards[:count]
        self.cards = self.cards[count:]
        return cards

class Game:
    '''
        Class for setting up gameplay
    '''
    def __init__(self, player):
        self.player1 = Player(player)
        self.player2 = Player('computer')
        self.last_winner = None
        self.deck = Deck(True)
    # Method for getting winner
    def check(self):
        if self.player1.card == self.player2.card:
            self.last_winner = None
            words = ['I', 'declare', 'war', 'on', 'you!']
            speak = []
            for i in range(5):
                speak.append(words[i])
                clear()
                print(' ' .join(speak))
                sleep(0.75)
            self.player1.card = self.deck.deal()
            self.player2.card = self.deck.deal()
            self.check()
        elif self.player1.card > self.player2.card:
            self.last_winner = self.player1
            self.player2.loss += 1
        else:
            self.last_winner = self.player2
            self.player1.loss += 1
        if self.last_winner:
            self.last_winner.win += 1
    # Method for displaing results
    def show(self):
        clear()
        print(f'{self.player1.player}\'s Card: {self.player1.card[0]}, {self.player2.player}\'s Card: {self.player2.card[0]}')
        if self.last_winner:
            print(f'{self.last_winner.player} wins the round')
        else:
            print('tie game')
        print('\nCurrent Stats:')
        print(tabulate([[self.player1, self.player2]],tablefmt='pretty'))
    # Method for gameplay
    def play(self):
        self.player1.card = self.deck.deal()
        self.player2.card = self.deck.deal()
        self.check()
        self.show()
        if len(self.deck) <= 0:
            self.deck = Deck(True)
    # The main game loop
    def mainloop(self):
        while True:
            self.play()
            play_again = input('Play Again, Enter \'y\' ').upper()
            if play_again != 'Y':
                clear()
                print('Thanks for playing Cards of War.')
                print(f'Final Score:\n{tabulate([[self.player1, self.player2]], tablefmt="pretty")}')
                break
if __name__ == '__main__':
    ''' Start title loop '''
    while True:
        # List of letters to display for title
        war = ['W', 'A', 'R']
        # Empty title list / will append a letter through each iteration and print
        title = []
        for i in range(3):
            title.append(war[i])
            sleep(0.75)
            clear()
            print(''.join(title))
        # If i == 2 insert text into list at index 0 and print. Break out of while loop
        if i == 2:
            sleep(0.75)
            title.insert(0, 'Cards of ')
            clear()
            print(''.join(title))
            sleep(1.5)
            break
        
    '''
        Get player name
    '''
    clear()
    while True:
        print('Welcome to Cards of War!')
        print('Enter your name')
        name = input('>> ')
        if not name:
            print('You must enter a name')
        else:
            break
    Game(name).mainloop()

output
Code:
pop's Card: 9 of ♣️, computer's Card: 5 of ♠️
pop wins the round

Current Stats:
+------------------------------+-----------------------------------+
| pop: Cards:0 wins: 6 loss: 4 | computer: Cards:0 wins: 4 loss: 6 |
+------------------------------+-----------------------------------+
Play Again, Enter 'y'

Thanks for playing Cards of War.
Final Score:
+------------------------------+-----------------------------------+
| pop: Cards:0 wins: 6 loss: 4 | computer: Cards:0 wins: 4 loss: 6 |
+------------------------------+-----------------------------------+
 
Last edited:
Solution

computer

Active Coder
WOW!
please read the side note!!!

cbreemer-​

thank you for helping me along the way! without you, I would have given up a while ago. you helped me along the way,and made me improve so that I am now almost twice as good at decoding and thinking about my code than before. Thank you for dedicating some of your time to helping me. I have seen some of the ways you help others and am gratefull for the way you help many new coders out when they need it.
Contine being awsome, helpfull, and great at everything(mostly coding)! thank you!! :thumbsup:


menator01-​

umm... wow! I have never even heard of you before and you just come in and write all of my code for me! This is generous beyond what I expected. Not only that, but you explain most of the problems I have and how to solve them. I can't thank you enough for this. I am just a kid in 7'th grade trying out somthing new. I have been grounded for a month because I didn't know how to finish this. Thank you!!

both of you
thank you for your time and atention to my problem. I will come to you guys if I ever get stuck for weeks again.

side note:
Inside of Menator01's "working example" there is an import called 'tabulate'. when I tried this code out in Pycharm (my coding envirment), it did not reconize this import. any Ideas why this is? And if you dont know, how would I use this code(or simular code) without it?
 

cbreemer

King Coder
You're welcome. Just curious, did removing these two spurious bytes fix it for you ? Or did you go for menator01's complete object-oriented solution ?

EDIT - Never mind that question, I see that you went for the provided complete code.
 
Last edited:

menator01

Legendary Coder
Here is a short video on how to install tabulate with pip.
You may need to install pip but, I think the newer versions of python already have it preinstalled.
In the video I use pip as that's how how I set it up for my box. You may need to use pip3.
python3 -m pip3 install tabulate



Hope this helps.

Latest version of the script:


Python:
#! /usr/bin/env python3
# Do the imports
import random as rnd
from tabulate import tabulate
from sys import platform
import subprocess
from time import sleep

def clear():
    subprocess.call('cls' if platform == 'win32' else 'clear')


class Player:
    ''' Create the player class
        Set some class variables
        Return a string representation
    '''
    def __init__(self, player):
        self.player = player
        self.card = None
        self.cards = []
        self.win = 0
        self.loss = 0

    def __repr__(self):
        return f'{self.player}: Cards:{len(self.cards)} wins: {self.win} loss: {self.loss}'


class Card:
    ''' Card with a suit and value '''
    suits = ['❤️', '♠️', '♦️', '♣️']
    values = [("Ace",14), ("2",2), ("3",3), ("4",4), ("5",5), ("6",6), ("7",7), ("8",8), ("9",9), ("10",10), ("Jack",11), ("Queen",12), ("King",13)]

    def __init__(self, suit, value):
        self.suit = suit
        self.value = value

    def __lt__(self, other):
        return self.value[1] < other.value[1]

    def __gt__(self, other):
        return self.value[1] > other.value[1]

    def __eq__(self, other):
        return self.value[1] == other.value[1]

    # Return a string representation
    def __repr__(self):
        return f'{self.value[0]} of {self.suit}'


class Deck:
    ''' Card list that can shuffle '''
    def __init__(self, shuffle=False):
        self.cards = [Card(suit, value) for suit in Card.suits for value in Card.values]
        if shuffle:
            rnd.shuffle(self.cards)

    # For getting how many cards are in the deck
    def __len__(self):
        return len(self.cards)

    # Deal cards Default is one
    def deal(self, count=1):
        cards = self.cards[:count]
        self.cards = self.cards[count:]
        return cards


class Game:
    '''
        Class for setting up gameplay
    '''
    def __init__(self, player):
        self.player1 = Player(player)
        self.player2 = Player('computer')
        self.last_winner = None
        self.deck = Deck(True)

    # Method for getting winner
    def check(self):
        '''
            If cards are equal print out words list
            Using sleep so all words do not print out all at once
            self.last_winner will be None as will need to draw again
            call self.check() so cards can be compared again
        '''
        if self.player1.card == self.player2.card:
            self.last_winner = None
            words = ['I', 'declare', 'war', 'on', 'you!']
            speak = []
            for i in range(5):
                speak.append(words[i])
                clear()
                print(' ' .join(speak))
                sleep(0.75)
            self.player1.card = self.deck.deal()
            self.player2.card = self.deck.deal()
            self.check()
        # If player has high card set player 1 winner
        # Add 1 to player 2 loss score
        elif self.player1.card > self.player2.card:
            self.last_winner = self.player1
            self.player2.loss += 1
        else:
            # Same as above but, for player 2
            self.last_winner = self.player2
            self.player1.loss += 1
        if self.last_winner:
            self.last_winner.win += 1

    # Method for displaing results
    def show(self):
        clear()
        headers = ['Player', 'Card']
        data = [[self.player1.player, self.player1.card[0]], [self.player2.player, self.player2.card[0]]]
        print(tabulate(data, headers=headers), '\n')
        if self.last_winner:
            print(f'{self.last_winner.player} wins the round')
        else:
            pass
        print('\nCurrent Stats:')
        print(tabulate([[self.player1, self.player2]],tablefmt='pretty'))


    # Method for gameplay
    # If the deck get down to only four cards
    # generate a new deck
    def play(self):
        self.player1.card = self.deck.deal()
        self.player2.card = self.deck.deal()
        self.check()
        self.show()
        if len(self.deck) <= 0:
            self.deck = Deck(True)

    # The main game loop
    def mainloop(self):
        while True:
            self.play()
            play_again = input('Play Again, Enter \'y\' ').upper()
            if play_again != 'Y':
                clear()
                print('Thanks for playing Cards of War.')
                print(f'Final Score:\n{tabulate([[self.player1, self.player2]], tablefmt="pretty")}')
                break

if __name__ == '__main__':
    ''' Start title loop '''
    while True:
        # List of letters to display for title
        war = ['W', 'A', 'R']

        # Empty title list / will append a letter through each iteration and print
        title = []
        for i in range(3):
            title.append(war[i])
            sleep(0.75)
            clear()
            print(''.join(title))

        # If i == 2 insert text into list at index 0 and print. Break out of while loop
        if i == 2:
            sleep(0.75)
            title.insert(0, 'Cards of ')
            clear()
            print(''.join(title))
            sleep(1.0)
            break

        
    '''
        Get player name
    '''
    clear()
    while True:
        print('Welcome to Cards of War!')
        print('Enter your name')
        name = input('>> ')
        if not name:
            print('You must enter a name')
        else:
            break
    Game(name).mainloop()
 
Last edited:
Top