Im very new to code and decided to make my own little dungeon crawler text game using Python because im in tutorial hell. However i just learned about "DRY" (Dont repeat yourself) and my code definitely repeats itself. So im trying to learn how i can condense my code to not make it so long and repetitive.
I will upload the entire code for context but my question revolves around (# Troll Encounter) and (# Goblin Encounter), How can i make it so these aren't just repeat code blocks, if that makes sense?
`import random
import time
hitpoints = int(100)
hit = int(-50)
troll = 100
goblin = 100
print("You wake up in a dark dungeon with weapons laying around you")
time.sleep(1)
print(".")
time.sleep(1)
print(".")
time.sleep(1)
print(".")
time.sleep(1)
# Weapon Selection
weapon = str(input("Select your weapon - broadsword, spear, or dagger: "))
if weapon == "Broadsword" or weapon == "broadsword":
print("You've selected a broadsword.")
if input("are you sure? (y/n)") != "y":
exit()
print("This weapon has a 2 second delay")
elif weapon == "Spear" or weapon == "spear":
print("You've selected a spear.")
if input("are you sure? (y/n)") != "y":
exit()
print("This weapon has a 1 second delay")
elif weapon == "Dagger" or weapon == "dagger":
print("You've selected a dagger.")
if input("are you sure? (y/n)") != "y":
exit()
print("This weapon has no delay")
time.sleep(1)
print(".")
time.sleep(1)
print(".")
time.sleep(1)
print(".")
time.sleep(1)
print("A Troll sees you wandering the dungeon halls")
# Troll Encounter
while True:
if troll <= 0:
print("The Troll is dead!! *bump badabum bum bumm bumbadummm*")
break
attack = input("Hit or escape? ")
if attack == ("hit" or "Hit"):
if weapon == "spear":
print("Tink!")
time.sleep(1)
elif weapon == "broadsword":
time.sleep(1)
print("Tink!")
time.sleep(1)
else:
print("Tink")
print("The Troll now has", troll + hit, "health-points")
troll-=50
elif attack == ("escape" or "Escape"):
print("You have escaped with your", hitpoints, "health-points")
break
input("Press enter to continue...")
time.sleep(1)
print(".")
time.sleep(1)
print(".")
time.sleep(1)
print("As you walk down the dungeon hall you run into a group of Goblins! Defend yourself!!")
time.sleep(1)
print(".")
time.sleep(1)
# Goblin encounter
while True:
if goblin <= 0:
print("The Goblin is dead!! *bump badabum bum bumm bumbadummm*")
break
attack = input("Hit or escape? ")
if attack == ("hit" or "Hit"):
if weapon == "spear":
print("Tink!")
time.sleep(1)
elif weapon == "broadsword":
time.sleep(1)
print("Tink!")
time.sleep(1)
else:
print("Tink")
print("The Goblin now has", goblin + hit, "health-points")
goblin -= 50
elif attack == ("escape" or "Escape"):
print("You have escaped with your", hitpoints, "health-points")
break
input("Press enter to continue...")
`
I was thinking about using the def init(Self) function and try to return it again during the # Goblin Encounter, but im having a hard time implementing it. If that would even work im not sure cause i was unable to get it to work
Related
I am learning how to make a text typed game in python. I could not get it to work. eventhough there is a water in my list (bag) it would still end the game eventhough i have it. Please help me
...
bag = [ ]
sword = ("sword")
water_bucket = ("water")
dead = False
ready = input("are you ready? ")
while dead == False:
print("this is whats inside your bag ")
print(bag)
if ready == "yes":
print("let's start our journey ")
print(
"It was a beautiful morning, you woke up in a dungeon, your quest is to find a dragon and slay his head off")
while dead == False:
if dead == True:
break
else:
first = input("Choose a path front/back/left/right")
if first == "front":
if bag == "water":
print(" You got safe because of the water bucket")
else:
dead = True
print(" You died in a hot lava")
elif first == "back":
ask2 = input("There is a sword, do you want to take it?")
if ask2 == "yes":
bag.append(sword)
print("You got a sword")
elif ask2 == "no":
print("you did not take it and went back to start")
else:
print("please answer with yes or no")
elif first == "left":
if bag == "sword":
print("You fought a dragon and win")
elif bag != "sword":
print("You fought a dragon but lost because you do not have a weapon")
dead = True
elif first == "right":
ask3 = input("Water Buckets! might be helpful, take it? ")
if ask3 == "yes":
bag.append(water_bucket)
print("You got a water bucket")
print(bag)
elif ask3 == "no":
print("you did not take it and went back to start")
else:
print("please answer with yes or no")
else:
print("not a path")
else:
print("See you next time, A journey awaits")
...
It is a text based im learning right now
I am creating a 2 player number guessing game in python 3.8. I want a countdown timer to run in the background so that the program is terminated when time runs out, but its not working. I have tried using a solution I found online but the program does not get terminated.
declaring all the variable and modules
import random
guess=""
Gamewinner=0
n = random.randint(1, 99)
lives = 8
answer = "yes"
print("You have a total of 8 lives. A wrong guess would result in one less life.")
SingleOrDouble=input("Do you want single player or double player?")
from time import *
import threading
The solution that I found online
def countdown():
global my_timer
my_timer=5
for x in range(5):
my_timer=my_timer-1
sleep(1)
print("Out of time")
countdown_thread=threading.Thread(target=countdown)
countdown_thread.start()
main program
while my_timer>0:
if SingleOrDouble=="Single":
while answer=="yes" or answer=="Yes":
while lives!=0 and n!=guess:
guess = int(input("Enter an integer from 1 to 99: "))
if guess < n:
print("guess is low")
lives-=1
print("You have "+ str(lives) +" lives left.")
elif guess > n:
print ("guess is high")
lives-=1
print("You have "+ str(lives) +" lives left.")
else:
print("You guessed it!")
print("You won with "+ str(lives) +" lives left.")
break
print("Game over, the number was "+ str(n))
answer = input("Do you want to play again?")
if answer=="yes" or answer=="Yes":
lives=8
else:
lives=16
while answer=="yes"or answer=="Yes":
while lives!=0 and n!=guess:
if lives%2==0:
guess = int(input("Player 1 please Enter an integer from 1 to 99: "))
else:
guess = int(input("Player 2 please Enter an integer from 1 to 99: "))
if guess < n:
print("guess is low")
lives-=1
print("You have "+str(lives//2)+" lives left.")
elif guess > n:
print ("guess is high")
lives-=1
print("You have "+ str(lives//2) +" lives left.")
else:
if lives%2==0:
print("Player 1 guessed it!")
print("You won with "+ str(lives//2) +" lives left.")
Gamewinner=2
else:
print("Player 2 guessed it!")
print("You won with "+ str(lives//2) +" lives left.")
Gamewinner=1
break
if Gamewinner>0:
print("Game Over! Player "+str(Gamewinner)+"the number was "+ str(n))
else:
print("Game Over! The number was "+ str(n))
answer = input("Do you want to play again?")
if answer=="yes" or answer=="Yes":
lives=8
sleep(1)
if my_timer==0:
break
The code for the countdown timer is working just fine. What you could do is - Use a system exit when the timer hits zero so that you could stop the execution of your program.
You would need to use os._exit(1) to terminate your Python program. The modified code would look something like this -
from time import *
import os
import random
import threading
guess=""
Gamewinner=0
n = random.randint(1, 99)
lives = 8
answer = "yes"
print("You have a total of 8 lives. A wrong guess would result in one less life.")
SingleOrDouble=input("Do you want single player or double player?")
def countdown():
global my_timer
my_timer=5
for x in range(5):
my_timer=my_timer-1
sleep(1)
print("Out of time")
os._exit(1)
countdown_thread=threading.Thread(target=countdown)
countdown_thread.start()
I would put the game in a function called game and run it in a daemon thread so that it terminates when the main thread terminates. If N_SECONDS is the number of seconds allotted to the game then the main thread becomes simply:
from threading import Thread
import sys
N_SECONDS = some_value
t = Thread(target=game)
t.daemon = True
t.start()
t.join(N_SECONDS) # block for N_SECONDS or until the game ends by returning
if t.is_alive(): # the game has not returned and is still running
print('Out of time!')
sys.exit(0) # exit and the thread terminates with us
No additional timing is required!
When I have a line that has input() on it, the input() line after the first won't work when both are after each other. Here is my code.
from random import randint
you = 100
troll = 50
sword = randint(5,20)
goblin_attack = randint(25,50)
heal = you + 25
t_f = randint(1,2)
print("______________________")
print("WELCOME TO DRAGON GAME")
print("WRITE YOUR NAME......")
x = input()
print("Hello,")
print(x)
print("Lets begin....")
print("______________________")
print("You are in a troll cave")
print("A troll attacks!")
print("Quick, Dodge or attack,type D or A ")
print("______________________")
if input() == "D":
print("You attempt to dodge out of it's swing!")
if t_f == 1:
print("You dodge and attack!")
print("You hit the troll for")
print(sword)
print("damage")
print("It has")
print(troll - sword)
print("health left!")
if t_f == 2:
print("You trip! you got hit for")
print(goblin_attack)
print("damage!")
print("You have")
print(you - goblin_attack)
you2 = you- goblin_attack
print("Health left!")
if input() == "A":
print("You hit the troll for")
print(sword)
print("damage")
print("It has")
print(troll - sword)
print("health left!")
When I press A and hit enter, Nothing happens. But when I press D, it works. The first one always works no matter what I change the input to. Anyone have any idea how I can make both inputs work?
Each input call waits for a keyboard input, so when you call input() twice, you're asking for two keyboard inputs.
To fix, change your code to something like so:
user_input = input()
if user_input == 'D':
# go through the "dodge" scenario
elif user_input == 'A':
# go through the "attack" scenario
I was writing a code in a programming book for beginners.
This is what it looks like. (I HAVE TO EXTEND THIS POST BECAUSE THIS WEBSITE IS SO FINICKY ABOUT QUESTION POSTS.)
import random
print("You are in a dark room in a mysterious castle.")
print("In front of you are four doors. You must choose one.")
playerChoice = input("Choose 1, 2, 3, or 4...")
if playerChoice == "1":
print("You found a room full of tresure. YOU'RE RICH!!!")
print("GAME OVER, YOU WIN!")
elif playerChoice == "2":
print("The door opens and an angry ogre hits you with his club.")
print("GAME OVER, YOU DIED!")
elif playerChoice == "3":
print("You encounter a sleeping dragon.")
print("You can do either:")
print("1) Try to steal some of the dragon's gold")
print("2) Sneak around the dragon to the exit")
dragonChoice = input("type 1 or 2...")
if dragonChoice == "1":
print("The dragon wakes up and eats you. You are delicious.")
print("GAME OVER, YOU WERE EATEN ALIVE.")
elif dragonChoice == "2":
print("You sneak around the dragon and escape the castle, blinking in the sunshine.")
print("GAME OVER, YOU ESCAPED THE CASTLE.")
else:
print("Sorry, you didn't enter 1 or 2.")
elif playerChoice == "4":
print("You enter a room with a sphinx.")
print("It asks you to guess what number it is thinking of, betwwen 1 to 10.")
number = int(input("What number do you choose?")
if number == random.randint (1, 10)
print("The sphinx hisses in dissapointment. You guessed correctly.")
print("It must let you go free.")
print("GAME OVER, YOU WIN.")
else:
print("The sphinx tells you that your guess is incorrect.")
print("You are now it's prisoner forever.")
print("GAME OVER, YOU LOSE.")
else:
print("sorry, you didn't enter 1, 2, 3, or 4...")
print("YOU TURN BACK AND LEAVE (YOU COWARD)")
Here are two of your problems:
number = int(input("What number do you choose?")
if number == random.randint (1, 10)
The cast to int is missing a closing parenthesis and the if statement is missing a colon.
The last problem has to do with the double else statement at the end. Un-indent the last one, assuming that is what you wanted.
Fixed:
import random
print("You are in a dark room in a mysterious castle.")
print("In front of you are four doors. You must choose one.")
playerChoice = input("Choose 1, 2, 3, or 4...")
if playerChoice == "1":
print("You found a room full of tresure. YOU'RE RICH!!!")
print("GAME OVER, YOU WIN!")
elif playerChoice == "2":
print("The door opens and an angry ogre hits you with his club.")
print("GAME OVER, YOU DIED!")
elif playerChoice == "3":
print("You encounter a sleeping dragon.")
print("You can do either:")
print("1) Try to steal some of the dragon's gold")
print("2) Sneak around the dragon to the exit")
dragonChoice = input("type 1 or 2...")
if dragonChoice == "1":
print("The dragon wakes up and eats you. You are delicious.")
print("GAME OVER, YOU WERE EATEN ALIVE.")
elif dragonChoice == "2":
print(
"You sneak around the dragon and escape the castle, blinking in the sunshine.")
print("GAME OVER, YOU ESCAPED THE CASTLE.")
else:
print("Sorry, you didn't enter 1 or 2.")
elif playerChoice == "4":
print("You enter a room with a sphinx.")
print("It asks you to guess what number it is thinking of, betwwen 1 to 10.")
number = int(input("What number do you choose?"))
if number == random.randint(1, 10):
print("The sphinx hisses in dissapointment. You guessed correctly.")
print("It must let you go free.")
print("GAME OVER, YOU WIN.")
else:
print("The sphinx tells you that your guess is incorrect.")
print("You are now it's prisoner forever.")
print("GAME OVER, YOU LOSE.")
else:
print("sorry, you didn't enter 1, 2, 3, or 4...")
print("YOU TURN BACK AND LEAVE (YOU COWARD)")
Python is a whitespace delimited language, which means you need to pay special attention to indentation. Your indentation is inconsistent which will inevitably lead to issues.
Other than that, you did not specify WHAT your error actually is. Add the syntax error information to your post.
You just had some problems with spacing and forgot ":" in line 30
import random
print("You are in a dark room in a mysterious castle.")
print("In front of you are four doors. You must choose one.")
playerChoice = input("Choose 1, 2, 3, or 4...")
if playerChoice == "1":
print("You found a room full of tresure. YOU'RE RICH!!!")
print("GAME OVER, YOU WIN!")
elif playerChoice == "2":
print("The door opens and an angry ogre hits you with his club.")
print("GAME OVER, YOU DIED!")
elif playerChoice == "3":
print("You encounter a sleeping dragon.")
print("You can do either:")
print("1) Try to steal some of the dragon's gold")
print("2) Sneak around the dragon to the exit")
dragonChoice = input("type 1 or 2...")
if dragonChoice == "1":
print("The dragon wakes up and eats you. You are delicious.")
print("GAME OVER, YOU WERE EATEN ALIVE.")
elif dragonChoice == "2":
print("You sneak around the dragon and escape the castle, blinking in the sunshine.")
print("GAME OVER, YOU ESCAPED THE CASTLE.")
else:
print("Sorry, you didn't enter 1 or 2.")
elif playerChoice == "4":
print("You enter a room with a sphinx.")
print("It asks you to guess what number it is thinking of, betwwen 1 to 10.")
number = int(input("What number do you choose?"))
if number == random.randint (1, 10):
print("The sphinx hisses in dissapointment. You guessed correctly.")
print("It must let you go free.")
print("GAME OVER, YOU WIN.")
else:
print("The sphinx tells you that your guess is incorrect.")
print("You are now it's prisoner forever.")
print("GAME OVER, YOU LOSE.")
else:
print("sorry, you didn't enter 1, 2, 3, or 4...")
print("YOU TURN BACK AND LEAVE (YOU COWARD)")
I'm working on a text-based RPG, but I've found numerous problems, like:
being unable to go anywhere after entering the shop;
I cannot access the "tavern" for some reason; and
the computer just says "buy is not defined in crossbow".
Code:
gold = int(100)
inventory = ["sword", "armor", "potion"]
print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
classic = {"Warrior",
"Archer",
"Mage",
"Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
crossbow = int(50)
spell = int(35)
potion = int(35)
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
answer = input("Do you want it: ")
if answer == "yes":
print("Thank you for coming!")
inventory.append("crossbow")
gold = gold - crossbow
print("Your inventory is now:")
print(inventory)
print("Your gold store now is: ", gold)
if answer == "no":
print("Thank you for coming!")
if buy == "spell":
print("this costs 35 gold")
answear2 = input("Do you want it: ")
if answear2 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - spell
print("Your inventory is now:")
print(inventory)
if answear2 == "no":
print("Thank you for coming!")
if buy == "potion":
print("this costs 35 gold")
answear3 = input("Do you want it: ")
if answear3 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - potion
print("Your inventory is now:")
print(inventory)
if answear3 == "no":
print("Thank you for coming!")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
print("They notice you as you get close and become weary of your presence.")
print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
if dexterity >= 5:
print("You quickly dodge the mug and leave the warriors alone")
else:
print("You are caught off guard and take the mug to the face compleatly soaking you.")
print("The dodgy figure leaves the tavern")
The first time you ask the user where to go on line 111, what happens if they enter something besides "shop"? then the if choice == "shop": condition on line 119 will fail, and buy = input("...") will never execute. At that point, buy doesn't exist, so when the next conditional executes, it crashes because it can't evaluate if buy == "crossbow". buy has no value, so you can't compare it to anything.
You need to indent all of your shop logic so that it lies inside the if choice == "shop" block.
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
#...etc
if buy == "spell":
print("this costs 35 gold")
And the same problem is present for your tavern code. Even if you don't go to the tavern, you check for tavernChoice. That needs to be indented as well.
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
At this point, your program will end, but I'm guessing you want to continue to be able to explore areas. You could put everything in a while loop, starting with the first input command.
while True:
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "shop":
print("Welcome to the shop!")
#...etc
elif choice == "tavern":
print("You enter the tavern...")
#...etc
elif choice == "forest":
print("You enter the forest...")
#etc
else:
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
This is also a little cleaner than your current method, since you only have to ask the user where they're going once, instead of three times on lines 112, 165, and 170.
Building on Kevin's answer, here is a version with redundancy squeezed out, so you can add a new place just by adding a new def go_xyz(): ... near the top.
def go_shop():
print("Welcome to the shop!")
#...etc
def go_tavern():
print("You enter the tavern...")
#...etc
def go_forest():
print("You enter the forest...")
#etc
places = {name[3:]:globals()[name] for name in globals() if name.startswith('go_')}
placenames = ', '.join(places)
inventory = ['book']
retry = False
while True:
if not retry:
print("Here is your inventory: ", inventory)
else:
print("I do not know that place")
print("Where do you wish to go?")
print("Possible places: ", placenames, '.')
choice = input("? ")
try:
places[choice]()
retry = False
except KeyError:
retry = True