Creating a Python Rock, Paper, Scissors Game with Fun AI Opponents: Build Your Own Classic Game with a Twist!

Are You Ready to Challenge an AI? Let’s Play Rock, Paper, Scissors! ✊✋✌️

Ah, the classic game of Rock, Paper, Scissors—everyone’s favorite childhood game! While it’s simple, there’s always that thrill when your hand wins against your opponent’s. But what if we took this game and made it a little more interesting? Say, by adding AI opponents that use random strategies to keep you on your toes! 🎮

In this tutorial, we’ll show you how to build your very own Python Rock, Paper, Scissors game with a fun AI. Not only will you create the basic game mechanics, but we’ll also add a little twist: different AI strategies to make the game more exciting. Whether you’re playing against the computer, testing out different AI levels, or trying to outsmart the bot, this game will be a fun project that teaches you Python and AI basics at the same time.

So, let’s dive in and code up a Python Rock, Paper, Scissors game that you’ll actually want to play!


Step 1: Setting Up the Game

First things first, let’s get the basic setup. You’ll need Python installed on your machine (Python 3.x is recommended). Open your favorite IDE (PyCharm, VS Code, or even Jupyter) and create a new Python file. You can call it rock_paper_scissors.py.

We’ll start by defining the basic elements of the game, such as the player’s choices (Rock, Paper, Scissors), and the AI’s moves.

import random

def player_choice():
    """Get the player's choice."""
    choice = input("Enter Rock, Paper, or Scissors: ").lower()
    while choice not in ['rock', 'paper', 'scissors']:
        print("Invalid input! Please try again.")
        choice = input("Enter Rock, Paper, or Scissors: ").lower()
    return choice

def ai_choice():
    """Generate a random choice for the AI."""
    return random.choice(['rock', 'paper', 'scissors'])

def determine_winner(player, ai):
    """Determine the winner between player and AI."""
    if player == ai:
        return "It's a tie!"
    elif (player == 'rock' and ai == 'scissors') or \
         (player == 'paper' and ai == 'rock') or \
         (player == 'scissors' and ai == 'paper'):
        return "You win!"
    else:
        return "AI wins!"

Here, the player_choice() function will ask the user to input their choice, the ai_choice() function generates a random choice for the AI, and the determine_winner() function compares both choices and determines the winner.


Step 2: Introducing the AI Strategies

Now, let’s add some fun twists to the AI by giving it different strategies. We’ll create a “predictive AI” that tries to “predict” your next move based on your previous choices. Or, we could make the AI use a “random strategy”, just like the one we’ve already set up.

Strategy 1: Random AI

This is the simple AI we’ve already implemented. It picks Rock, Paper, or Scissors at random each time.

def ai_random():
    return random.choice(['rock', 'paper', 'scissors'])

Strategy 2: Predictive AI

Here, we’ll make the AI track your previous move and predict your next one based on a simple assumption that you might repeat your last choice. This makes the AI a little more challenging!

def ai_predictive(player_history):
    if len(player_history) == 0:
        return random.choice(['rock', 'paper', 'scissors'])
    else:
        last_move = player_history[-1]
        if last_move == 'rock':
            return 'paper'  # AI counters rock with paper
        elif last_move == 'paper':
            return 'scissors'  # AI counters paper with scissors
        else:
            return 'rock'  # AI counters scissors with rock

Strategy 3: Aggressive AI

This AI tries to “beat” your previous choice every time. It looks at your last move and counters it. For example, if you played Rock last, it will choose Paper to beat you.

def ai_aggressive(player_history):
    if len(player_history) == 0:
        return random.choice(['rock', 'paper', 'scissors'])
    else:
        last_move = player_history[-1]
        if last_move == 'rock':
            return 'paper'  # AI counters rock with paper
        elif last_move == 'paper':
            return 'scissors'  # AI counters paper with scissors
        else:
            return 'rock'  # AI counters scissors with rock

Step 3: Putting It All Together

Now let’s add some code to bring everything together! We’ll allow the player to choose which AI they want to face, and play multiple rounds with the ability to track the score.

def play_game():
    print("Welcome to Python Rock, Paper, Scissors!")
    player_history = []
    ai_level = input("Choose AI level (1 = Random, 2 = Predictive, 3 = Aggressive): ")

    if ai_level == '1':
        ai = ai_random
    elif ai_level == '2':
        ai = ai_predictive
    else:
        ai = ai_aggressive

    score = {'player': 0, 'ai': 0, 'ties': 0}

    while True:
        player = player_choice()
        ai_move = ai(player_history)
        print(f"AI chose: {ai_move}")
        
        result = determine_winner(player, ai_move)
        print(result)

        if "win" in result:
            score['player'] += 1
        elif "AI wins" in result:
            score['ai'] += 1
        else:
            score['ties'] += 1
        
        print(f"Score - Player: {score['player']} | AI: {score['ai']} | Ties: {score['ties']}")
        
        player_history.append(player)
        
        play_again = input("Do you want to play again? (y/n): ").lower()
        if play_again != 'y':
            print("Thanks for playing!")
            break

This function handles the gameplay loop, where the player chooses their move, the AI picks its move, and the winner is determined. The score is updated after each round, and the player can choose to play again.


Step 4: Enhancing the Game (Optional)

If you want to make the game even more interesting, consider adding:

  • Graphical interface using pygame for a more interactive experience.
  • Difficulty levels, where the AI gets smarter as you win more rounds.
  • A leaderboard, where players can compete for the highest score across multiple rounds.

Conclusion

Congratulations! You’ve just built a Python Rock, Paper, Scissors game with a fun, unpredictable AI opponent! 🎉 Whether you face off against a random AI, a predictive AI, or a more aggressive AI, you can keep the game fresh and challenging every time you play. So, what are you waiting for? Go ahead, challenge your friends, and let’s see who’s the real champion of Rock, Paper, Scissors!


If you had fun building this game, let me know how you’ve personalized it. Have any creative ideas for new AI strategies or features? Drop a comment below or tweet me @funwithai!

Leave a Comment