Python Forum
Text-Based RPG - After selecting correct decision it also prints others code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Text-Based RPG - After selecting correct decision it also prints others code
#1
Hiya,

First off, apologies for a presumably hilarious error or gap in knowledge!

I, along with two others have been tasked with making a text-based RPG as part of a course we are doing however we've all had roughly 3 hours worth of Python experience and are completely new, we are coding this game on Replit (just due to course preference & ability to collaboratively work etc.)

The issue we are experiencing is that for our game, we have a beginning A & B path, however, when testing I've noticed that when I make a decision, it prints the correct response however it also prints a subsequent line of code from lower down i.e another decision choice. it'd be best to articulate if you were to run it, I'll attach the game's code so far (some 60 odd lines).

if you were to run the code and run through the below the decisions in the following order you'll see what I mean -

A, N
A, Y
B, B, B

As stated above this is probably due to our lack of knowledge around Python and properly segmenting off code.
Please could someone run the below and give it a test and if possible fix it and # what steps were taken so I can feed back to our group or advise me and I can try! (I've attached a flow chart (in pdf) of how we are intending the game to run if that helps with decision order etc.

Many thanks,

KJ

DecisionY = ["Y","y","yes","Yes","YES"]
DecisionN = ["N","n","no","No","NO"]
DecisionA = ["A","a"]
DecisionB = ["B","b"]
DecisionC = ["C","c"]
DecisionD = ["D","d"] #Currently unsure if we will have 4 options at once but its here if needed... delete if not used/applicable
DecisionBee = ["Bee", "bee","BEE"]
#The above decision section has been used to make the code neater by using an array to condense the code and increase error checking and validity and keeps code consistent - change it here it changes throughout the code 

print("Ah, my friend.\nIt's good to see you again. I trust you're doing well.\nListen, I've got a proposition for you - a little business opportunity, if you will. See, there's a certain bank in town that's caught my eye, and a 'lil birdie told me they've got themselves a diamond!I think it's time we paid them a little visit. But watch out, you'll need to find the keycard! You in?\n")

print("*Fades into present-day New Pascani* \n")

print("Royal City Bank \n")

#Need to create a basic introduction to the setting and characters!

Entrance = input("What Entrance do you want to choose? \n A. Main Entrance \n B. Side Entrance \n > ")

if Entrance in DecisionA:  #When user types A - Show Enclosed
  print("\nMain Entrance Selected")
  CamDisable = input(str("\nWould you like to disable the cameras? Y/N \n> "))

  if CamDisable in DecisionY:
    print("\nThe cameras have been disabled \n")
    
  elif CamDisable in DecisionN:
    print("\nYou've been caught on camera during your heist.\nThe police have arrived and are taking you to prison.\nThere's no escaping the consequences of your actions.\n\nYOU HAVE ACHIVED:\nTHE PRISON ENDING!")

elif Entrance in DecisionB:  #When user types B - Show Enclosed
  print("\nSide Entrance Selected")

JanChoice = input("\nYou enter quietly through the side entrance, it looks to be a service door.\nYou hear a shuffling sound ahead and spot a janitor working, glancing around you spot somewhere you could hide..\nDo you.. \n A. Take him out \n B. Hide \n > ")

if JanChoice in DecisionA:
  print("\nYou sneak up behind the elderly janitor..")
  StrikeLoc = input(str("\nWhere do you strike the janitor? \n A. Head\n B. Crotch\n C. Leg\n > "))

  if StrikeLoc in DecisionA:
    print("\nThe janitor slumps to floor unconcious, crisis avoided!")
  
  elif StrikeLoc in DecisionB:
      print("\nThe janitor is completely unaffected.\n'You never should have come here' he announces, cracking his knuckles.\n The elderly janitor folds you like a pretzel!\n MISSION FAILED" )
      
  
  elif StrikeLoc in DecisionC:
    print("\nHe yells out cursing & setting off the alarm!\n MISSION FAILED! ")

elif JanChoice in DecisionB:
  print("\nThe janitor walks past blissfully unaware. \nYou press on further into the bank..")

JanSearch = input("\nDo you search the janitor?\n A. Yes\n B. No \n> ")

if JanSearch in DecisionA:
        print("\nYou find a keycard on him! With confidence you make your way to the vault!\n")

elif JanSearch in DecisionB:
      print("\nYou'll need a keycard to get into the vault!\nYou continue futher into the bank...")

VaultDoor = input("To the left of the giant door is a keycard slot, do you have a keycard?\nA. Yes\nB. No\n> ")

if VaultDoor in DecisionA:
  print("\nThe vault opens with a satisfying beep!\nPeering inside you find a diamond awaiting you!\nCongratulations!")

elif VaultDoor in DecisionB:
  print("You do not have a keycard, you turn back..")

Attached Files

.pdf   Flow Chart - Game.pdf (Size: 123.04 KB / Downloads: 134)
Reply
#2
Theoretically you could write a game as a cascading series of if/then statements, but it would be a challenge, and you'd probably need a really wide monitor to handle all the indenting. Instead of writing this as one large block of code, you should break it up into smaller scenarios and have a game flow manager that controls the transitions from one scenario to the next. You can find this pattern described as a State Machine. The scenarios are the "states".

A simple playable example:
# Define the "states".  These are functions that take user input and return the name of the next
# state.  Invalid input results in looping until valid input.

def start():
    x = input(
        "What Entrance do you want to choose? \n A. Main Entrance \n B. Side Entrance \n > "
    ).upper()
    if x == "A":
        print("\nMain Entrance Selected")
        return "Main Entrance"
    if x == "B":
        print("\nSide Entrance Selected")
        return "Side Entrance"
    print(f"\n{x} is not a valid input.")
    return "Start"


def main_entrance():
    x = input(str("\nWould you like to disable the cameras? Y/N \n> ")).upper()
    if x == "Y":
        print("The camera is disabled.")
        return "Main Lobby"
    if x == "N":
        print(
            "\nYou've been caught on camera during your heist.\nThe police have arrived and are taking you to prison.\nThere's no escaping the consequences of your actions.\n\nYOU HAVE ACHIVED:\nTHE PRISON ENDING!"
        )
        return "End"
    print(f"\n{x} is not a valid input.")
    return "Main Entrance"


def side_entrance():
    x = input(
        "\nYou enter quietly through the side entrance, it looks to be a service door.\nYou hear a shuffling sound ahead and spot a janitor working, glancing around you spot somewhere you could hide..\nDo you.. \n A. Take him out \n B. Hide \n > "
    ).upper()
    if x == "A":
        print("\nYou sneak up behind the elderly janitor..")
        return "Attack Janitor"
    if x == "B":
        print(
            "\nThe janitor walks past blissfully unaware. \nYou press on further into the bank.."
        )
        return "Unknown"
    print(f"\n{x} is not a valid input.")
    return "Side Entrance"


# Create a dictionary of state names: state functions
game_map = {
    "Start": start,
    "Main Entrance": main_entrance,
    "Side Entrance": side_entrance,
}

# Start the game
print("Lengthy introduction")
state = "Start"
while state != "End":
    state = game_map[state]()
Each of the functions defines a state and the transitions to other states. A simple dictionary and for loop replaces the error prone cascade of if statements. Now you can add as many scenarios as you like and not have to worry about breaking the existing map.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Complete beginnner making a text based adventure Mishmaccles 2 2,693 Jul-07-2021, 05:00 PM
Last Post: BashBedlam
  Adding an inventory and a combat system to a text based adventure game detkitten 2 6,906 Dec-17-2019, 03:40 AM
Last Post: detkitten
  Text Based Game DuaneJack 3 3,567 Aug-15-2018, 12:02 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020