Open In App

Number Guessing Game Using Python Streamlit Library

The game will pick a number randomly from 1 to 100 and the player needs to guess the exact number guessed by calculating the hint. The player will get 7 chances to guess the number and for every wrong guess game will tell you if the number is more or less or you can take a random hint to guess the number like (2+2=?, 3*3=?) to guess the number. In this article, we will create a number-guessing game using the Python Streamlit Library

Number Guessing Game Using Python Streamlit Library

Below, is the explanation by which we can make a number guessing game using Python Streamlit Library:

Install Necessary Library

First, we need to install the streamlit library, for creating the Number Guessing Game so to install the streamlit library use the below command:

pip install streamlit

Writing Python Code

Below, are the step-by-step implementation of the number-guessing game.

Step 1: Import Libraries and Define Functions

Below, code imports the Streamlit library as 'st' and the random module. It defines a function called 'get_secret_number()' that returns a randomly generated integer between 1 and 100.

import streamlit as st
import random


def get_secret_number():
    return random.randint(1, 100)

Step 2: Generate Secret Number and Initialize Game State

In below code the 'initial_state()' function initializes session variables for the game, setting 'input' to 0, generating the secret number, and initializing attempt count and game over status

def initial_state(post_init=False):
    if not post_init:
        st.session_state.input = 0
    st.session_state.number = get_secret_number()
    st.session_state.attempt = 0
    st.session_state.over = False

Step 3: Restarting the Game

In below code 'restart_game()' function resets the game state by calling 'initial_state()' with 'post_init' set to True, then increments the input counter.

def restart_game():
    initial_state(post_init=True)
    st.session_state.input += 1

Step 4: Generating a Hint

In below code 'get_hint(number)' function generates a hint for the player based on the secret number provided, utilizing addition, subtraction, or multiplication operations to create a related calculation.

def get_hint(number):

    operation_list = ["+", "-", "*"]

    operation = random.choice(operation_list)

    if operation == "+":
        op1 = random.randint(1, number-1)
        op2 = number-op1
        return f"{op1}+{op2}=?"

    elif operation == "-":
        op1 = random.randint(number+1, 100)
        op2 = op1-number
        return f"{op1}-{op2}=?"
    else:
        for op1 in range(100, 0, -1):
            for op2 in range(1, 101):
                if op1*op2 == number:
                    return f"{op1}*{op2}=?"

Step 5: Main Function

In below code 'main()' function controls the game's flow, displaying the title and interface, managing user input for guessing numbers and hints, and providing feedback on guesses. It terminates the game when the player exhausts attempts or guesses the correct number

def main():
    st.write(
        """
        # Guess The Number !!
        """
    )
    if 'number' not in st.session_state:
        initial_state()

    st.button('New game', on_click=restart_game)
    placeholder, debug, hint_text = st.empty(), st.empty(), st.empty()
    guess = placeholder.number_input(
        f'Enter your guess from 1 - {100}',
        key=st.session_state.input,
        min_value=0,
        max_value=100,
    )

    col1, _, _, _, col2 = st.columns(5)
    with col1:
        hint = st.button('Hint')

    with col2:
        if not guess:
            st.write(f"Attempt Left : 7")
        if guess:
            st.write(f"Attempt Left : {6-st.session_state.attempt}")

    if hint:
        hint_response = get_hint(st.session_state.number)
        hint_text.info(f'{hint_response}')

    if guess:
        if st.session_state.attempt < 6:
            st.session_state.attempt += 1
            if guess < st.session_state.number:
                debug.warning(f'{guess} is too low!')
            elif guess > st.session_state.number:
                debug.warning(f'{guess} is too high!')
            else:
                debug.success(
                    f'Yay! you guessed it right 🎈'

                )
                st.balloons()
                st.session_state.over = True
                placeholder.empty()
        else:
            debug.error(
                f'Sorry you Lost! The number was {st.session_state.number}'
            )

            st.session_state.over = True
            placeholder.empty()
            hint_text.empty()


if __name__ == '__main__':
    main()

Complete Code Implementation

main.py

import streamlit as st
import random


def get_secret_number():
    return random.randint(1, 100)


def initial_state(post_init=False):
    if not post_init:
        st.session_state.input = 0
    st.session_state.number = get_secret_number()
    st.session_state.attempt = 0
    st.session_state.over = False


def restart_game():
    initial_state(post_init=True)
    st.session_state.input += 1


def get_hint(number):
    operation_list = ["+", "-", "*"]
    operation = random.choice(operation_list)
    if operation == "+":
        op1 = random.randint(1, number-1)
        op2 = number-op1
        return f"{op1}+{op2}=?"
    elif operation == "-":
        op1 = random.randint(number+1, 100)
        op2 = op1-number
        return f"{op1}-{op2}=?"
    else:
        for op1 in range(100, 0, -1):
            for op2 in range(1, 101):
                if op1*op2 == number:
                    return f"{op1}*{op2}=?"


def main():
    st.write(
        """
        # Guess The Number !!
        """
    )

    if 'number' not in st.session_state:
        initial_state()

    st.button('New game', on_click=restart_game)

    placeholder, debug, hint_text = st.empty(), st.empty(), st.empty()

    guess = placeholder.number_input(
        f'Enter your guess from 1 - {100}',
        key=st.session_state.input,
        min_value=0,
        max_value=100,
    )

    col1, _, _, _, col2 = st.columns(5)
    with col1:
        hint = st.button('Hint')

    with col2:
        if not guess:
            st.write(f"Attempt Left : 7")
        if guess:
            st.write(f"Attempt Left : {6-st.session_state.attempt}")

    if hint:
        hint_response = get_hint(st.session_state.number)
        hint_text.info(f'{hint_response}')

    if guess:
        if st.session_state.attempt < 6:
            st.session_state.attempt += 1
            if guess < st.session_state.number:
                debug.warning(f'{guess} is too low!')
            elif guess > st.session_state.number:
                debug.warning(f'{guess} is too high!')
            else:
                debug.success(
                    f'Yay! you guessed it right 🎈'

                )
                st.balloons()
                st.session_state.over = True
                placeholder.empty()
        else:
            debug.error(
                f'Sorry you Lost! The number was {st.session_state.number}'
            )

            st.session_state.over = True
            placeholder.empty()
            hint_text.empty()


if __name__ == '__main__':
    main()

# this code is contibuted by shraman jain

Run the Server

To run the server using the below command

streamlit run "script_name.py"

Output:
Fianl_Game-transformed

Video Demonstration

Article Tags :