Python >> Tutoriel Python >  >> Python

Comment créer un jeu d'aventure textuel en Python ?

Bonjour, là camarade apprenant! Aujourd'hui, nous allons créer un jeu d'aventure textuel amusant à partir de zéro. Tout d'abord, comprenons ce qu'est un jeu basé sur du texte, puis nous implémenterons la même chose dans le langage de programmation Python.

Qu'est-ce qu'un jeu textuel ?

Un jeu basé sur du texte est un jeu simple d'entrée-sortie entièrement basé sur du texte. Dans ce type de jeu, les utilisateurs ont des options pour gérer diverses situations à mesure qu'elles arrivent avec des choix pris par l'utilisateur sous la forme d'entrées.

Le scénario de notre jeu

La figure ci-dessous affiche la petite histoire que nous allons construire en python dans ce tutoriel. Vous pouvez développer ou modifier l'histoire selon vos propres préférences.

Implémentation du jeu d'aventure textuel en Python

Commençons d'abord l'histoire en imprimant la scène initiale et comment l'histoire avance. Cela peut être fait en utilisant simplement la fonction d'impression. Pour le rendre plus amusant, nous pouvons également ajouter des émoticônes et des émoticônes !

print("""WELCOME TO THE ADVENTURE GAME!
    Let's start the action! ☆-🎬-☆
    
    Lily wakes up in her bedroom in the middle of the night. She heard a loud BAN outside the house.
    Now she has two choices she can either stay in the room or check what the sound might be about.
    
    Type your choice: Stay or Evaluate?
""")

Bon déroulement! Maintenant, nous avons la scène en place et cela s'avère également intéressant et regardez ici votre premier choix ! Prenons maintenant l'entrée de l'utilisateur et entrons dans les instructions conditionnelles pour chaque choix effectué.

Nous devons nous assurer que notre jeu a des réponses à tous les types d'entrées faites par l'utilisateur et qu'il n'entraîne pas d'erreur dans les choix effectués.

def scene1():
    import time
    print("""WELCOME TO THE ADVENTURE GAME!
        Let's start the action! ☆-🎬-☆

        Lily wakes up in her bedroom in the middle of the night. She heard a loud BAN outside the house.
        Now she has two choices she can either stay in the room or check what the sound might be about.

        Type your choice: Stay or Evaluate?
    """)

    c1 = input()
    time.sleep(2)
    ans = 'incorrect'
    while(ans=='incorrect'):
        if(c1.upper()=="STAY"):
            print("\nLily decides to stay in the room and ends up staying inside forever as noone seems to come to help her.")
            ans = 'correct'
        elif(c1.upper()=="EVALUATE"):
            print("Lily exits the room silently and reaches the main hall.")
            ans='correct'
            scene2()
        else:
            print("ENTER THE CORRECT CHOICE! Stay or Evaluate?")
            c1 = input()

Nous prenons le premier choix input puis nous créerons une variable qui confirmera si notre réponse est correcte ou incorrecte. Ensuite, nous créons la boucle conditionnelle et les instructions if-else. Le jeu continue de demander le choix encore et encore jusqu'à ce que la réponse donnée soit valide.

Maintenant que la première scène est terminée, nous pouvons passer à la scène suivante et construire tout le jeu de la même manière. Ci-dessous, nous avons le code de la deuxième scène.

def scene2():
    import time
    print("""
            In the main hall, she finds a strange but cute teddy bear on the floor. 
            She wanted to pick the teddy up. 
            But should she? It doesn't belong to her. (•˳̂•̆)

            Type your choice: Pick or Ignore?

            """)
    time.sleep(2)
    c1 = input()
    ans = 'incorrect'
    while(ans=='incorrect'):
        if(c1.upper()=="PICK"):
            print("""\nThe moment Lily picked up the the teddy bear. The Teddy bear starts TALKING!The bear tells Lily that she is in grave danger as there is a monster in the house.And the monster has captured her PARENTS as well!But he hugged her and told her not to get scared as he knows how to beat the moster!""")
            time.sleep(2)
            print("""\nThe bear handed lily a magical potion which can weaken the moster and make him run away!He handed her the potion and then DISAPPEARED!Lily moved forward.""")
            ans = 'correct'
            pick="True"
        elif(c1.upper()=='IGNORE'):
            print("""\nLily decided not to pick up the bear and walked forward.""")
            ans='correct'
            pick="False"
        else:
            print("Wrong Input! Enter pick or ignore?")
            c1=input()
    time.sleep(2)
    scene3(pick)

Le code de la troisième scène est le suivant. Maintenant, le résultat de la troisième scène dépend du choix fait dans la scène 2, à savoir si l'ours en peluche a été choisi ou ignoré et si le protagoniste principal a reçu la potion ou non.

def scene3(pick_value):
    import time
    print("""\n\nAfter walking for a while, Lily saw the MONSTOR in front of her!
    It had red eyes and evil looks. She got very scared! """)
    time.sleep(2)
    if(pick_value=="True"):
        time.sleep(2)
        print("""But then she remembered! She had the magic portion and she threw it on the moster!
              Well she had nothing to lose!""")
        time.sleep(2)
        print("\n The monster SCREAMED in pain but he managed to make a portal and pushed Lily to a new world!")
    elif(pick_value=="False"):
        print("The monster attacked Lily and hurt her! She was then thrown to the new world by the monster!")

Nous terminerons le chapitre 1 de l'histoire après trois scènes. Vous pouvez développer ou même modifier toute l'histoire selon vos préférences.

Pour commencer l'histoire, démarrez simplement la scène 1 de l'histoire.

scene1()
print("\n\n")
print("=================================END OF CHAPTER 1=================================")

Le résultat de l'histoire ci-dessus est illustré ci-dessous. Et c'est plutôt génial !

Conclusion

Vous savez maintenant comment créer vous-même des jeux d'aventure textuels simples et faciles ! Vous pouvez également essayer votre propre histoire unique! Bon codage ! Merci d'avoir lu !