PyCharm outputs a "Non ASCII" error on the terminal - python

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()

Related

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

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'm making a text based adventuere game in python and trying to add a third option but it's not working

I'm trying to make a simple text adventure game with three choices. But I can't seem to figure out why this isn't working.
This is the code I have been working on:
#Text based medieval adventure game
#Imported libraries are required
import random
import time
def displayWelcome():
print ("\nText adventure game\n")
print ("Welcome to the medieval adventure game!")
print ("You will have many choices through out this game")
print ("Be sure to pick the right one")
print (" Good Luck! ")
answer = askYesNo("Would you like help with this program? (Y/N): ")
if answer == "Y":
helpForUser()
time.sleep(3)
def askYesNo (question):
# This function will ask you a yes or no question and will keep asking until one is chosen.
# The following function is used to erase the variable response of any values
response = None
while response not in ("Y", "N"):
response = input (question).upper()
return response
def helpForUser():
#This function will show the user some helpful advice if they desire it
print ("\n+++++++++++++++++++++++++++++++++++++++ Help +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print ("This game is a adventure text based game set in the medieval times")
print ("You will be asked multiple questions with a yes or no response")
print ("you must answer the questions with the answers supplied to you suches as yes or no")
print ("If you don't answer the q uestion with the given answers it will be repeated untill a valid response occurs")
print ("The program can end when you choose")
print ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def displayIntro():
#Displays intro to game
print ("\n It's been a rough day in the wild and you despratly need shelter")
print ("There is currently a war going on and nowhere is safe")
print ("But you intend to find somwhere with food and a bed but it wont be easy...")
print ()
def choosePath(lower,middle,upper):
#This functions allows you to choose between multiple options
path = 0
while path < lower or path > upper:
number = input("What path will you take(" + str(lower) + " - " + str(upper) + ")?: ")
if number.isdigit():
path = int (number)
else:
path = 0
return path
def followPath(chosenPath):
print ("you head down a long road\n")
time.sleep(3)
print ("You come across an abandoned campsite and decide to stay there for the night")
time.sleep(3)
print("You wake up to a sudden sound of voices and begin to realise that this campsite wasn't abandoned...")
time.sleep(3)
print("You start to freak out")
time.sleep(3)
if chosenPath == 1:
print("You grab your sword out and decide to go out the tent")
print ("Four well trained knights surround you")
print ("They strike without any hesitation, you counter two knights trying to hit you from the front as two from behind stab you in the back")
print ("The knights decide to burn your body and leave nothing left of you.\n")
elif chosenPath == 2:
print("You dart out of the tent and head for the exit")
print("All the guards try and get you whilst shooting arrows")
print("Several arrows hit you leaving you injured unable to run")
print ("Suddenly a man with a giant axe appears before you and slices you head off in a clean swoop\n")
else chosenPath == 3:
print("You keep calm and decide to sneak past all the guards")
print ("You're close to the exit when suddenly a guard notices you")
print("He's about to call for back up when you dash right into his chest with your sword, leaving it in him and running out the campsite")
print("You make it to a safe forest and decide to rest\n")
displayWelcome()
playAgain = "Y"
while playAgain == "Y":
displayIntro()
choice = choosePath()
followPath(choice)
playAgain = askYesNo ("Would you like to play again?")
print ("\nBye")
Error Number one: line 63, else should be elif or get rid of the condition "chosenPath == 3:
Current state
else chosenPath == 3:
What it should look like
elif chosenPath == 3:
or
else:
The other error is that nothing ever happens on initialization of choice because you forgot to input the "lower, middle, upper" values.

How do I stop this program after a certain amount of time

I just started programming python for GCSE and made a program called do not press the button, it is going good, but at the end there is the part where you need to try to click the enter button(which is impossible on purpose) Does anyone know how to stop it after 10seconds and continue with the program? (I used sources from everywhere the internet, myself and friends, dont get disturbed by the #'s)
print("##############################")
print("DO NOT PRESS THE ENTER BUTTON!")
print("##############################")
a = input("")
b = input("Hello?")
name = input("What is your name?\n")
d = input("Aha, you know " + str(name) + " you are very anoying!")
e = input("Stop it!")
f = input("I hate you soooo much")
g = input("I am sure you don't have friends")
h = input("BECAUSE ANOYING PEOPLE DON'T HAVE FRIENDS!!!")
i = input("I just won't answer anymore")
j = input("you will get bored")
k = input(".")
l = input("..")
m = input("...")
n = input("....")
o = input(".....")
p = input("STOOOOOOPPPP!!!!!")
q = input("You know what, i will lock me in with a code HA!")
import time
import random
import sys
print("Here you go, locked... you only have 5 tries, its between 1 and
20, and if you fail, I WILL SHUT DOWN YOUR COMPUTER, NO ENTER BUTTON
PRESSING THEN HAHAHA!!!\n")
#sets initial values
the_number = random.randint(1,20)
guess = int(input("Take a guess: "))
tries = 1
guesses = 5
#guessing loop
while guess != the_number:
tries += 1
guesses -= 1
if guesses == 0:
print("Computer getting shut down in,")
print("!3!")
time.sleep(1)
print("!2!")
time.sleep(1)
print("!1!")
time.sleep(5)
print("Just joking haha, but this is still finished.\n\n")
print("cOmMANd ENTER BUTTON bLOcKed!")
time.sleep(2)
print("##########")
print("YOU LOSE!!")
print("##########")
time.sleep(2)
sys.exit("Error message")
break
elif guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
guess = int(input("Take a guess: "))
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input()
#number guesser from internet changed slightly
print("aha, i see you unlocked me, you are so vexatious...")
r = input("...")
s = input("TAKE YOUR DIRTY FINGERS OFF ME!!!")
t = input("Man you are so anoying, by the way, ure you don't even know
what vexatious means, haha")
u = input("I will just move away, try pressing me know:")
time.sleep(4)
#Button game from internet
from tkinter import *
from random import *
def do_event(event):
print("{},{}".format(event.x,event.y))
def jump(event):
app.hello_b.place(relx=random(),rely=random())
class App:
def __init__(self,master):
frame = Frame(master)
master.geometry("500x500")
master.title("You will never catch me!")
master.bind("<Button-1>",do_event)
master.bind("<Button-1>",do_event)
frame.pack()
self.hello_b = Button(master,text="Enter
Button",command=sys.exit)
self.hello_b.bind("<Enter>",jump)
self.hello_b.pack()
root = Tk()
app = App(root)
root.mainloop()
#here i don't know how to end it, i want it to end after 10sec and
#continue with that
print("ahhh you got me...")
Try this timeout script written in bash.
#!/bin/sh
timeout 15 ./test.sh
status=$?
if[$status -eq 124] #time out
then
exit 0
fi
exit $status

hangman game in python after trying to exit after playing one round

If I play one round of the game and select the option to quit, the game finishes, BUT, if I play a second round and try to quit, the game continues and the user is prompted to enter a guess again, instead of terminating the game.
It seems to be stuck in a loop.
Here is my code:
from random import randint
def core_game():
def init_hangman():
hangman = []
for x in range(7):
hangman.append([" "] * 7)
hangman[0][0] = "_"
hangman[0][1] = "_"
hangman[0][2] = "_"
hangman[1][3] = "|"
return hangman
hangman = init_hangman()
def print_hangman():
for x in hangman:
print(str.join("", x))
def get_input(guess):
your_guess = input(guess)
if your_guess in guessed_letters:
print("You already guessed that letter!")
return get_input(guess)
elif your_guess.isalpha() and len(your_guess) == 1:
return your_guess
else:
print("Please guess a single letter!")
return get_input(guess)
words_list = ["monkey", "cow"]
city_list = ["Amarillo", "Houston"]
lists = ["animals", "cities"]
random_list = randint(0,1)
random_word = randint(0,1)
if lists[random_list] == "cities":
rand_list = city_list
elif lists[random_list] == "animals":
rand_list = words_list
word = rand_list[random_word]
guessed = ""
guessed_letters = []
hang = 6
Cont = True
for letter in word:
guessed += "-"
print("\n\n\nWELCOME TO HANGMAN!")
print("The category is: ", lists[random_list])
print("The secret word: ", guessed, "is", len(guessed), "letters")
while Cont:
your_guess = get_input("\nEnter your guess: ")
if your_guess in word.lower():
for x in range(len(word)):
if word[x].lower() == your_guess.lower():
guessed = guessed[:x] + word[x] + guessed[x+1:]
guessed_letters.append(your_guess)
print("\nThe secret word: ", guessed)
if guessed.lower() == word.lower():
print("\n\nCongratulations, you guessed the word!")
play_again = input("\nWould you like to play again?(y/n) ")
if play_again == "y" or play_again == "yes":
core_game()
else:
Cont = False
else:
hang -= 1
guessed_letters.append(your_guess)
print("\nGuessed letters: ", guessed_letters)
if hang == 5:
hangman[2][3] = "O"
print_hangman()
print(guessed)
elif hang == 4:
hangman[3][3] = "|"
print_hangman()
print(guessed)
elif hang == 3:
hangman[3][2] = "-"
print_hangman()
print(guessed)
elif hang == 2:
hangman[3][4] = "-"
print_hangman()
print(guessed)
elif hang == 1:
hangman[4][2] = "/"
print_hangman()
print(guessed)
elif hang == 0:
hangman[4][4] = "\\"
print_hangman()
print("Game Over!")
print("The word was: ", word)
play_again = input("Would you like to play again?(y/n) ")
if play_again == "y" or play_again == "yes":
core_game()
else:
Cont = False
core_game()
The main function is core_game() and this is called when the program is run.
Okay- yes, I like the game- played it in the browser at trinket.io
Then I walked through an entire game here. Use this to debug your code, step by step and you can view all of the variables, lists etc. as well as enter input and view output.
The reason that your game is repeating is because:
1) In the function core_game you have the following code:
if play_again == "y" or play_again == "yes":
core_game()
This means that when you select yes after the first game, you are opening another "instance" of the function- you can see this if you trace through the code. You can also see this in the screenshot below (f19).
2) after you play the second game (remember that the first instance is still open) and select "n", this causes the "Cont" variable to change to False, but only in the second instance. The "while" is closed then, and the code goes back to the first instance where Cont is still True. You can also see both instances in the screenshot, and the state of each value of "Cont". The closed frame is "greyed out".
3) The program resumes in the first instance of the core_game at the start of the while loop, and the user is prompted to enter a guess.
This is difficult to see until you trace through the code, but I have included a snapshot here where you can (I hope) see what I mean.
So the issue is that you are calling the function from within itself.
Consider something more like this:
def core_game():
print("I was called")
while Cont:
ans = ("Do you wish to play a game? (Y/N)")
if ans[0].lower() == "y": # works for Y, y, Yup, Yeah, Yes etc.
core_game()
else:
Cont = False
PS
there are other really good reference sources out there, such as this as well.
Never give up- you'll find the step-thru really handy, and you might try Rice Universities MOOC on Coursera at some later stage.

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.

Categories

Resources