How to Build a Guess The Number Game Web Application

Introduction : 

Hey Fellow coders , Today we will be having fun and we will learn a new thing . So, In today’s tutorial we are going to learn about How we can build a Guess the number Game web application . we will be doing it in very easy and simple ways so that it will be easy for us to understand .

This application will have to thing which will ensure that the game will run perfectly fine one will be the backend which will handle the game logic and the other one will be frontend to provide the user interface. We’ll use Flask for the backend and HTML, CSS, and JavaScript for the frontend.

Flask :

Before we will proceed  on doing the program we should know something about flask so . Flask is a microframework, which means it’s designed to be simple and easy to extend. Unlike some other web frameworks, Flask provides the basics for web development and allows you to add additional functionality as needed.

Now , Lets begin with the code

Step 1 :  Setting Up the Backend with Flask 

1.Importing the necessary modules :

In this step we will import the necessary modules that will be used to build this game . The necessary modules are listed below with there functionality and work , Those modules are :

  • Flask: This is the main Flask class we use to create our web application.
  • render_template: This function is used to render HTML templates.
  • request: This module handles incoming requests from the client.
  • jsonify: This function converts Python dictionaries into JSON responses.
  • session: This module allows you to store information across different requests.
  • random: This module is used to generate random numbers.
from flask import Flask, render_template, request, jsonify, session
import random

2.Creating the Flask App: 

After importing the necessary modules we need to create the flask app and give our guess the number app a name . And we will also give a security key to our app which will be required to use sessions securely . To do all of this we just need to write a simple lines in our program that are

app = Flask(__name__)
app.secret_key = 'supersecretkey'

Here ,

  • app = Flask(__name__)  : This line creates a new Flask web application .
  •  app.secret_key = ‘supersecretkey’: This line sets a secret key for the application. This is required to use sessions securely.

3.Defining the Homepage Route:

After all of the above steps and creating the app now we need to set the route of the pplication through which we will be able to access it , For that we need to write some lines in our code and all of the function are also described below .

@app.route('/')
def index():
    session['number'] = random.randint(1, 100)  # Generate a random number
    return render_template('index.html')

Here ,

  • @app.route(‘/’) : This decorator defines the route for the homepage. When a user visits the root URL (/), the index function is called.
  • session[‘number’] = random.randint(1, 100) : This line generates a random number between 1 and 100 and stores it in the session. The session allows us to keep this number across multiple requests from the same user.
  • return render_template(‘index.html’) : This line renders the index.html template and sends it to the user.

4.Defining the Guess Route:

After setting the home page route we need to define the guess route which will be used to guess the number . To do this we need to write Some lines of code .

@app.route('/guess', methods=['POST'])
def guess():
    user_guess = int(request.form['guess'])  # Get the user's guess
    number = session['number']  # Retrieve the stored number

    if user_guess < number:
        result = 'too low'
    elif user_guess > number:
        result = 'too high'
    else:
        result = 'correct'

    return jsonify(result=result)

Here ,

  • @app.route(‘/guess’, methods=[‘POST’]) : This decorator defines a new route for handling guesses. It only accepts POST requests.
  • user_guess = int(request.form[‘guess’]) : This line gets the user’s guess from the form data in the POST request and converts it to an integer.
  • number = session[‘number’] : This line retrieves the stored random number from the session.
  • The if statement checks if the user’s guess is too low, too high, or correct and sets the result accordingly.
  • return jsonify(result=result) : This line converts the result into a JSON response and sends it back to the client.

5.Running the Application:

Now we have done all of the game logic part and now we will run our program for that we will wrte a line in our program that  is

if __name__ == '__main__':
    app.run(debug=True)

Here ,

  •  if __name__ == ‘__main__’: : This condition ensures that the Flask app runs only if this script is executed directly (not imported as a module).
  •  app.run(debug=True) : This line starts the Flask web server in debug mode. Debug mode provides helpful error messages and automatically restarts the server when you make changes to the code.

Now we are done with the Back end part and now we will proceed to the front end part which will provide the user interface.

Full code for the Backend Part :

from flask import Flask, render_template, request, jsonify, session
import random

app = Flask(__name__)
app.secret_key = 'supersecretkey'  # Necessary for using sessions

@app.route('/')
def index():
    session['number'] = random.randint(1, 100)  # Generate a random number
    return render_template('index.html')

@app.route('/guess', methods=['POST'])
def guess():
    user_guess = int(request.form['guess'])  # Get the user's guess
    number = session['number']  # Retrieve the stored number

    if user_guess < number:
        result = 'too low'
    elif user_guess > number:
        result = 'too high'
    else:
        result = 'correct'

    return jsonify(result=result)  # Send the result back to the client

if __name__ == '__main__':
    app.run(debug=True)

 

Step 2 : Creating the Frontend with HTML , CSS, and JavaScript : 

1.Create the HTML File

Create a folder named  ‘ templates ‘ in the same directory as ‘ app.py ‘ . Inside the ‘ templates ‘ folder, create a file named ‘ index.html ‘ . After creating the fine we will proceed to write the code and add the code to it .

2. Document Type Declaration :

<!DOCTYPE html>

This declaration defines the document as an HTML5 document. It tells the browser that this is an HTML file and helps it render the content correctly.

3. HTML Tag : 

<html lang="en">
  • <html> : The root element of the HTML document. All other elements are nested inside this tag.
  • lang=“en” : Specifies the language of the document as English. This helps search engines and browsers understand the language of the content.

4. Head Section : 

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Guess the Number</title>
    <style>
        /* CSS styles will go here */
    </style>
</head>
  • <head> : Contains meta-information about the document, such as its title and character set.
  • <metacharset=“UTF-8”> : Specifies the character encoding for the document, ensuring that characters are displayed correctly.
  • <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> : Ensures the webpage is responsive, meaning it adjusts its layout to look good on different devices (like phones, tablets, and desktops).
  • <title>Guess the Number</title> : Sets the title of the webpage, which appears in the browser tab.
  • <style>: Contains CSS styles to define the appearance of elements on the page. These styles will be added within this tag.

In this head section we will use css for the interface for that we will have to write the css code where we need to define the body style , container style , input style , button style and the result .

For this project , I am selecting the things of my own you can enter the specification as you like

body {
    font-family: Arial, sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
}

.container {
    text-align: center;
}

input {
    padding: 10px;
    font-size: 16px;
}

button {
    padding: 10px 20px;
    font-size: 16px;
}

.result {
    margin-top: 20px;
    font-size: 18px;
    font-weight: bold;
}

4. Body Section : 

<body>
    <div class="container">
        <h1>Guess the Number</h1>
        <p>Guess a number between 1 and 100</p>
        <input type="number" id="guess" min="1" max="100">
        <button onclick="makeGuess()">Guess</button>
        <div class="result" id="result"></div>
    </div>
    <script>
        /* JavaScript code will go here */
    </script>
</body>
</html>
  • <body>: Contains the main content of the HTML document. This is what will be displayed on the webpage.
  • <div class=“container”>: A container element that groups related content together and allows for styling with CSS. Here, it wraps the entire game interface.
  • <h1>: Defines a top-level heading. It gives a title to the page and usually contains the most important heading.
  • <p>: Defines a paragraph of text. It provides instructions to the user.
  • <input type=“number”>: Creates an input field where the user can enter a number.
  • id=“guess”: Gives the input field a unique identifier, which allows it to be easily accessed and manipulated with JavaScript.
  • min=“1” max=“100” : Specifies that the input value must be a number between 1 and 100.
  • <button>: Creates a clickable button.
  •  onclick=“makeGuess()” : Specifies that when the button is clicked, the makeGuess JavaScript function should be called.
  • <div class=“result” id=“result”></div> : Creates a division (or section) of the page with a class of “result” and an id of “result”. This is where the result of the guess (too low, too high, or correct) will be displayed.
  • <script>: Contains JavaScript code that will run on the page. The code will be added within this tag and is responsible for the game’s logic, such as handling the user’s guess and updating the result.

Now , We will write the JavaScript code that will run on the page . It will ensure the Function Definition , Get User Guess , Send Guess to Server , Handle Server Response .

function makeGuess() {
    const guess = document.getElementById('guess').value;
    fetch('/guess', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: `guess=${guess}`
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('result').innerText = `Your guess is ${data.result}`;
    });
}

Now , We have also completed the frontend part which will ensure the user interface and now we just need to Run the application .

Full code for the Frontend Part :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Guess the Number</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }
        .container {
            text-align: center;
        }
        input {
            padding: 10px;
            font-size: 16px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
        }
        .result {
            margin-top: 20px;
            font-size: 18px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Guess the Number</h1>
        <p>Guess a number between 1 and 100</p>
        <input type="number" id="guess" min="1" max="100">
        <button onclick="makeGuess()">Guess</button>
        <div class="result" id="result"></div>
    </div>
    <script>
        function makeGuess() {
            const guess = document.getElementById('guess').value;
            fetch('/guess', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `guess=${guess}`
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('result').innerText = `Your guess is ${data.result}`;
            });
        }
    </script>
</body>
</html>

 

Step 3 : Run the Application : 

1. Ensure You Have Flask Installed 

First, make sure you have Flask installed in your Python environment. If you don’t have it installed, you can install it using pip .

2. Save Your Flask Application Code

Make sure you have saved your Flask application code into a Python file, for example,  ‘ app.py ‘ .

3. Save Your HTML File

Ensure your ‘ index.html ‘ file is saved in a folder named ‘ templets ‘ within the same directory as ‘ app.py ‘ . Your project structure should look like this:

project-folder/
    app.py
    templates/
        index.html

4. Run Your Flask Application 

Open your terminal (or command prompt) and navigate to the directory where your app.py file is located. Then, run the following command :

python app.py

If your Flask application is set up correctly, you should see output similar to the following:

* Serving Flask app "app" (lazy loading)
* Environment: production
  WARNING: This is a development server. Do not use it in a production deployment.
  Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789

This output indicates that your Flask server is running on http://127.0.0.1:5000/.

5. Open the Application in Your Web Browser 

Open your web browser and navigate to http://127.0.0.1:5000/. You should see your “Guess the Number” game interface.

Hope you would have been learned that how we could make this game in easy process hope you all liked it.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top