How To Make Crazy Eights With Python | Multiplayer & AI Modes

“How To Make Crazy Eights: Fun Card Game for All Ages | Multiplayer & AI Modes”

Let’s create a simple Crazy Eights game with HTML, CSS, and Python. Crazy Eights is a classic card game that is usually played with a standard deck of 52 cards. The objective of the game is to get rid of all your cards by matching the rank or suit of the top card on the discard pile.

Step 1: HTML Structure

Create a new file named `crazy_eights.html` and add the following content:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crazy Eights Game</title>
<link rel="stylesheet" href="styles.css">

<div class="container">
<h1>Crazy Eights Game</h1>
<div id="instructions">
<p>Welcome to Crazy Eights! The objective is to get rid of all your cards by matching the rank or suit of
the top card on the discard pile. If you don't have a matching card, you can play an Eight to change the suit.</p>
<p>Click the "Start Game" button to begin.</p>
<div id="game" style="display: none;">
<!-- Game board will be dynamically generated here -->
<button id="start-btn">Start Game</button>

<script src="script.js"></script>


Step 2: CSS Styling

Create a new file named `styles.css` and add the following CSS styles:
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f5f5f5;

.container {
margin-top: 50px;

h1 {
font-size: 36px;
margin-bottom: 20px;

#instructions {
font-size: 18px;
margin-bottom: 20px;

#game {
display: flex;
flex-wrap: wrap;
justify-content: center;
margin-bottom: 20px;

.card {
width: 70px;
height: 100px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #fff;
margin: 5px;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
font-weight: bold;

button {
padding: 8px 16px;
background-color: #4CAF50;
color: #fff;
border: none;
cursor: pointer;

Step 3: Python Backend

Create a new file named `` for the Python backend. In this step, we’ll define the core functions for the Crazy Eights game.

import random
# Define the ranks, suits, and values of cards
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
SUITS = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
'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': 14

# Function to create a standard deck of 52 cards
def create_deck():
deck = []
for rank in RANKS:
for suit in SUITS:
deck.append((rank, suit))
return deck

# Function to shuffle the deck
def shuffle_deck(deck):

# Function to deal cards to players
def deal_cards(deck, num_players, num_cards):
players = []
for _ in range(num_players):
hand = [deck.pop() for _ in range(num_cards)]
return players

# Function to check if a card can be played
def can_play(card, top_card):
rank, suit = card
top_rank, top_suit = top_card
return rank == top_rank or suit == top_suit or rank == '8'

# Function to check if the player has any valid moves
def has_valid_move(hand, top_card):
return any(can_play(card, top_card) for card in hand)

# Function to check if the player has won
def has_won(hand):
return len(hand) == 0

# Function to check if the card is an Eight
def is_eight(card):
return card[0] == '8'

# Function to play an Eight card and change the suit
def play_eight(card, new_suit):
return (card[0], new_suit)

Step 4: JavaScript Interaction (Optional)

In this step, you can use JavaScript to interact with the Python backend without page reloads. To do this, create a new file named `script.js` and add the following content:

document.addEventListener("DOMContentLoaded", function () {
const instructionsDiv = document.getElementById("instructions");
const gameDiv = document.getElementById("game");
const startBtn = document.getElementById("start-btn");

let deck = [];
let players = [];
let currentPlayer = 0;
let topCard = null;
let currentSuit = null;

// Function to create a card element
function createCardElement(rank, suit) {
const cardDiv = document.createElement("div");
cardDiv.textContent = `${rank} ${suit}`;
return cardDiv;

// Function to display the player's hand
function displayHand(hand) {
gameDiv.innerHTML = "";
hand.forEach((card) => {
gameDiv.appendChild(createCardElement(card[0], card[1]));

// Event listener for the "Start Game" button
startBtn.addEventListener("click", function () {
// Reset game state
deck = [];
players = [];
currentPlayer = 0;
topCard = null;
currentSuit = null;

// Create and shuffle the deck
.then((response) => response.json())
.then((data) => {
deck = data.deck;
fetch("/shuffle-deck", {
method: "POST",
headers: {
"Content-Type": "application/json",
body: JSON.stringify({ deck: deck }),
}).then(() => {
// Deal cards to players
.then((response) => response.json())
.then((data) => {
players = data.players;
topCard = data.top_card;
currentSuit = topCard[1];

// Display player's hand
displayHand(players[currentPlayer]); = "none";

.style.display = "block";

// ... (remaining code)

Step 5: Flask Backend (Python Web Framework)

To create a basic backend server, you can use the Flask web framework in Python. To set up the backend, install Flask using pip:

pip install Flask

Then, create `` for the Flask application:

from flask import Flask, jsonify, request
from crazy_eights import create_deck, shuffle_deck, deal_cards, can_play, has_valid_move, has_won, is_eight, play_eight

app = Flask(__name__)

deck = []
players = []
current_player = 0
top_card = None
current_suit = None

@app.route("/create-deck", methods=["GET"])
def create_new_deck():
global deck
deck = create_deck()
return jsonify({"deck": deck})

@app.route("/shuffle-deck", methods=["POST"])
def shuffle_deck_route():
global deck
data = request.get_json()
deck = data["deck"]
return jsonify({})

@app.route("/deal-cards", methods=["GET"])
def deal_cards_route():
global deck, players, top_card, current_suit
players = deal_cards(deck, num_players=2, num_cards=5)
top_card = deck.pop()
current_suit = top_card[1]
return jsonify({"players": players, "top_card": top_card})

@app.route("/play-card", methods=["POST"])
def play_card():
global players, current_player, top_card, current_suit
data = request.get_json()
card = data["card"]
player_hand = players[current_player]

if can_play(card, top_card):
top_card = card
current_suit = card[1] if is_eight(card) else None

if has_won(player_hand):
return jsonify({"status": "win"})
elif not has_valid_move(player_hand, top_card):
return jsonify({"status": "invalid", "message": "No valid move. Draw a card."})

return jsonify({"status": "valid", "top_card": top_card, "current_suit": current_suit})
return jsonify({"status": "invalid", "message": "Invalid move. Try again."})

if __name__ == "__main__":

Step 6: Finishing Up

1. Update the `script.js` file to add event listeners for playing cards and handling the game flow.

2. Modify the HTML file (`crazy_eights.html`) to display the player’s hand, top card, and suit. Add buttons for playing cards and drawing cards from the deck.

3. Add CSS styles to make the game interface visually appealing and responsive.

4. Run the Flask backend by executing the `` file, and open the game in your web browser by visiting ``.

Please note that this is a basic implementation of the Crazy Eights game, and you can further enhance it by adding features like AI players, game scoring, and multiplayer support. Happy coding and have fun with your Crazy Eights game!

Leave a comment