Python Project - Card Game

Rahul Patodi
Wiki Flood
Published in
5 min readNov 4, 2023

Most of us have experienced playing card games at least once in our lives. These games revolve around suits and ranks. A standard deck of cards comprises four suits: diamonds, spades, hearts, and clubs. Each suit incorporates face cards (king, queen, jack) and numbered cards ranging from 1 to 10.

The essence of the game lies in comparing the ranks of cards to determine the winner, based on who has the higher or lower ranked card, and eventually declaring the victor according to the player with more cards.

About Python Card Game Project:

In this Python project, we will build a Card Game in Python with its tkinter library, which provides a graphical user interface (GUI) for creating windows, labels and buttons. The game uses a standard deck of 52 playing cards, which are randomly shuffled and distributed between two players. Each player reveals their top card, and the player with the higher-ranking card wins the round. The winning player collects both cards, and the game continues until one player collects all the cards.

Prerequisites For Python Card Game Project:

  • Initially, we’ll use the pip installer to install the necessary library and module on our system.
  • This project necessitates a solid understanding of Python and proficiency in using tkinter to develop the GUI for the application.
pip install tkinter
pip install random
python card game project

Following Steps are Required to Build Project:

  1. Importing the library and module.
  2. Initializing GUI window.
  3. Creating Labels and Button.
  4. Implementing the Card Game function.

1. Importing the libraries and modules-

from tkinter import *
import random

tkinter- This library will help us in creating a GUI window for our program.
random- This module generates random integers in Python programs.

2. Initializing GUI window-

We will initiate the GUI window for the application.

root = Tk()
root.title("Card Game-PythonFlood")
root.geometry("350x320")
root.resizable(False, False)
root.config(bg='#E6E6FA')

root- It is the name of our GUI window.
Tk()- Initialised tkinter, which means GUI window created.
geometry()- This method provides the length and breadth to the GUI window.
resizeable()- This method allows the window to change its size as per user need.
title()- This method gives title to the window
confg()- This method sets the configuration of the window.

3. Creating Labels and Button-

We will generate label and button widgets, positioning them in alignment with the dimensions of the application’s GUI.

lb1 = Label(root, text="Player 1 Card", font=("Helvetica", 15), bg='#E6E6FA')
lb1.place(x=30, y=20)
lb2 = Label(root, text="Player 2 Card", font=("Helvetica", 15), bg='#E6E6FA')
lb2.place(x=30, y=50)

lb3 = Label(root, text=f"Player 1 Deck: {len(player1_deck)} cards", font=("Helvetica", 15), bg='#E6E6FA')
lb3.place(x=70, y=100)

lb4 = Label(root, text=f"Player 2 Deck: {len(player2_deck)} cards", font=("Helvetica", 15), bg='#E6E6FA')
lb4.place(x=70, y=140)

result_label = Label(root, text="", font=("Helvetica", 15), bg='#8B8386', fg='White', width=35, justify=CENTER)
result_label.place(x=0, y=270)

btn = Button(root, text="Play Round", font=("Helvetica", 15), bd=5, bg='#8B8386', fg='White', command=play)
btn.place(x=115, y=200)

root.mainloop()

Label()- It is used to display one line or more than one line of text.
text- It is used to display text on labels.
font- It is a style in which font is written.
bg- It is the background Colour of the label.
fg- it is the colour of characters in labels.
pack()- This displays the widgets in the GUI window.
pady- It provides padding between widgets y-axis.
Button()- It is a button used to display on our window.
bd- It is the border of the Button.
command- It is used as a function of a button when it is clicked.
place()- It is used to set the position.
root.mainloop()- This method will execute what we wish to execute in an application and end the mainloop.

4. Defining variables for cards and ranking-

Here we are declaring variables.

suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
nums = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
deck = [(rank, suit) for suit in suits for rank in nums]

random.shuffle(deck)

player1_deck = deck[:26]
player2_deck = deck[26:]

We’ve defined the variable “suits” to represent the suits in a deck of cards, and the variable “nums” to denote the card numbers within a suit. Subsequently, the “shuffle” method is employed to randomise the arrangement of cards within the deck.

random.shuffle(deck)- It is used to shuffle the deck randomly.

5. Implementing the Card Game function-

Now we will define the main game function i.e. def play().

def play():
if len(player1_deck) > 0 and len(player2_deck) > 0:

p1_card = player1_deck.pop(0)
p2_card = player2_deck.pop(0)

lb1.config(text=f"Player 1 Card: {p1_card[0]} of {p1_card[1]}")
lb2.config(text=f"Player 2 Card: {p2_card[0]} of {p2_card[1]}")

num1 = nums.index(p1_card[0])
num2 = nums.index(p2_card[0])

if num1 > num2:
result_label.config(text="Player 1 wins the round!")
player1_deck.append(p1_card)
player1_deck.append(p2_card)
elif num1 < num2:
result_label.config(text="Player 2 wins the round!")
player2_deck.append(p1_card)
player2_deck.append(p2_card)
else:
result_label.config(text="It's a tie!")

lb3.config(text=f"Player 1 Deck: {len(player1_deck)} cards")
lb4.config(text=f"Player 2 Deck: {len(player2_deck)} cards")

if len(player1_deck) == 0 or len(player2_deck) == 0:
if len(player1_deck) > len(player2_deck):
result_label.config(text="Player 1 wins the game!")
elif len(player1_deck) < len(player2_deck):
result_label.config(text="Player 2 wins the game!")
else:
result_label.config(text="It's a tie!")

Initially, we assess the count of cards possessed by both players. Subsequently, a card is drawn from each player’s deck and displayed on the GUI of the application.

Then, utilising if/elif/else statements, we convert the card ranks into numerical values and make comparisons to determine the victor, adding both cards to the deck of the winning player.

Furthermore, we employ another set of if/elif/else statements to gauge the card count for each player and declare the victor as the one with a larger card count.

pop()- This method is used to pop the first cards from both the player’s deck.
index()- This method is used to determine the position of a card rank within a list.
append()-
This method is used to append the cards in the winning players deck.
len()- This method returns the length of the string.

Python Card Game Output:

python card game output

Conclusion:

Congratulations! We’ve effectively built a Card Game using Python and the tkinter library for GUI development, along with the random module for selecting cards randomly. You can now enjoy playing this game and even tailor it to your preferences if desired.

--

--