DEV Community

Cover image for Generating Python Game Code with Lyzr and Streamlit
harshit-lyzr
harshit-lyzr

Posted on

Generating Python Game Code with Lyzr and Streamlit

Have you ever dreamt of creating your own game but lacked the coding experience? Well, fret no more! Today, we'll delve into the world of Lyzr Game Generator, a user-friendly web app that leverages the power of OpenAI to bring your game ideas to life.
This blog post will not only introduce you to Lyzr but also provide a step-by-step walkthrough of its code, giving you a peek behind the scenes. So, buckle up and get ready to unleash your inner game developer!

Here's a quick rundown of how it works:
Input Your Game Idea: Simply type in the name of your game in the designated text box. Be as descriptive as possible to give the AI a clear understanding of your vision.
Lyzr Takes the Wheel: Lyzr's AI engine gets to work! It utilizes OpenAI's capabilities to craft Python code that translates your game concept into reality.
Quality Assurance Checks: Lyzr doesn't stop at just code generation. It employs the AI to act as a QA engineer, scrutinizing the code for errors and ensuring its functionality.
The Final Product: Lyzr presents you with the generated Python code, along with basic gameplay instructions, allowing you to visualize your game concept coming to life.

Building Game Ganerator Team with Lyzr
The Lyzr Game Generator Application demonstrates the potential of combining Lyzr ,Streamlit and OpenAI for creating interactive Team.
Let's break down the key components of our implementation:
Import Libraries:
The code begins by importing necessary libraries:
streamlit: for building the web app interface.
lyzr_automata libraries: for defining AI models, agents, and tasks.
dotenv: for loading environment variables (API key).

pip install lyzr_automata python-dotenv streamlit
Enter fullscreen mode Exit fullscreen mode
import streamlit as st
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent,Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from dotenv import load_dotenv
import os
Enter fullscreen mode Exit fullscreen mode

Load API Key:
API key for OpenAI is loaded from a .env file using load_dotenv and os.getenv.

load_dotenv()
api = os.getenv("OPENAI_API_KEY")
Enter fullscreen mode Exit fullscreen mode

User Input:
st.text_input creates a text box for users to enter their math problem.

query=st.text_input("Enter your Maths Problem: ")
Enter fullscreen mode Exit fullscreen mode

Define OpenAI Model:
An OpenAIModel object is created using the loaded API key.
Model parameters like "gpt-4-turbo-preview" (replace with your desired model), temperature, and maximum output length are specified.

open_ai_text_completion_model = OpenAIModel(
    api_key=api,
    parameters={
        "model": "gpt-4-turbo-preview",
        "temperature": 0.2,
        "max_tokens": 1500,
    },
)
Enter fullscreen mode Exit fullscreen mode

Define game_generator Function:
Agents: These represent different personas involved in the game creation process.
engineer_agent: Represents a Senior Software Engineer who writes the code.
qa_agent: Represents a Software Quality Control Engineer who checks for errors.
senior_qa_engineer: Represents a Senior QA Engineer who ensures code completeness.

engineer_agent = Agent(
        role="Senior Software Engineer",
        prompt_persona="""You are a Senior Software Engineer at a leading tech think tank.
                Your expertise in programming in python. and do your best to
                produce perfect code"""
    )

    qa_agent=Agent(
        role="Software Quality Control Engineer",
        prompt_persona="""You are a software engineer that specializes in checking code
            for errors. You have an eye for detail and a knack for finding
                hidden bugs.
            You check for missing imports, variable declarations, mismatched
                brackets and syntax errors.
            You also check for security vulnerabilities, and logic errors"""
    )

    senior_qa_engineer=Agent(
        role="Senior Software Quality Control Engineer",
        prompt_persona="""\
                You feel that programmers always do only half the job, so you are
                super dedicate to make high quality code."""
    )
Enter fullscreen mode Exit fullscreen mode

Give Prompts for different Agents and Tasks:

prompt=f"""You will create a game using python, these are the instructions:

            Instructions
            ------------
        {query} game

            Your Final answer must be the full python code, only the python code and simple documentation how to play up to 30 words and nothing else.
            """

    qa_prompt=f"""You are helping create a game using python, these are the instructions:

            Instructions
            ------------
            {query} game

            Using the code you got, check for errors. Check for logic errors,
            syntax errors, missing imports, variable declarations, mismatched brackets,
            and security vulnerabilities.

            Your Final answer must be the full python code, only the python code and nothing else.
            """

    senior_qa_prompt=f"""\
            You are helping create a game using python, these are the instructions:

            Instructions
            ------------
            {query} game

            You will look over the code to insure that it is complete and
            does the job that it is supposed to do.

            Your Final answer must be the full python code, only the python code and nothing else.
            """
Enter fullscreen mode Exit fullscreen mode

Tasks: These represent specific actions each agent performs.
code_task: Generates the initial Python code based on the user query.
review_task: Reviews the generated code for errors (QA).
evaluate_task: Evaluates the code for completeness and functionality (Senior QA).

code_task  =  Task(
        name="Code Generation",
        model=open_ai_text_completion_model,
        agent=engineer_agent,
        instructions=prompt,
    )

    review_task=Task(
        name="QA Testing",
        model=open_ai_text_completion_model,
        agent=qa_agent,
        instructions=qa_prompt,
    )

    evaluate_task =Task(
        name="Senior QA Testing",
        model=open_ai_text_completion_model,
        agent=senior_qa_engineer,
        instructions=senior_qa_prompt,
    )
Enter fullscreen mode Exit fullscreen mode

Pipeline: This combines all tasks into a linear workflow.
LinearSyncPipeline: Executes each task in sequence.

output = LinearSyncPipeline(
    name="Game Pipline",
    completion_message="pipeline completed",
    tasks=[
          code_task,
          review_task,
          evaluate_task
    ],
).run()
Enter fullscreen mode Exit fullscreen mode

As we reach the culmination of our journey, we stand in awe of the vast landscapes we've traversed and the limitless possibilities that lie ahead. Through the fusion of Lyzr Automata, Streamlit, and OpenAI, we've unlocked a new frontier of game generation where creativity knows no bounds and innovation knows no limits. Whether you're a seasoned developer or an aspiring creator, the tools at your disposal promise to reshape the way games are conceived, crafted, and experienced.

Try it Now:https://lyzr-game-generator.streamlit.app/
For more information explore the website: Lyzr


Top comments (0)