Coding Assignment

For my coding assignment, I’ve created an Akinator like guessing game in Python, where the computer tries to figure out the character the user is thinking of. The program I created uses
AI to generate simple yes/no questions, and the user responds until the AI makes a guess.

Below is the flowchart I made for my program:

Flowchart

Image URL (clearer version): https://i.imgur.com/ddYnl0R.png

Source Code: https://replit.com/@michaelhu28/Python?v=1

1. Variables

history = ""      # stores past questions and answers
game_over = False # tracks if the game has ended
question_count = 0 # counts number of questions asked

This is part of the variables I’ve defined to keep track of the game’s progress. The history is a. string which stores a log of the entire conversation. game_over is a boolean (meaning can be assigned True of False) that stores the status of the game. And question_count keeps a total of how many questions the AI has asked.

2. Functions

def get_user_answer():
  #Gets user input
  while True:
    answer = input("You: ").strip().lower()
    if answer in ["yes", "y","no","n","maybe","m","stop","quit","q"]:
      if answer in ["yes", "y"]:
        return "yes"
      elif answer in ["no", "n"]:
        return "no"
      elif answer in ["maybe", "m"]:
        return "maybe"
      elif answer in ["stop", "quit", "q"]:
        return "stop"
      else:
        print("Please answer with yes, no, maybe, or quit.")

This function validates the user’s input. Instead of crashing or accepting a random input, this function keeps asking the user until they provide a valid answer. It also takes into account different forms of input (like “y” and “yes”) into consistent outputs for the AI.

3. Conditional Statements:

if ai_output["type"] == "guess":
    ask = input("Is this correct? (yes/no): ").strip().lower()
    if ask in ["yes", "y"]:
        print("Great! I guessed it right.")
        print(f"It took me {question_count} questions to guess it.")
        game_over = True
    else:
        print("Sorry, I couldn't guess it right. Let's try again.")
        history += f"\nAI: {ai_output}\nYou: no (incorrect guess)"
        question_count += 1

This portion of the code checks if the AI is making a guess or asking a question. This is made possible by prompting the AI to respond in a JSON format. If the type of response is a guess and is correct, it ends the game with a success message.

Example response format:

{ "type": "question", "message": "Is your person real, not fictional?", 

"confidence": 0.01, 

"state": { "q_count": 1, "top_candidates": ["Barack Obama","Harry Potter","Elvis Presley"], 

"notes": "Starting with real vs fictional split for major info gain." } 
}

Prompt Engineering:

I have explored with the prompt and the different models to let the AI guess correctly using the least amount of questions. (left is the new prompt, right is the old one)

Pros and Cons of the New Prompt

ProsCons
Improves the accuracy of the response.A longer prompt would result in longer response times.
Specifies the structure of the response, making it readable by the program.Generating structured JSON with all that information can increase the token load.

Result:

When thinking of the same character(Mr. Beast), by using the new prompt, the program is able to guess it correctly using less amount of questions (15 questions – 22 questions). The new prompt also shows a confidence score when asking the question.

What I Learned

  • How to use flowcharting to plan my logic before coding.
  • How to connect Python with the OpenAI API and structure prompts.
  • How to use loops, conditionals, and functions to make code readable and organized.

Future Improvements

  • Add a confidence score so the AI can explain how sure it is about a guess. (Added)
  • Save the transcript of each game to a file so I can analyze failures.
  • Build a version with GUI

Update (Sep. 28):

After receiving feedback that my original setup required a paid API and wasn’t directly runnable, I updated my project to use the Google Gemini API. This change allows anyone to clone the project and run the program for free without extra setup. To make the project accessible over time, I also recorded a short walk-through video demonstrating how the game works in action. This way, even if the API service changes or keys expire, readers can still clearly see the program’s functionality.

Thanks for Reading my First Blog Post!

Comments

3 Responses to “Coding Assignment”

  1. mcrompton Avatar
    mcrompton

    This is outstanding work, Michael! Leveraging AI within your code takes the assignment to the next level and you’ve managed to explain your code in your post in a way that I think most readers will understand. My biggest issue at the moment is that I can’t actually run your code! It looks like you’ve set it up in a way that requires a paid account for a service that I don’t subscribe to. Your options are to either move it to another platform that allows me access to it, or record a walk-through video of your code that you can embed in your post. While the video doesn’t let the user play with the program, considering that your API key “will expire soon”, this might be a better option. The post is intended to be readable over the course of a longer period of time. Please address this issue and resubmit.

    1. michaelh Avatar
      michaelh

      Thank you so much for your feedback, Mr. Compton! I completely understand your concern about the code not being directly runnable. To address this, I’ve updated the project to use the Google Gemini API, which provides a free tier that users are able to use free of charge. I have provided a free key for users to use directly within the source code. I’ve also recorded a short walk-through video demonstrating how the program works so that the functionality is still accessible over time, even if API keys expire. Thanks again for your feedback.

      1. mcrompton Avatar
        mcrompton

        This helps, Michael. The spoken walk through also helps me to understand your thinking and skill at programming better. Just so that we’re clear, part of the issue that I had with the original submission related to the API key, but the other part is that I need to pay for a Replit account to be able to remix your project. So, even with the chaged API key, I still can’t run the code. But you have completed the assignment and demonstrated a high level of skill!

Leave a Reply to michaelh Cancel reply

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