DEV Community

Jacob Wooldredge
Jacob Wooldredge

Posted on

Coding First Card Game with Python

Background

For my first Python project, my goal was to build a basic terminal program for friends to play with. I thought a card game would be a great first program to code independently! My close friends enjoy cards (specifically euchre), but they came up with a silly game of their own called Face Card or Nah?. The rules are in the repository readme, but the idea is simple: the player has to guess certain attributes for five cards before they're shown. If all attributes are correct, the player wins and the next person goes. There's no points or score kept- it's just a fun (and maybe frustrating) game to play.

Image description

The Code

The program is mainly comprised of basic functions for each question prompt - all of which are used sequentially in the main game function. Some functions/questions required more logic than others, which was fun to work through such as the in/out question. This one required different range arguments depending on if the second card drawn was greater than the first card. A lot of other functions involved checking the user input against a class attribute (e.g. color, suit, and if the card is a face card).

For the deck itself - I knew a card class would be great to work with so I looked around Stack Overflow until I found a great idea for a class to expand on and add attributes that were specific to the game. I used a list iteration to instantiate the cards using two for loops which looped through a list containing the suits and then looped through a dictionary containing the card names and their corresponding values.

Since the game requires six cards for each turn, I used the random module for a function to pop six cards from the deck and return them in a draw variable. It wasn't until testing the program that I realized a discard pile was needed or else the game would only run for 8 turns before returning an error since there were not enough cards left for the next function call, so I created a global variable for an empty list which the draw function uses to append the popped cards. I also needed a function to represent "shuffling" the deck, so I took the remaining four cards from the deck and appended them to the discard pile before adding the cards back into the deck list. Then I used the random shuffle method before returning the deck. The game can be repeated indefinitely and will print a message every time the deck is being "shuffled".

Conclusion

This was a fun project to work on because I got to reinforce my learning while creating something that my friends and I can enjoy!
There were some "dead ends" which required me to rethink my original plan, but these were also great learning experiences.
It will be nice to revisit this project once I have more Python experience to potentially refactor and maybe add some more features!

https://github.com/jakew101/Python_Terminal_Game

Top comments (0)