Input() in python not working when after another input() - python

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

Related

How to make the program go back to the top of the code with a while loop?

I need to include a decrement life counter that has 5 lives. I need to use a while loop and once the player loses a life it needs to send them back to the choice between going left and right in the code. I am new to python so I am not very familiar with it, any help is appreciated.
answer = input("Do you want to go on an adventure? (Yes/No) ")
if answer.lower().strip() == "yes":
x=5
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
answer= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack":
print("She turned you into a green one-legged chicken, you lost!")
elif answer == "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer == "right":
import random
num = random.randint(1, 3)
answer = input("Pick a number from 1 to 3: ")
if answer == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer != num:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print("You can't run away...")
else:
print("That's too bad!")
You should try to add comments to your code, it will help you and others as well.
I think for getting user answer, you should use a different variable. It will make things easier.
I removed the following code, it didn't make any sense to me.
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
--
This is the code, which works:
# Try to write imported modules at the top, it's a good practice.
import random
# Start the game
answer_start = input("Do you want to go on an adventure? (Yes/No) ")
# user chooses to play
if answer_start.lower().strip() == "yes":
lives=5
# function for displaying the lives
def display_lives():
print("You have ",lives,"lives")
#display lives
display_lives()
# As long lives are more than 0, this will keep going.
while lives>0:
#First choice
answer1= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
#User chooses left
if answer1 == "left":
answer2 = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer2 == "attack":
print("She turned you into a green one-legged chicken, you lost!")
lives=lives-1
display_lives()
# User is running away
elif answer2 == "run":
print("Wise choice, you made it away safely.")
answer3 = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer3 == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer3 == "car":
print("You found your way home. Congrats, you won!")
elif answer3 != "plane" or answer3 != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer1 == "right":
num = random.randint(1, 3)
answer4 = input("Pick a number from 1 to 3: ")
if answer4 == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer4 != num:
print("You fall into deep sand and get swallowed up. You lost!")
lives=lives-1
else:
print("You can't run away...")
#Player chose not to play or player out of lives.
else:
print("That's too bad!")

Im trying to add a countdown timer in the background so that when time runs out the program is terminated

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!

PyCharm outputs a "Non ASCII" error on the terminal

I've been making game which is called the riddle game it works semi perfect on pycharm, because the code os.system("clear") doesn't work, but it does work on terminal, but there is slightly a problem it return with a a error "Non ASCII" i couldn't understand. How can i fix this?
Either way I try to make the code as simple as possible can anyone check it and if it's too big give me a suggestion to change a rewrite the code please.
import random
import sys
import time
riddle1 = "You’re running a race and pass the person in second place. What place are you in now?"
riddle2 = "Imagine you are in a dark room. How do you get out?"
riddle3 = "David's father has three sons : Snap, Crackle and _ _ _ ?"
riddle4 = "You answer me, but I never ask you a question. What am I?"
riddle5 = "The more you take, the more you leave behind. What am I?"
riddle6 = "What comes once in a minute, twice in a moment, but never in a thousand years?"
riddle7 = "What room that ghosts can't get in?"
riddle1_Ans = "You’re in second place. You didn't pass the person in first"
riddle2_Ans = "Stop imagining"
riddle3_Ans = "David"
riddle4_Ans = "A telephone"
riddle5_Ans = "Footsteps"
riddle6_Ans = "m"
riddle7_Ans = "The living room"
riddles_lists = [riddle1, riddle2, riddle3, riddle4, riddle5, riddle6, riddle7]
random_list = random.choice(riddles_lists)
# Welcoming the user
def welcome():
print("")
print("\033[1;31;0m", " Welcome to RIDDLES")
print("\033[1;33;0m", " ")
answer = input(" Do you want to play the game?Y/N:")
if answer in ("yes", "y"):
Introductin()
else:
print("Bye....")
sys.exit()
# RESTART GAME
def restart():
print(" ")
ask = input("Do you want to Try? if you say yes the game will restart"
" if you say no there answer of the riddle will be shown:")
if ask in ("yes", "y"):
print("Restarting game.....")
time.sleep(1)
play_game()
if ask in ("no", "n"):
print("The question was:")
print(" ")
print("\033[1;32;0m", random_list)
print(" ")
time.sleep(4)
print("\033[1;35;0m", "The answer is:")
print(" ")
time.sleep(1)
print(".........")
if random_list == riddle1:
print(riddle1_Ans)
if random_list == riddle2:
print(riddle2_Ans)
if random_list == riddle3:
print(riddle3_Ans)
if random_list == riddle4:
print(riddle4_Ans)
if random_list == riddle5:
print(riddle5_Ans)
if random_list == riddle6:
print(riddle6_Ans)
if random_list == riddle7:
print(riddle7_Ans)
print(".........")
# The Game
def Introductin():
print(" ")
print("\033[1;36;0m", "Hello there, I'm Zelandini the host of the game. You will be guessing the answer of the " \
"coming riddles"
", you have 20 second to guess. Once the time ran out you have the chance to see the answer.")
print(" ")
game_start = input("Ready?Y/N:")
if game_start in ("yes", "y"):
play_game()
def play_game():
sec = 1
print(" ")
while sec != 4:
print("Game starts in", sec)
time.sleep(1)
sec += 1
if sec == 4:
Game_Start()
def Game_Start():
minutes = 1
print(" ")
print("\033[1;32;0m BEGIN!")
print("..............")
print("\033[1;32;0m ", "The riddle is", random_list)
print("..............")
while minutes != 21:
print(">>>>", minutes, "seconds")
time.sleep(1)
minutes += 1
if minutes == 21:
print(" ")
print("\033[1;34;0m", "TIMES OUT!")
break
restart()
welcome()

Computer guessing game

import random
def start():
print "\t\t***-- Please enter Y for Yes and N for No --***"
answer = raw_input("\t\t Would you like to play a Guessing Game?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
def end():
print("\t\t\t **Goodbye** ")
raw_input("\t\t\t**Press ENTER to Exit**")
def game():
print "\t\t\t Welcome to Williams Guessing Game"
user_name = raw_input("\n\t\t Please enter your name: ")
print "\n", user_name, "I am thinking of a number between 1 and 20"
print "You have 5 attempts at getting it right"
attempt = 0
number = random.randint(1, 20)
while attempt < 5:
guess = input("\t\nPlease enter a number: ")
attempt = attempt + 1
answer = attempt
if guess < number:
print "\nSorry", user_name, "your guess was too low"
print "You have ", 5 - attempt, " attempts left\n"
elif guess > number:
print "\nSorry ", user_name, " your guess was too high"
print "You have ", 5 - attempt, " attempts left\n"
elif guess == number:
print "\n\t\t Yay, you selected my lucky number. Congratulations"
print "\t\t\tYou guessed it in", attempt, "number of attempts!\n"
answer = raw_input("\n\t\t\t\tTry again? Y/N?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
start()
If you want the computer to guess your number, you could use a function like this:
import random
my_number = int(raw_input("Please enter a number between 1 and 20: "))
guesses = []
def make_guess():
guess = random.randint(1, 20)
while guess in guesses:
guess = random.randint(1, 20)
guesses.append(guess)
return guess
while True:
guess = make_guess()
print(guess)
if guess == my_number:
print("The computer wins!")
break
else:
print(guesses)
It's just a quick-and-dirty example, but I hope it gives you the idea. This way, the computer gets unlimited guesses, but you could easily change the while loop to limit its number of guesses.

Hangman drawing regardless of correct letters (Python, turtle)

I'm creating a hangman game in Python 3.5.1 and everything is going well except for when it comes to the guessing part. I print "Hurray" when the letter is guessed correctly and I have it draw an additional body part when it is not guessed correctly. My problem is that even when a letter is guessed correctly it will also draw another body part:
import drawHangman
import turtle
import random
def main():
window = turtle.Screen()
window.setup(400, 400, 200, 200)
HG = turtle.Turtle()
drawHangman.default(HG)
wrongGuess = 0
maxGuesses = 0
lines = open('wordlist.txt').read().splitlines()
myline =random.choice(lines)
print(myline)
name = input("Welcome to hangman! What is your name? \n")
print("Welcome", name + "! \n The rules are as follows: \n 1) No looking at answer list! \n 2) Do not have fun!! \n 3) No hacking my game!")
tos = input("Do you accept the rules provided above? Type Yes or No. \n")
if tos == "no":
print("Who cares! The rules suck anyways!")
elif tos == "yes":
print("HI")
else:
print("You don't listen very well. I guess proceed ugh")
while maxGuesses < 6:
guess = input("Please input your guess!")
maxGuesses += 1
for char in myline:
if char in guess:
print("Hurray")
else:
wrongGuess += 1
print("You have", 6 - maxGuesses, "guesses left!")
if wrongGuess == 1:
drawHangman.drawHead(HG)
elif wrongGuess == 2:
drawHangman.drawBody(HG)
elif wrongGuess == 3:
drawHangman.drawLeftArm(HG)
elif wrongGuess == 4:
drawHangman.drawRightArm(HG)
elif wrongGuess == 5:
drawHangman.drawLeftLeg(HG)
elif wrongGuess == 6:
drawHangman.drawRightLeg(HG)
else:
playAgain = input('Do you want to play again? (yes or no)')
if playAgain == "yes":
drawHangman.reset(HG)
main()
else:
print("Thanks for playing!")
return
main()
I know it has something to do with the part where else tells it there is a wrong letter but I can't figure it out. I've tried indenting it one more space, but that just prints the amount of guesses left. Any help is appreciated.
PS. The drawHangman.* routines come from a file I have in my src folder that contains body parts.
You have indented the else clause (and the following lines) incorrectly - it's in the scope of the for loop instead of the if statement:
for char in myline:
if char in guess:
print("Hurray")
else:
wrongGuess += 1
print("You have", 6 - maxGuesses, "guesses left!")
if wrongGuess == 1:
drawHangman.drawHead(HG)
# etc.
As you wrote it, the else clause and all the drawings are executed only after the entire for loop has finished.
Besides the problem raised in your question, there seem to be other issues with your code: your logic assumes/hardcodes 6 letter words; you're repeat game logic is actually recursive; you don't close the words file after you're finished with it; your yes/no question handling isn't robust; you repeat things, by recalling main(), that need only be done once; you don't display the current correct/unknown letter status.
Below is a rework of your code to address these issues and play an actual game of hangman:
from turtle import Turtle, Screen
import random
import drawHangman
BODY_PARTS = [ \
drawHangman.drawHead, drawHangman.drawBody, drawHangman.drawLeftArm, \
drawHangman.drawRightArm, drawHangman.drawLeftLeg, drawHangman.drawRightLeg, \
]
MAXIMUM_WRONG_GUESSES = len(BODY_PARTS)
def hangman(HG):
drawHangman.default(HG)
with open('wordlist.txt') as file:
lines = file.read().splitlines()
word = random.choice(lines)
letters = set(word)
wrongGuesses = 0
while letters and wrongGuesses < MAXIMUM_WRONG_GUESSES:
for letter in word:
print("*" if letter in letters else letter, end="")
print(".")
letter = input("Please input your guess: ")
if letter in letters:
print("Hurray!")
letters.remove(letter)
else:
BODY_PARTS[wrongGuesses](HG)
wrongGuesses += 1
print("You have", MAXIMUM_WRONG_GUESSES - wrongGuesses, "guesses left!")
def main():
screen = Screen()
screen.setup(400, 400, 200, 200)
turtle = Turtle()
playAgain = True
print("Welcome to hangman!")
name = input("Enter your name: ")
print("Welcome", name + "!")
print("The rules are as follows:")
print(" 1) No looking at answer list!")
print(" 2) Do not have fun!!")
print(" 3) No hacking my game!")
tos = input("Do you accept the rules provided above? (yes or no): ")
if tos.lower().startswith("n"):
print("Who cares! The rules suck anyways!")
elif tos.lower().startswith("y"):
print("Hi")
else:
print("You don't listen very well. I guess proceed ugh")
while playAgain:
hangman(turtle)
answer = input('Do you want to play again? (yes or no): ')
playAgain = answer.lower().startswith("y")
if playAgain:
drawHangman.reset(turtle)
else:
print("Thanks for playing!")
main()

Categories

Resources