Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • 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.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • 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:
    '''...
I've not ever used a mac so, I don't know anything about them.
The information I gave in the last post came from https://www.geeksforgeeks.org/how-to-install-pip-in-macos/

open a terminal and type pip --version and hit enter to see if pip is installed.
If it's not copy and paste:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
in the terminal and hit enter
and then copy and paste
python3 get-pip.py
in the terminal. That should install pip.

Then in the terminal copy and paste
python3 -m pip install tabulate

That should install the tabulate module in python and you should be able to run my example without errors.
 
I don't use pycharm so I can't help you with anything related to it. I did try it once and found it to be too bloated and resource intensive.
I used atom for a long time and had to switch because it will be archived at years end.
Now I use Visual Studio.
 
ok. I did that and the termanal said that the download had been successful, but no matter how many times I close and reopen pycharm, it always says that it doesn't reconize 'tabulate'. I am going to try to use a different coding envirment and see if it has the same resultes.
once again, thanks for your time & help & quick responses!
 
Here is a version that doesn't use tabulate.

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')
        print(f'{self.player1.player} got {self.player1.card[0]}\n{self.player2.player} got {self.player2.card[0]}\n')
        if self.last_winner:
            print(f'{self.last_winner.player} wins the round')
        else:
            pass
        print('\nCurrent Stats:')
        print(f'{self.player1} | {self.player2}\n')
        # 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('\nPlay Again, Enter \'y\' ').upper()
            if play_again != 'Y':
                clear()
                print('\nThanks for playing Cards of War.\n')
                print(f'Final Score:\n{self.player1}\n{self.player2}\n')
                # 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()
 
Your python3 command says that module tabulate is already installed, but your PyCharm does not want to recognize it. This doesn't surprise me much, as the screenshot suggests your PyCharm is using Python 2.10. Not sure why that is, but you should upgrade to 3.10,
 
I did.
I have the newest python update, I upraded Pycharm to the latest version, and when neither of those did anything, I compleatly reinstalled Pycharm.

edit - now I just switched to Visual studios
 
Last edited:
ok. on the coding envirment that you sugested, the code runs without a flaw! one thing I dont understand, is why in 'current stats', the number of cards for both of them is always 0. either way, this will defenitly get me ungrounded. :) THANKS!
Happy So Excited GIF
Excited Aww GIF
 
so, just to clarify, you gave me the majority of the game, but I have to make It use a realistic deck?

also, if it is an endless deck, why does the game end at random times?
 
Back
Top Bottom