Welcome, aspiring web developers and coding enthusiasts! Have you ever wanted to build something interactive on the web, perhaps a simple game, but felt overwhelmed by complex frameworks? Well, you’re in luck! Today, we’re going to dive into the exciting world of Django and create a fun, classic “Guess the Number” game.
Django is a powerful and popular web framework for Python.
– Web Framework: Think of a web framework as a toolkit that provides all the essential tools and structures you need to build a website or web application quickly and efficiently, without starting entirely from scratch.
Django helps you build robust web applications with less code, making it perfect for both beginners and experienced developers. While it’s often used for complex sites, its simplicity and clear structure make it surprisingly great for fun, experimental projects like a game!
By the end of this guide, you’ll have a basic understanding of how Django works and a working “Guess the Number” game you can play right in your browser. Let’s get started!
What We’ll Build: “Guess the Number”
Our game will be straightforward:
* The computer will randomly pick a secret number between 1 and 100.
* You, the player, will guess a number.
* The game will tell you if your guess is “too high,” “too low,” or “correct.”
* It will also keep track of how many guesses you’ve made.
This game will introduce you to key Django concepts like views, URLs, and templates, along with a touch of Python logic.
Prerequisites: Getting Ready
Before we jump into Django, make sure you have these essentials in place:
- Python: You should have Python installed on your computer (version 3.6 or higher is recommended). If not, head over to python.org to download and install it.
- Basic Python Knowledge: Familiarity with Python basics like variables, functions, and conditional statements (
if/else) will be very helpful. pip: This is Python’s package installer, usually included with Python installations. We’ll use it to install Django.
Step 1: Setting Up Your Django Project
It’s good practice to set up a virtual environment for each Django project.
- Virtual Environment: Imagine a separate, isolated space on your computer where your project’s Python packages live. This prevents conflicts between different projects that might need different versions of the same package.
Let’s open your terminal or command prompt and get started:
-
Create a Project Folder:
First, create a folder for your game project and navigate into it.bash
mkdir django_game
cd django_game -
Create and Activate a Virtual Environment:
bash
python -m venv venv- On Windows:
bash
venv\Scripts\activate - On macOS/Linux:
bash
source venv/bin/activate
You’ll see(venv)appearing at the beginning of your terminal prompt, indicating that your virtual environment is active.
- On Windows:
-
Install Django:
Now that your virtual environment is active, install Django usingpip.bash
pip install django -
Start a New Django Project:
A Django project is a collection of settings and applications that together make a website.bash
django-admin startproject guess_the_number_project .
–guess_the_number_project: This is the name of your project.
–.: This tells Django to create the project files in the current directory (yourdjango_gamefolder), rather than creating another nested folder. -
Create a Django App:
Within your project, you typically create one or more “apps.” An app is a self-contained module that does one specific thing, like handling users, blogs, or, in our case, the game itself. This keeps your code organized.bash
python manage.py startapp game
This creates a new folder namedgamewith several files inside. -
Register Your App:
Django needs to know about the new app you’ve created. Open theguess_the_number_project/settings.pyfile and add'game'to theINSTALLED_APPSlist.“`python
guess_the_number_project/settings.py
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘game’, # Add your new app here
]
“` -
Run Migrations (Optional but Good Practice):
Django uses migrations to set up and update your database schema (the structure of your database). Even though our simple game won’t use a database for its core logic, it’s good practice to run migrations after creating a project.bash
python manage.py migrate
Step 2: Defining URLs
URLs are how users access different parts of your website. We need to tell Django which URL patterns should trigger which parts of our game logic.
-
Project-Level
urls.py:
First, openguess_the_number_project/urls.pyand tell Django to look for URLs defined within ourgameapp.“`python
guess_the_number_project/urls.py
from django.contrib import admin
from django.urls import path, include # Import includeurlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘game/’, include(‘game.urls’)), # Include game app URLs
]
``path(‘game/’, include(‘game.urls’))
Here,means that any URL starting with/game/will be handed over to thegameapp'surls.py` file. -
App-Level
urls.py:
Now, inside yourgameapp folder, create a new file namedurls.py. This file will define the specific URL patterns for our game.“`python
game/urls.py
from django.urls import path
from . import viewsurlpatterns = [
path(”, views.start_game, name=’start_game’),
path(‘play/’, views.play_game, name=’play_game’),
]
``path(”, views.start_game, name=’start_game’)
-: When someone visits/game/(because of theinclude(‘game.urls’)above), this will call thestart_gamefunction ingame/views.py.path(‘play/’, views.play_game, name=’play_game’)
-: When someone visits/game/play/, this will call theplay_gamefunction ingame/views.py`.
Step 3: Crafting the Game Logic (Views)
Django “views” are Python functions that receive a web request, process it, and return a web response (like an HTML page). Our game logic will live here.
Open game/views.py and replace its content with the following:
from django.shortcuts import render, redirect
import random
def start_game(request):
"""
Initializes a new game: generates a secret number and resets guess count.
"""
request.session['secret_number'] = random.randint(1, 100)
request.session['guesses'] = 0
request.session['feedback'] = "I'm thinking of a number between 1 and 100. Can you guess it?"
return redirect('play_game') # Redirect to the play page
def play_game(request):
"""
Handles user guesses and provides feedback.
"""
secret_number = request.session.get('secret_number')
guesses = request.session.get('guesses')
feedback = request.session.get('feedback')
if secret_number is None or guesses is None:
# If session data is missing, start a new game
return redirect('start_game')
message = feedback
guess_made = False
if request.method == 'POST':
# --- Supplementary Explanation: HTTP POST Request ---
# HTTP POST Request: Used when a web browser sends data to the server,
# typically from a form submission. It's used here to send the user's guess.
try:
user_guess = int(request.POST.get('guess'))
guesses += 1
request.session['guesses'] = guesses
guess_made = True
if user_guess < secret_number:
message = "Too low! Try again."
elif user_guess > secret_number:
message = "Too high! Try again."
else:
message = f"Congratulations! You guessed the number {secret_number} in {guesses} guesses!"
# Game over, clear session data or offer to restart
request.session['secret_number'] = None # Clear secret number
request.session['guesses'] = None # Clear guesses
request.session['feedback'] = message + " Click 'Restart Game' to play again."
except (ValueError, TypeError):
message = "Invalid input. Please enter a whole number."
request.session['feedback'] = message # Update feedback for next rendering
# After POST, redirect to the same page to prevent re-submission on refresh
# This is a common pattern called Post/Redirect/Get (PRG)
return redirect('play_game')
# For GET requests or after POST-redirect, render the game page
context = {
'message': message,
'guesses': guesses,
'game_over': request.session.get('secret_number') is None # True if game is over
}
return render(request, 'game/game.html', context)
start_game: This function is called when a new game begins. It generates a random secret number and initializes the guess count, storing them in the user’s session. It then redirects to theplay_gameview.play_game: This is the main game logic.- It retrieves the secret number, guess count, and feedback message from the session.
- If the request is a
POST(meaning the user submitted a guess), it processes the guess: checks if it’s too high, too low, or correct, updates the guess count, and stores new feedback. - It uses
request.sessionto store temporary data specific to the current user’s interaction with the website, which is perfect for our game state. - Finally, it prepares data (
context) and renders thegame/game.htmltemplate.
Step 4: Designing the User Interface (Templates)
Django “templates” are HTML files with special Django syntax that allow you to display dynamic content from your Python views.
-
Create Template Folders:
Inside yourgameapp folder, create a new folder namedtemplates, and inside that, another folder namedgame. This structure (app_name/templates/app_name/your_template.html) helps Django find your templates and keeps them organized.django_game/
├── guess_the_number_project/
├── game/
│ ├── templates/
│ │ └── game/
│ │ └── game.html <-- This is where our game's HTML will go
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── manage.py
└── venv/ -
Create
game.html:
Now, create a file namedgame.htmlinsidegame/templates/game/and add the following HTML:“`html
<!DOCTYPE html>
Guess the Number!
Guess the Number!
<p class="message">{{ message }}</p> {% if game_over %} <p>What a game! You can restart below.</p> <form action="{% url 'start_game' %}" method="post"> {% csrf_token %} {# Required for all Django forms #} <button type="submit">Restart Game</button> </form> {% else %} <form action="{% url 'play_game' %}" method="post"> {% csrf_token %} {# Required for all Django forms #} <input type="number" name="guess" min="1" max="100" placeholder="Enter your guess" required autofocus> <button type="submit">Guess</button> </form> <p class="guesses">Guesses: {{ guesses }}</p> {% endif %} </div>
``{{ message }}
* **and{{ guesses }}:** These are Django template tags that display themessageandguessesvariables passed from ourplay_gameview function via thecontextdictionary.{% if game_over %}
* **and{% else %}:** These are Django template tags for conditional logic, allowing us to display different content based on whether the game is over or not.
* **