Python: Guessing game gone wrong - python

I'm trying to create a small, basic guessing game in python, something like Text Twist. Here's the code:
while game_running == True:
if (tries_left != 0):
print "Tries left: " + str(tries_left)
chosen_text = text_list[picker(text_length)]
scrambled_text = scrambler(chosen_text)
print "Guess the word/s: " + scrambled_text
guess_text = raw_input("Your answer (space included): ")
if (chosen_text == guess_text):
print "Congratulations! You guessed correctly!"
game_running = False
else:
tries_left-=1
else:
print "LOL. You dun goofed son. Terminating like SkyNet..."
game_running = False
Out of sight functions:
picker - basically a randomizer
scrambler - scrambles the words. In progress and not yet implemented.
You have 3 tries to guess correctly, or the app terminates. If you guessed correctly, the app displays a message, then terminates. Sounds simple enough.
The Problem:
I could not get this to work:
if (chosen_text == guess_text):
Even though I'm 100% sure (via print chosen_text) that I guessed it right.
What I Tried:
I tried reversing the order, putting str() around them, and even reversing the flow of the if and else, using is instead of ==, and removing the tries function, fwiw.
Nothing could get it to go true...
...unless I hard-code chosen_text, and guess that correctly.
Am I missing something?

You probably want to insert some debugging code:
print repr(chosen_text)
print repr(guess_text)
This will show you exactly what two strings you are dealing with. The repr function will put quotes around the strings, and let you identify whether there are unexpected spaces or other difficult-to-see issues with your strings.
If there are, you might try something like:
if chosen_text.strip() == guess_text.strip():
print "Congratulations! You guessed correctly!"
Or if there are differing capitalizations:
if chosen_text.strip().lower() == guess_text.strip().lower():
print "Congratulations! You guessed correctly!"
There are some other things you could do to make your code more Pythonic / more in the Python idiom. For example:
while game_running == True:
is better stated as:
while game_running:
But those few other cleanups are stylistic, and not related to your comparison difficulty.

Related

Exiting a python application for 'GAME OVER'

I would like to know why this code does not work; it should exit at the "GAME OVER" point, but it continues to my next defined function.
I have tried other variations on exit() such as: sys.exit(), quit() and SystemExit.
run_attack = input("What do you do: Run/Attack\n")
run = ['run', 'Run', 'RUN']
attack = ['attack', 'Attack', 'ATTACK']
run_attack = 1
while run_attack < 10:
if run_attack == ("run") or ("Run") or ("RUN"):
print ("You turn to run from the wolf but he quickly pounces
you...")
time.sleep(2)
print("You are quickly ripped apart and just about get to see
yourself be eaten.")
print("GAME OVER")
break
exit() #This is where the game should exit, yet after input it
continues to the next function
elif run_attack == ("attack") or ("Attack") or ("ATTACK"):
print("You brace yourself for a bite and have no time to reach"
"for any kind of weapon form your backpack.")
time.sleep("2")
input("You clock the dog hard, twice on the muzzle.")
print("The dog recoils in pain and retreats back to the woods.")
print("You quickly start running as you assume there will be a den in the woods.")
break
else:
input("Type Run or Attack...")
You have several problems in your code; why did you write this much without testing it?
First, you read the user's input, immediately replace is with 1, and then try to test it (incorrectly) as if it were still a string. Your posted code has several syntax errors, so I have some trouble reproducing the problem. However, the immediately obvious problem is here:
break
exit() # This is where ...
You can't get to the exit statement, as you break from the loop just before you can get there.
I strongly recommend that you back up to a few lines and use incremental programming: write a few lines at a time, debug those, and don't continue until they do what you want.
Also look up how to test a variable against various values. Your if statement is incorrect. Instead, try the list inclusion you're trying to set up:
if run_attack in run:
...
elif run_attack in attack:
...
I took the liberty of rewriting your whole program to show you a few things wrong with it and a few tricks. I've done it without the loop, since you never use it anyway... you can add the while loop later once you've mastered it, but you should really go back to basics on some things here:
run_attack = input("What do you do: Run/Attack\n")
if run_attack.lower() == "run":
print("""some
stuff
with
multiple
lines and GAME OVER""")
exit()
elif run_attack in ("attack", "Attack", "ATTACK"):
print("""some
stuff
with
multiple
lines""")
else:
input("Type Run or Attack...")
Some notes:
Using """ for strings enables you to write multiple lines without multiple print statements
Using str.lower() on strings makes everything easy to compare because you only have to compare it to the lowercase version of each string. However for attack you can notice I used a different inclusion test, without multiple conditions. Either way works here.
Like the other answer here (and many comments), you should use only exit() to leave the program entirely, or only break to exit the loop and continue to other code that's beneath the entire loop.
When you rewrite your loop, with a condition like while number_of_turns < 10 don't forget to add 1 to the number of turns on each loop, otherwise that condition is always True and you'll have an infinite loop...
I'm actually quite surprised this code had any resemblance to the behavior you expected from it, my suggestion is to go back over to the basics of python, learn loops, string methods, basic commands. The rest is already said in the other answer here (which is better than mine, frankly) just wanted to add some ideas.

Python: Break statements for while blocks

import random
def get_num ():
return random.randrange (999,9999)
print ("{}".format (get_num ()))
def get_user_input():
while True:
user_input = input
print("Please enter a four digit number")
return user_input
if False:
print ("Length of string:" , len (str))
Here in this piece of coding I am trying to make a random 4 digit number which will tell user whether or not s/he has guessed the right number (essentially),
specifically though: It will tell the user (at the end of the game) if s/he has guessed certain digits correctly but not which position.
I want 'break' statement to be fitted into this which will separate the while block from the if False. How do I do this correctly? I have tried maany times but I have 4 problems:
1- I don't know where to insert the break
2- When I run the program it doesn't print the second print function.
3- When I run the program it doesn't tell me the length of the string so I don't know if the user is even enterring the correct number of digits.
4- How do I set a limit on python (i.e. how many goes a player can have before the game ends?
I guess you are new to programming and this may be one of your very first codes. It would be great if you start by learning syntax of programming language which you have decided to use as well as working of loops, return statements, etc. I personally preferred reading any basic programming language book. For your case, it would be any book of python which is for beginners. For the sake of completeness, i have added the below code which is probably not exactly what you asked for:
import random
def get_num():
return random.randrange (999,9999)
def get_user_input():
user_input = int(input())
return user_input
while True:
comp_num = get_num()
print("The computer gave: {}".format(comp_num))
print("Your turn:")
user_num = get_user_input()
if user_num == comp_num:
print("Done it!")
break
else:
print("No, it's different. Try again!")
print()
In the above code, there are two functions and a while loop. One of the functions takes input from the user while the other generates a random number. The while loop is set to run for infinite iterations in case the user doesn't give the same input as the computer. As soon as the user gives the same input as the computer (which is displayed on the screen before he is asked to give input), the if condition evaluates to true, some things are printed and the break statement breaks the loop. And since, there is no further code, the program terminates

How would I put an if statement inside a function?

I am very very new to Python and before this I only used extremely simple "programming" languages with labels and gotos. I am trying to make this code work in Sikuli:
http://i.imgur.com/gbtdMZF.png
Basically I want it to loop the if statement until any of the images is found, and if one of them is found, it executes the right function and starts looping again until it detects a new command.
I have been looking for tutorials and documentation, but I'm really lost. I think my mind is too busy trying to go from a goto/label to an organized programming language.
If someone could give me an example, I would appreciate it a lot!
In Python indentation matters, your code should look like this:
def function():
if condition1:
reaction1()
elif condition2:
reaction2()
else:
deafult_reaction()
I recommend reading the chapter about indentation in Dive Into Python as well as PEP 0008.
x = input( "please enter the variable")
print(" the Variable entered is " + x)
myfloat = int(x)
def compare (num):
if num%2 == 0:
print(" entered variable is even")
else:
print("entered variable is odd")
compare(myfloat)

While loop issues in Python

I'm trying to write a small Python program for use in secondary schools to teach about ciphers.
It's all part of an ongoing project they have to do.
However on my while loops I have an if condition inside them and if the condition isn't met the first time it just infinitely loops until I break.
while esc == False:
if guess != cipher:
print("ERROR: INCORRECT CIPHER:" + Decrypt(guess, enc))
pass
else:
esc = True
print("Correct Cipher! Decryption successful:" + Decrypt(guess, enc))
The cipher here is 12 and if that is input it carries on as normal, however any other input just gives the error message and loops out forever.
I'm from a C#/C++ background usually and I know Python needs to be in line with its tab characters and white space and I've checked that a few times but I'm at a loss now.
ADDITIONAL CODE:
This works fine and It's done the same way
while esc == False:
if CheckPassword(pw) == True:
print("Authorisation successful.")
esc = True
else:
pw = input("Password = : ")
ADDITIONAL PLACES WHERE SAME PROBLEM HAPPENS:
while esc == False:
if attempts < 1:
esc = True
GameOver()
elif x == "USERS":
print("USERS UNAVAILABLE.")
attempts = RemoveAttempt(attempts)
pass
I'm not sure what else you are expecting to happen. If the guess is incorrect once you get into the while loop, it is going to always be incorrect, because you never ask the user for another guess. Note that in the one that does work, the else clause has an input for a new password: you don't do that in either of your non-working examples.
(Also I think you might be confused about what pass does: it's simply a no-op, ie it does nothing at all, and is only useful where you syntactically need a statement but don't want to do anything. That's not the case in either of the places you use it, so you should remove it. Unless you perhaps meant break instead, to break out of the loop?)

English command [text RPG] - python

I am creating a text-RPG taking inspiration from older text adventures where the player enters an English command; such as 'pick up sword' and the like.
I have established a simple; enter 'A' to do this and enter 'B' to do this, but I would like to expand my system for more freedom.
I need to create a system that; when the player types in a command the program picks out key words.
I assume this would be achievable via the 'in' command.
Here is my code:
print "What would you like to do??"
input_loop_sleep = str('')
choice_sleep = raw_input(str('>>>'))
loop_sleep = False
table_time = False
bed_time = False
error_time = False
while loop_sleep == False:
if str('sleep') in choice_sleep or str('bed') in choice_sleep or str('goodnight') in choice_sleep or str('Sleep') in choice_sleep or str('tired') in choice_sleep:
while bed_time == False:
print "you decide to go back to sleep"
time.sleep(1)
print "..."
time.sleep(1)
print ""
time.sleep(1)
print "darkness"
time.sleep(1)
print ""
print "you wake up..."
time.sleep(1)
print "it is now 9:15am"
time == int(9.15)
time.sleep(1)
print "You are standing in your room, slightly more refreshed."
time.sleep(1)
print "there is a table with some things on it, stairs, and a wardrobe... with the doors wide open..."
time.sleep(1)
print "that's strange... you swear that they were shut when you went to sleep..."
break
else:
bed_time == True
break
bed_loop_choice = raw_input('>>>')
elif str('bedside') in choice_sleep or str('table') in str(choice_sleep):
while table_time == False:
print "You rub your eyes and pick up some belongings from a"
print "bedside table."
time.sleep(1)
print "Map added!"
time.sleep(1)
print "100 gold added!"
time.sleep(1)
print "Leather Bag added!"
cash == int(100)
time.sleep(1)
Map == str('map of', str(province))
Inventory == [str(Map)]
container == str('leather bag')
print "your", str(container), str("contains a"), str(Map), str('and'), str(cash)
break
else:
table_time == True
break
else:
print "invalid command!"
when I run the code, no matter what I type in it always goes with the 'sleep' option.
I probably just made some simple mistake!
can you please help me with what I did wrong and how I can fix it.
To answer your question about why the sleep loop is repeated all the time:
You're controlling the loop via
while bed_time == False:
but you never set bed_time to True in your loop (only in the else clause, but that clause is only executed when the loop exits normally, not when it's exited via break, as you're now doing - therefore bed_time will never change).
Furthermore, direct comparisons to a boolean value are usually frowned upon. The idiomatic way (in most languages, not just Python) would be while not bedtime:.
You should probably read some beginners' programming books and/or the Python tutorial before embarking on such a big project. There are several issues in your code that convey the impression that you really need to get a grasp on some basic programming principles and Python idioms.
For example,
int(9.15)
is not a good way to store a time - the result will be 9.
You're then using time == int(9.15), which means "compare the module time to the integer 9". I guess you meant time = int(9.15) which is already bad for the reasons stated above, but there would be even another problem: You would be overwriting the module name time, which will cause the subsequent time.sleep(1) command to fail with an AttributeError.
There's no need for most str() calls in your code because you're using it on objects that already are strings. Where you're not, it's incorrect: str('map of', str(province)) will raise TypeError (str takes only one argument).
You're using uppercase variable names for objects that aren't class instances.
Etc., etc...
I think this should be sufficient to sort out the problem
In [1]: str('bed') in "bedside"
Out[1]: True
So when you write bedside it gets inside the sleep option if condition and hence you are getting wrong answer .
You should write :
if str('bed') == choice_sleep or *other conditions* :
then got inside the sleep option
P.S: I am assuming you have imported the time module .
P.P.S: I checked the code with entering table it is working fine .

Categories

Resources