Level Up Your Web Skills: Creating a Simple “Guess the Number” Game with Django

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:

  1. Create a Project Folder:
    First, create a folder for your game project and navigate into it.

    bash
    mkdir django_game
    cd django_game

  2. 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.
  3. Install Django:
    Now that your virtual environment is active, install Django using pip.

    bash
    pip install django

  4. 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 (your django_game folder), rather than creating another nested folder.

  5. 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 named game with several files inside.

  6. Register Your App:
    Django needs to know about the new app you’ve created. Open the guess_the_number_project/settings.py file and add 'game' to the INSTALLED_APPS list.

    “`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
    ]
    “`

  7. 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.

  1. Project-Level urls.py:
    First, open guess_the_number_project/urls.py and tell Django to look for URLs defined within our game app.

    “`python

    guess_the_number_project/urls.py

    from django.contrib import admin
    from django.urls import path, include # Import include

    urlpatterns = [
    path(‘admin/’, admin.site.urls),
    path(‘game/’, include(‘game.urls’)), # Include game app URLs
    ]
    ``
    Here,
    path(‘game/’, include(‘game.urls’))means that any URL starting with/game/will be handed over to thegameapp'surls.py` file.

  2. App-Level urls.py:
    Now, inside your game app folder, create a new file named urls.py. This file will define the specific URL patterns for our game.

    “`python

    game/urls.py

    from django.urls import path
    from . import views

    urlpatterns = [
    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 the play_game view.
  • 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.session to 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 the game/game.html template.

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.

  1. Create Template Folders:
    Inside your game app folder, create a new folder named templates, and inside that, another folder named game. 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/

  2. Create game.html:
    Now, create a file named game.html inside game/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.
    * **

    :** This creates an HTML form.
    *
    action=”{% url ‘play_game’ %}”: The{% url %}template tag dynamically generates the URL for theplay_gameview, ensuring it's always correct.
    *
    method=”post”: This means the form data will be sent using an HTTP POST request.
    * **
    {% csrf_token %}:** This is a crucial security feature in Django.
    * **CSRF (Cross-Site Request Forgery):** A type of malicious exploit where an attacker tricks a logged-in user into unknowingly submitting a request to a web application. The
    csrf_token` protects your forms from this by ensuring that the request originated from your own website. Always include it in your forms!

Step 5: Running Your Game

You’ve done all the hard work! Now it’s time to see your game in action.

  1. Start the Development Server:
    Make sure your virtual environment is active and you are in the django_game directory (the one containing manage.py).

    bash
    python manage.py runserver

    You should see output similar to this:

    “`
    Watching for file changes with StatReloader
    Performing system checks…

    System check identified no issues (0 silenced).

    You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
    Run ‘python manage.py migrate’ to apply them.
    August 09, 2023 – 14:30:00
    Django version 4.2.4, using settings ‘guess_the_number_project.settings’
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    “`

  2. Open in Browser:
    Open your web browser and navigate to http://127.0.0.1:8000/game/.

    You should see your “Guess the Number!” game. Try guessing numbers, and the game will tell you if you’re too high or too low. Once you guess correctly, you’ll see a congratulatory message and a “Restart Game” button.

What’s Next? Ideas for Improvement

This simple game is just the beginning! Here are some ideas to expand your project and learn more about Django:

  • Add a High Score List: This would involve creating a Django Model (a Python class that represents a table in your database) to store player names and their number of guesses. You’d then learn how to save and retrieve data from a database.
  • Multiple Difficulty Levels: Allow players to choose a range (e.g., 1-10, 1-1000).
  • User Accounts: Use Django’s built-in authentication system to allow users to create accounts, log in, and track their personal best scores.
  • CSS Styling: Improve the look and feel with more advanced CSS or a CSS framework like Bootstrap.
  • Make it a “Hangman” or “Tic-Tac-Toe” Game: Challenge yourself to implement more complex game logic within the Django framework.

Conclusion

Congratulations! You’ve successfully built a basic web-based game using Django. You’ve touched upon setting up a project, defining URLs, writing view logic, and creating HTML templates. Django provides a robust and elegant way to build web applications, and even simple games can be a fantastic way to learn its core concepts. Keep experimenting, keep building, and have fun on your coding journey!


Comments

Leave a Reply