Related
How can I make it so the game is infinite? and is there a way to simplify this code?
I have tried to work around but can't seem to figure it out.
# A rock paper scissors game.
import random
Move1=input("Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower()
Move2=["r","p","s"]
while Move1 != "q":
if Move1 == "r" or "p" or "s" or "q":
# print(random.choice(Move2))
Move2=random.choice(Move2)
if Move1=="r" and Move2=="s":
print("You've won")
break
elif Move2=="p":
print("You lost!")
break
elif Move2=="r":
print("You went even!")
break
if Move1=="p" and Move2=="s":
print("You lost!")
break
elif Move2=="p":
print("You went even!")
break
elif Move2=="r":
print("You won!")
break
if Move1=="s" and Move2=="s":
print("You went even!")
break
elif Move2=="p":
print("You won!")
break
elif Move2=="r":
print("You lost!")
break
else:
print("You've quit the game!")
exit()
Tried to remove break
Move the request for input inside the loop. Use while True: around the loop to make it infinite. Remove all the break statements after reporting the winners and losers.
Don't use the same variable Move2 for the list of moves and the computer's move. That will prevent making a computer choice on the 2nd round.
# A rock paper scissors game.
import random
allowed_moves=["r","p","s"]
while True:
player_move=input("Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower()
if player_move in allowed_moves:
Move2=random.choice(allowed_moves)
if player_move=="r" and Move2=="s":
print("You've won")
elif Move2=="p":
print("You lost!")
elif Move2=="r":
print("You went even!")
if player_move=="p" and Move2=="s":
print("You lost!")
elif Move2=="p":
print("You went even!")
elif Move2=="r":
print("You won!")
if player_move=="s" and Move2=="s":
print("You went even!")
elif Move2=="p":
print("You won!")
elif Move2=="r":
print("You lost!")
else if player_move == 'q':
print("You've quit the game!")
break
else:
print("That's not a valid move!")
You have to re-evaluate the input at the end of the while loop. Or you put it into the while condition. So you could do while (Move1 := input(...)) != "q".
Also your first if check is always true because of the or "p". You would have to do or Move1 == "p" or Move1 == "s" or Move1 == "q"
You could simplify it with if Move1 in {"r", "p", "s", "q"}
Abstracting some of the game logic to a function is a start in the direction of simplifying. But there are other ways to simplify. Here's an example of it along with what I think you mean by making the game infinite.
def play(move1, move2):
# the logic
print("you win")
# more logic
is_playing = True
while is_playing:
Move1 = input(
"Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower()
Move2 = ["r", "p", "s"]
if Move1 == 'q':
print("You've quit the game!")
is_playing = False
break
play(Move1, Move2)
Let me know if that helps or not
### Import specification function required - for some reason if I do just "import random"
from random import randint
moves = ["rock", "paper", "scissors"]
### While pretty much is used so we can play over and over.
while True:
computer = moves[randint(0,2)]
player = input("Choose rock, paper or scissors, or 'end' to finish the game: ").lower()
### Break the loop if player wants to end
if player == "end":
print("The game is over")
break
### All possible iterations.
elif player == computer:
print("It's a tie!")
elif player == "rock":
if computer == "paper":
print("You lose!", computer, "beats", player)
else:
print("You win!", player, "beats", computer)
elif player == "paper":
if computer == "scissors":
print("You lose!", computer, "beats", player)
else:
print("You win!", player, "beats", computer)
elif player == "scissors":
if computer == "rock":
print("You lose!", computer, "beats", player)
else:
print("You win!", player, "beats", computer)
### This is to let the player know they typed in the wrong thing and re do it.
else:
print("Check your spelling and try again")
I made this code and have tried other ways to simplify but none of them seem to work as intended.
Any help refining/condensing the code with some explanations/guidance would be much appreciated.
This is my 3rd-day learning python so I'm not familiar with any of the more advanced python commands you may know.
You can eliminate most of your code and achieve the same result:
At its core, rock/paper/scissors is a 1/3 chance of each of win, loss, or tie. Therefore, requesting the user's input and then returning a randomly chosen outcome will give the same results.
import random as r
input("Enter rock, paper, or scissors")
print(r.choice(["You won!", "You lost!", "Tie!"]))
There isn't much here to be refined, really (and looks like something I'd make in Lua lol).
However, there are a few quality of life suggestions I can give:
player = input("...")
player = player.lower() # -- Strings in python act akin to arrays, and this changes all
# -- characters in the string lowercase
This way, if someone capitalizes in their response, it will still be recognized.
Beyond that, perhaps adding a simpler method to responding aswell:
elif player == "rock" or player == "r"
elif player == "paper" or player == "p"
elif player == "scissors" or player == "s"
However, that does add complexity, and I'm not sure if your looking to lower line count or complexity. (Probably both.) It's your choice.
(Maybe arrays could be used to make it very easy to add other moves, but I personally don't see the point there...)
You can create a function as follows to reduce code repetition in the win condition logic:
def is_win(player, computer):
if player == computer:
print('Tie')
elif player == 'rock' and computer == 'scissors' or
player == 'paper' and computer == 'rock' or
# Rest of win conditions here
print('Win')
else:
print('Lose')
Then invoke it like this:
is_win(player, computer)
There is another a bit advanced option to use class for Player and class for Computer and define methods for win for each one.
I'm new at coding and I've been trying this text-based adventure game. I keep running into syntax error and I don't seem to know how to solve this. Any suggestions on where I could have gone wrong would go a long way to helping.
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
def game_over(reason):
print("\n", reason)
print("Game Over!!!")
play_again()
def diamond_room():
print("\nYou are now in the room filled with diamonds")
print("what would you like to do?")
print("1) pack all the diamonds")
print("2) Go through the door")
answer = input(">")
if answer == "1":
game_over("The building collapsed bcos the diamonds were cursed!")
elif answer == "2":
print("You Win!!!")
play_again()
else:
game_over("Invalid prompt!")
def monster_room():
print("\nYou are now in the room of a monster")
print("The monster is sleeping and you have 2 choices")
print("1) Go through the door silently")
print("2) Kill the monster and show your courage")
answer = input(">")
if answer == "1":
diamond_room()
elif answer == "2":
game_over("You are killed")
else:
game_over("Invalid prompt")
def bear_room():
print("\nThere's a bear in here!")
print("The bear is eating tasty honey")
print("what would you like to do?")
print("1) Take the honey")
print("2) Taunt the bear!")
answer = input(">").lower()
if answer == "1":
game_over("The bear killed you!!!")
elif answer == "2":
print("The bear moved from the door, you can now go through!")
diamond_room()
else:
game_over("Invalid prompt")
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
start()
it keeps popping error and i cant detect where the error is coming from.
You have 2 problems.
Assertion instead of Assignment.
Calling the wrong function.
For 1. You have
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
You should uuse answer = input(">") and not answer ==.
For 2. You have
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
You should call start not play_again
In this part of your code, you should change you last line:
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
to answer = input(">").lower()
use = to assign a value to a variable, and use == to check the similarity(ex. in an if)
it is better to make the user input to lower case as other parts of your code, because in next lines of you've checked its value in an if condition with lower case (r and l).
3)another problem is that in def play_again(): you have to call start() function, sth like this:
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
start()
I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()
I'm a fairly new programmer, been struggling for a few years on and off with brief exposure to a few languages. I'm trying to finally get a firm grasp with Python, and to do so my current project is to design a simple text based game like "Zork".
I've successfully made an EXTREMELY simple version of this using functions for each room, however this isn't generalizable at all. Before I explain what I'm currently working on poorly, I'll link the code. Now as you can see, this is a very inefficient way of building rooms as it requires tons of code and I can't use it for anything except this exact game.
To start I created a list to be used as the player inventory
inventory = []
def addToInventory(item):
inventory.append(item)
This is the class I am using to construct weapons, and is where my trouble starts. The class works fine, and I can even add instances of it to my inventory list successfully.
class Weapon:
def __init__(self, name, damage, speed, weight):
self.name = name
self.damage = damage
self.speed = speed
self.weight = weight
sword = Weapon("Sword", 7, 5, 5)
knife = Weapon("Knife", 5, 7, 3)
stick = Weapon("Stick", 2, 3, 3)
This is the class I am attempting to design to create rooms. It has not been implemented yet. Right now the issue that I'm facing is that unable to add instances of the Weapon class to the argument for Roominv. So for example, I could not use the sword instance of my weapon class as an argument for the contents of a Room, it tells me that sword is undefined.
Entrance = Room("You are at an entrance", "N", "Search the ground", sword)
Now my goal with this project really is to learn, so I don't want any code, but am I going down the right path with this? How can I tie certain instances of the weapons class to certain rooms? Should I be using dictionaries to build the rooms instead? If I SHOULD be using dictionaries, do I have to create an individual dictionary for each room or are nested dictionaries a thing?
I've searched a lot for the answers to these as I'm sure similar questions have been asked, but I can't seem to find a straight answer.
class Room:
def __init__(self, description, exits, actions, Roominv): #Runs every time a new room is created
self.description = description
self.exits = exits
self.actions = actions
self.Roominv = Roominv
def GAMEOVER():
print("Oh no, it appears you have died. Press 1 to restart")
choice = input(">>> ")
if choice == "1":
intro()
def introstrt():
print("WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO")
print("PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?")
print("THEN LOOK NO FURTHER!")
print("BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,")
print("AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY")
print("THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.")
print("AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!")
print(" A A A A ooo")
print(" vvv vvv vvv vvv ooooo")
print("vvvvv vvvvv vvvvv vvvvv ooo")
print(" H H H H")
print(" A A A A")
print(" vvv vvv vvv vvv | O __")
print("vvvvv vvvvv vvvvv vvvvv +-|-(__) ")
print(" H H H H / \ ")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("PRESS 1 TO BEGIN")
choice = input(">>> ")
if choice == "1":
intro()
else:
print("I can't understand that command")
intro()
def intro():
global inventory
print("You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.")
print("You can:")
print("1.Look for sticks")
print("2. Do a backflip")
print("3.Attempt to befriend wildlife")
print("4.Go to Clearing ")
print("5.View Intro")
choice = input(">>> ")
if choice == "1":
print("You don't find any sticks. This is a poorly designed forest.")
intro()
elif choice == "2":
print("Sweet backflip, what now?")
intro()
elif choice == "3":
print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.")
print("GAME OVER.")
GAMEOVER()
elif choice == "4":
print("You move towards the clearing.")
clearing()
elif choice == "Pick up sword":
addToInventory(sword)
print("Your bag contains", inventory)
intro()
elif choice == "5":
introstrt()
else:
print("I can't understand that command")
intro()
def clearing():
print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
print("You can:")
print("1.Pick the flower")
print("2.Go towards the harp")
print("3.Curse the sun whilst masturbating vigorously")
print("4.Go back")
choice = input(">>> ")
if choice == "1":
print("You pick the white flower and put it in your bag. You notice that it glows slightly.")
clearingnofl()
elif choice == "2":
print("You can't tell which direction the music is coming from!.")
clearing()
elif choice == "3":
print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
print("The sun is deeply offended and goes away. It is dark now.")
clearingdrk()
elif choice == "4":
print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
intro()
else:
print("I can't understand that command")
clearing()
def clearingnofl():
print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
print("You can:")
print("1.Go towards the harp")
print("2.Curse the sun whilst masturbating vigorously")
print("3.Go back")
choice = input(">>> ")
if choice == "1":
print("You can't tell which direction the music is coming from!.")
clearingnofl()
elif choice == "2":
print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
print("The sun is deeply offended and goes away. It is dark now.")
print("You notice the flower glowing brightly in your bag.")
clearingnofldrk()
elif choice == "3":
print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
intronofl()
else:
print("I can't understand that command")
clearingnofl()
def clearingdrk():
print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
print("You can:")
print("1.Pick the flower")
print("2.Go towards the harp")
print("3.Apologize to the sun, promise that you'll change and things will be like they used to be.")
print("4.Go back")
choice = input(">>> ")
if choice == "1":
print("You pick the white flower and put it in your bag. You notice that it glows brightly in the dark.")
clearingnofldrk()
elif choice == "2":
print("You can't tell which direction the music is coming from!.")
clearingdrk()
elif choice == "3":
print("The sun reluctantly forgives you, it is sunny again.")
clearing()
elif choice == "4":
print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
introdrk()
else:
print("I can't understand that command")
clearingdrk()
def clearingnofldrk():
print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
print("You can:")
print("1.Go towards the harp")
print("2.Apologize to the sun, promise that you'll change and things will be like they used to be.")
print("3.Go back")
choice = input(">>> ")
if choice == "1":
print("You can't tell which direction the music is coming from!.")
clearingnofldrk()
elif choice == "2":
print("The sun reluctantly forgives you, it is sunny again.")
clearingnofl()
elif choice == "3":
print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
intronofldrk()
else:
print("I can't understand that command")
clearingnofldrk()
def intronofldrk():
print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
print("You can:")
print("1.Look for sticks")
print("2.Do a backflip")
print("3.Attempt to befriend wildlife")
print("4.Go to Clearing ")
choice = input(">>> ")
if choice == "1":
print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
intronofldrk()
elif choice == "2":
print("Sweet backflip, what now?")
intronofldrk()
elif choice == "3":
print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
elif choice == "4":
print("You move towards the clearing.")
clearingnofldrk()
else:
print("I can't understand that command")
intronofldrk()
def introdrk():
print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
print("You can:")
print("1.Look for sticks")
print("2.Do a backflip")
print("3.Attempt to befriend wildlife")
print("4.Go to Clearing ")
choice = input(">>> ")
if choice == "1":
print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
introdrk()
elif choice == "2":
print("Sweet backflip, what now?")
introdrk()
elif choice == "3":
print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
elif choice == "4":
print("You move towards the clearing.")
clearingdrk()
else:
print("I can't understand that command")
introdrk()
def intronofl():
print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
print("You can:")
print("1.Look for sticks")
print("2.Do a backflip")
print("3.Attempt to befriend wildlife")
print("4.Go to Clearing ")
choice = input(">>> ")
if choice == "1":
print("You don't find any sticks. This is a poorly designed forest.")
intronofl()
elif choice == "2":
print("Sweet backflip, what now?")
intronofl()
elif choice == "3":
print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
elif choice == "4":
print("You move towards the clearing.")
clearingnofl()
else:
print("I can't understand that command")
intronofl()
introstrt()
I would start by adding more structure, separating the definition of the rooms from the IO/action evaluation.
In terms of maintining state, one possibility (using introSword as an example) is to modify the containing Room within the action, changing the available future actions.
You'd have to change the input and output definitions for Python 3. Hopefully those are the only changes needed.
import traceback as tb
try:
input = raw_input
def output(*args):
print ''.join(map(str,args))
inventory = []
class Weapon:
def __init__(self, name, damage, speed, weight):
self.name = name
self.damage = damage
self.speed = speed
self.weight = weight
def __repr__(self):
return self.name
sword = Weapon("Sword", 7, 5, 5)
knife = Weapon("Knife", 5, 7, 3)
stick = Weapon("Stick", 2, 3, 3)
class Room:
def __init__(self,description,exits,actions,others=[]):
self.description = description
self.exits = exits
self.actions = actions
self.others = others
def render(self):
output(self.description)
if self.actions:
output('You can:')
for id,name,_ in self.actions:
output(id,'. ',name)
choice = input('>>> ').upper()
for id,_,action in self.actions:
if choice == id.upper():
action(self)
break
else:
for id,action in self.others:
if choice == id.upper():
action(self)
break
else:
output('I can\'t understand that command')
self.render()
quit = False
while not quit:
def introstrtBegin(room):
intro.render()
introstrt = Room(
'''
WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO
PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?
THEN LOOK NO FURTHER!
BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,
AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY
THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.
AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!
A A A A ooo
vvv vvv vvv vvv ooooo
vvvvv vvvvv vvvvv vvvvv ooo
H H H H
A A A A
vvv vvv vvv vvv | O __
vvvvv vvvvv vvvvv vvvvv +-|-(__)
H H H H / \
~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~
PRESS 1 TO BEGIN
''',
[],
[],
[('1',introstrtBegin)]
)
def gameoverRestart(_):
global quit
quit = False
def gameoverQuit(_):
global quit
quit = True
gameover = Room(
'Oh no, it appears you have died. Press 1 to restart, or 2 to quit.',
[],
[],
[('1',gameoverRestart)
,('2',gameoverQuit)
]
)
def introSticks(room):
output('You don\'t find any sticks. This is a poorly designed forest.')
room.render()
def introBackflip(room):
output('Sweet backflip, what now?')
room.render()
def introWildlife(room):
output('Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.')
output('GAME OVER.')
gameover.render()
def introClearing(room):
output('You move towards the clearing.')
clearing.render()
def introNoSword(room):
output('You already picked up the sword')
room.render()
def introSword(room):
global inventory
inventory.append(sword)
output('Your bag contains: ',inventory)
room.description = 'You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.'
room.others = [
('pick up sword',introNoSword)
]
room.render()
intro = Room(
'''
You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.
''',
[],
[('1','Look for sticks',introSticks)
,('2','Do a backflip',introBackflip)
,('3','Attempt to befriend wildlife',introWildlife)
,('4','Go to Clearing',introClearing)
,('5','View Intro',lambda _: introstrt.render())
],
[('pick up sword',introSword)]
)
def clearingFlower(room):
output('You pick the white flower and put it in your bag. You notice that it glows slightly.')
room.render()
def clearingHarp(room):
output('You can\'t tell which direction the music is coming from!.')
room.render()
def clearingCurse(room):
output('CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.')
output('The sun is deeply offended and goes away. It is dark now.')
room.render()
def clearingBack(room):
output('You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.')
intro.render()
clearing = Room(
'''
You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.
''',
[],
[('1','Pick the flower',clearingFlower)
,('2','Go towards the harp',clearingHarp)
,('3','Curse the sun whilst masturbating vigorously',clearingCurse)
,('4','Go back',clearingBack)
]
)
introstrt.render()
except:
tb.print_exc()
finally:
input('#')