Level 1 Python: War (Card Game)

Level 1 Python projects are the next level up from Super Simple Python projects. These projects are a little more complex, and/or involve more non-native Python libraries. Level 1 Python projects can be completed in about 30-45 minutes. In this post, we’re going to make the card game War! To do this, we’re going to borrow code from the Super Simple Python project, Generate a Deck of Cards.

Set Up War Card Game Python Code

As always, we’re going to start our program with our imports. Many of the projects we did in the Super Simple Python series, such as the High Low Guessing Game, the Dice Roll Simulator, or plotting a Random Data Set, use the random library. We’re also going to be using the random library for this project. You don’t need to import the sys library, but I’m going to take this chance to introduce it.

structure of directories
structure of directories

We’re going to use sys to extend the reach of our program. By appending .. to the sys.path of our project we can access sibling level directories. In this case, we’re going to be accessing the generate_cards function and face_cards dictionary from the starter_projects folder. After our imports, the last step of our setup is to generate the deck of cards.

import random
import sys
sys.path.append('..')
 
from starter_projects.generate_deck import generate_cards, face_cards
 
cards = generate_cards()

Split the Deck

Now that we’ve generated the deck of cards, let’s make a way to split the deck up. We’re going to make a function that takes one parameter, the car. At the start of the function, we’re going to use the random library to sample 26 cards. The sample() function takes two parameters, a list, and a number. It will return the passed in number of samples from the list.

We’ll use that sample of 26 cards and assign that as “your” cards. We’ll take the rest and assign it to your opponent’s hands. To make sure your opponent’s hand isn’t the cards in order, we’ll shuffle it. Finally, we return both hands.

def split_deck(cards=cards):
    yours = random.sample(cards, 26)
    opp = [i for i in cards if i not in yours]
    random.shuffle(opp)
    return yours, opp
 
your_cards, opp_cards = split_deck()

War Card Game Logic Python Code

Once we have the cards split up we gotta build the game logic. The first step is to build a function to draw cards. The draw function will take one parameter, cards. All this function will do is pop the first card in the list.

def draw(cards):
    return cards.pop(0)

After building a draw function, we can now implement the logic to play a turn of the game. The play_turn function will take in two parameters, your cards and the opponent’s cards. Both are lists. The first thing we’ll do in this function is draw cards. Once we draw the cards, if the cards are face cards, we’ll convert their values. Then we display the cards that were drawn and compare them. If your card is greater, you win, if your opponent’s card is greater they win, if it’s a tie nothing happens. The winner of each hand gets both cards added to their deck. At the end of the function we return the augmented decks.

def play_turn(yours=your_cards, opp=opp_cards):
    your_play = draw(yours)
    opp_play = draw(opp)
    your_val = your_play.value if your_play.value not in face_cards else face_cards[your_play.value]
    opp_val = opp_play.value if opp_play.value not in face_cards else face_cards[opp_play.value]
    print(f"Your play: {your_val} {your_play.suit}")
    print(f"Opp play: {opp_val} {opp_play.suit}")
    if your_val > opp_val:
        yours.append(your_play)
        yours.append(opp_play)
    elif opp_val > your_val:
        opp.append(opp_play)
        opp.append(your_play)
    else:
        yours.append(your_play)
        opp.append(opp_play)
    return yours, opp

Play the Game!

We’ve fully set up the War game, now all we need to do is play the game. I warn you though, this game could run basically forever, and you may not even get a winner. All we do to play the game is start by assigning cards for a turn, and then loop through and play a turn while both players still have cards in their decks.

yours, opp = play_turn()
counter = 0
while yours and opp:
    counter += 1
    yours, opp = play_turn(yours, opp)
    print(counter)
    print(len(yours), len(opp))
    if len(yours) == 0:
        print("You Lose!")
    if len(opp) == 0:
        print("You Win!")

The images below give an example of what it looks like when we run the game. If you’d prefer to show the J, Q, K, and A values instead of 11, 12, 13, and 14, just use face_cards to convert the cards. In this example, we won in 215 turns.

The first plays:

Start of the Python War Card Game sim
Start of the Python War Card Game sim

The last plays:

Python War Card Game Results
Python War Card Game Results

Learn More

To learn more, feel free to reach out to me @yujian_tang on Twitter, connect with me on LinkedIn, and join our Discord. Remember to follow the blog to stay updated with cool Python projects and ways to level up your Software and Python skills! If you liked this article, please Tweet it, share it on LinkedIn, or tell your friends!

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang
Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

2 thoughts on “Level 1 Python: War (Card Game)

Leave a Reply

%d bloggers like this: