C2C: Setup and Face-up Poker
Set up your environment
You can use a code editor of your choice. We like VSCode. You can also work with Google Colab in the browser. The instructions below are for coding locally on MacOS or Unix.
Step 1: Make directory
Make a local directory for the project cardstocode
. From the command line:
mkdir cardstocode
cd cardstocode
Step 2: Virtual environment
Create and activate a virtual environment:
python3 -m venv venv
source venv/bin/activate
You should now see (venv)
at the beginning of your command prompt, indicating that the virtual environment is active.
Step 3: Create Python file
Create a Python file c2c.py
. From the command line:
touch c2c.py
Step 4: Deactivating and reactivating virtual environment
To deactivate:
deactivate
To reactivate:
source venv/bin/activate
Step 5: Install numpy
Install numpy
, which we will use later.
pip install numpy
Face-up 1-card poker
We’ll start by setting up a poker game with a 3-card deck where the cards are given values {0, 1, 2}. Each player is dealt a card “face-up” and the higher card wins. This is like the game War, but even more simplified because there are no ties since the entire deck is only 3 cards.
Step 1: Imports
Let’s start by importing numpy
(will be used later) and random
.
Step 2: Cards and scores
Define a Game
class that is initialized with these class attributes:
3-card
deck
array with cards0
,1
, and2
Card placeholders for each player in a
cards
array that are initialized asNone
Score placeholders for each player in
scores
array that are initialized as0
Step 3: Deal cards
Let’s now add a deal_cards
function into the Game
class that samples two cards from the deck into self.cards
. This is the first of two class methods.
Step 4: Compare cards
Accumulate the scores for each player using self.scores
in a compare_cards
function. This is the second class method.
Step 5: Play round
Create a play_round
function in the Game
class that deals the cards using self.deal_cards
.
Step 6: Run the game
Create the main
function that defines num_games
as 100, creates an object of the Game
class in game
, and runs the game num_games
times.
Step 7: Print the scores
Print the scores for each player after the game ends, also in the main
function.
Step 8: Create the main block
Putting it all together
Run the code
python3 c2c.py
The output should look something like: