Of course! Let's build a simple, complete, and functional web-based game using Python.
We'll create a classic "Rock, Paper, Scissors" game. This example perfectly demonstrates the core principles of a full-stack application:
- Front-End (Client-Side): HTML, CSS, and JavaScript that the user interacts with in their browser.
- Back-End (Server-Side): A Python server using the Flask framework to handle the game logic.
- API: A simple communication channel between the front-end and back-end.
Project Structure
First, create a folder for your project and set up the following files and folders. This structure is standard for a Flask application.
/python-gaming-app
├── app.py # Our main Python/Flask server
├── templates/
│ └── index.html # The HTML file for our game interface
└── static/
├── style.css # The CSS for styling
└── script.js # The JavaScript for interactivity
Step 1: Install Flask
You'll need the Flask library. Open your terminal or command prompt and run:
pip install Flask
Step 2: The Back-End (Python/Flask)
This is the "brain" of our application. It will decide the computer's move and determine the winner.
File: app.py
import random
from flask import Flask, render_template, jsonify, request
# Initialize the Flask app
app = Flask(__name__)
# A dictionary to keep track of the score
score = {"player": 0, "server": 0, "ties": 0}
@app.route("/")
def index():
"""Renders the main game page."""
# Reset scores when the page is reloaded
score["player"] = 0
score["server"] = 0
score["ties"] = 0
return render_template("index.html")
@app.route("/play", methods=["POST"])
def play():
"""Handles the game logic when a player makes a move."""
# Get the player's choice from the request sent by JavaScript
player_choice = request.json.get("choice")
if not player_choice:
return jsonify({"error": "No choice made"}), 400
choices = ["rock", "paper", "scissors"]
server_choice = random.choice(choices)
# Determine the winner
if player_choice == server_choice:
result = "It's a tie!"
score["ties"] += 1
elif (player_choice == "rock" and server_choice == "scissors") or \
(player_choice == "scissors" and server_choice == "paper") or \
(player_choice == "paper" and server_choice == "rock"):
result = "You win!"
score["player"] += 1
else:
result = "You lose!"
score["server"] += 1
# Return the result and choices as a JSON response
return jsonify({
"result": result,
"player_choice": player_choice,
"server_choice": server_choice,
"score": score
})
if __name__ == "__main__":
# Run the app in debug mode for development
app.run(debug=True)
Step 3: The Front-End (HTML)
This file creates the user interface with buttons and areas to display results.
File: templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Gaming App - Rock, Paper, Scissors</title>
<!-- Link our CSS and JavaScript files -->
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Rock, Paper, Scissors</h1>
<p>Choose your weapon!</p>
<div class="choices">
<button id="rock">Rock ✊</button>
<button id="paper">Paper ✋</button>
<button id="scissors">Scissors ✌️</button>
</div>
<div id="result-display">
<p><strong>Result:</strong> <span id="result-text">Make a move to start...</span></p>
<p>You chose: <span id="player-choice-text">-</span></p>
<p>Server chose: <span id="server-choice-text">-</span></p>
</div>
<div id="score-board">
<h2>Score</h2>
<p>Player: <span id="player-score">0</span></p>
<p>Server: <span id="server-score">0</span></p>
<p>Ties: <span id="tie-score">0</span></p>
</div>
<script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
Step 4: Styling (CSS)
Let's make our game look nice and clean.
File: static/style.css
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f0f2f5;
color: #333;
padding: 20px;
}
h1, h2 {
color: #1a73e8;
}
.choices button {
font-size: 24px;
padding: 15px 30px;
margin: 10px;
cursor: pointer;
border: 2px solid #1a73e8;
border-radius: 8px;
background-color: white;
transition: background-color 0.3s, transform 0.2s;
}
.choices button:hover {
background-color: #e8f0fe;
transform: scale(1.05);
}
#result-display, #score-board {
margin-top: 30px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
background-color: #fff;
display: inline-block;
}
#result-display p, #score-board p {
font-size: 18px;
margin: 8px 0;
}
span {
font-weight: bold;
color: #d93025;
}
#player-score {
color: #1e8e3e;
}
Step 5: Front-End Logic (JavaScript)
This is the glue. It captures the user's click, sends it to our Python server, receives the result, and updates the webpage without needing to reload it.
File: static/script.js
document.addEventListener('DOMContentLoaded', () => {
// Get references to all the buttons and display elements
const rockButton = document.getElementById('rock');
const paperButton = document.getElementById('paper');
const scissorsButton = document.getElementById('scissors');
const resultText = document.getElementById('result-text');
const playerChoiceText = document.getElementById('player-choice-text');
const serverChoiceText = document.getElementById('server-choice-text');
const playerScoreText = document.getElementById('player-score');
const serverScoreText = document.getElementById('server-score');
const tieScoreText = document.getElementById('tie-score');
// Add event listeners to each button
rockButton.addEventListener('click', () => playGame('rock'));
paperButton.addEventListener('click', () => playGame('paper'));
scissorsButton.addEventListener('click', () => playGame('scissors'));
// The main game function
async function playGame(playerChoice) {
// Send the player's choice to the Python server using fetch
const response = await fetch('/play', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ choice: playerChoice }),
});
// Get the result from the server
const data = await response.json();
// Update the web page with the results
resultText.textContent = data.result;
playerChoiceText.textContent = data.player_choice;
serverChoiceText.textContent = data.server_choice;
// Update the score board
playerScoreText.textContent = data.score.player;
serverScoreText.textContent = data.score.server;
tieScoreText.textContent = data.score.ties;
}
});
How to Run the Application
- Make sure all your files are in the correct folders as described in the structure.
- Open your terminal or command prompt.
- Navigate to the root project folder (
/python-gaming-app).
- Run the Python server:
python app.py
- You will see output like this:
* Running on http://127.0.0.1:5000
- Open your web browser and go to
http://127.0.0.1:5000.
You should now see your Rock, Paper, Scissors game! Click the buttons to play against the Python server. The page will update dynamically with the results.