I am making a fighting system for a text-based game I am working on, and one option is to flee.
however, I want to make it so that you can only attempt to flee once. I made it so that after 1 failed attempt, the variable fleeing_attempted is set from false to true. However, python is ignoring this and letting me attempt to flee as many times as I want.
edit: I made fixes, but the result hasn't changed. here are the modifications.
fleeing_attempted = False #the first time the variable is defined
def battle():
print("What will you do?")
print("1. attack")
print("2. flee")
action = input()
if action == "1":
print("test")
elif action == "2":
fleeing = randint(1, 100)
if fleeing in range(1, 50):
print("You got away!")
elif fleeing in range(51,100):
callable(fleeing_attempted)
print("The enemy caught up!")
battle()
elif action == 2 and fleeing_attempted:
print("You already tried that!")
battle()
Take a look at the following two lines of code:
fleeing_attempted = False
if fleeing_attempted == True:
There is no chance for fleeing_attempted to ever be True at that if statement, since it is being set to False on the line above.
Without seeing the rest of your code, it is hard to tell where the fleeing_attempted=False should go but it should probably be somewhere in initialization.
elif action == "2":
fleeing = randint(1, 100)
fleeing_attempted = False < --- Your problem is here.
if fleeing_attempted == True:
You set it to False before you do the if check, so it will never be True.
You can also do:
if fleeing_attempted:
to test if it's true.
You can also clean up your code with and
elif action == "2" and fleeing_attempted :
# rest of code
Cleaned Code:
def have_battle():
action = input("What will you do?")
print("1. Attack")
print("2.Flee")
if action == "1":
print("You choose to attack")
elif action == "2":
# do your random check
fleeing = random.randint(0, 100)
print("fleeing variable: {0}", fleeing)
if fleeing in range (1,50):
print("You choose to flee")
You had some major problems, but I cleaned up some it and you should be able to work off it.
Related
I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)
You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()
Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.
So Im making the trade system on Monopoly using numbers. For example, if I want to add something, I input the number 1, if I want to remove something, I input the number 2, etc. My problem is, if I exit out the while loop, basically the code "break", that previous input to break also activates the main menu's if commands as well. If your confused what I am trying to say, I don't know if I'm allowed to post links on this website, but the link is:
https://repl.it/#BrentTersol/Monopoly-Official
if Action == 2 :
while True:
replit.clear()
print("What would you like to give?\n1: Add\n2: Remove\n3: Clear\n4: Offer Trade\n5: Cancel\n6: Switch")
Action = int(input(">>> "))
if Action == 1:
while True:
replit.clear()
print("What would you like to add?\n1: Money\n2: Property\n3: Jail Free Card\n4: Back")
Action = int(input(">>> "))
if Action == 1:
if Turn == 1:
while True:
replit.clear()
print("How much money do you want to give for the trade?\nMoney:",str(Player1Money))
Action = int(input(">>> "))
if Action >= 0 and Action <= (Player1Money):
TMoney1 = (Action)
print("You added $"+str(TMoney1),"to the trade")
time.sleep(2)
break
else:
print("You do not have enough money")
break
if Turn == 2:
while True:
replit.clear()
print("How much money do you want to give for the trade?\nMoney:",str(Player2Money))
Action = int(input(">>> "))
if Action >= 0 and Action <= (Player2Money):
TMoney2 = (Action)
print("You added $"+str(TMoney2),"to the trade")
time.sleep(2)
break
if Action == "back":
break
else:
print("You do not have enough money")
break
if Action == 2:
while True:
replit.clear()
if Turn == 1:
print(Inventory1)
if Turn == 2:
print(Inventory2)
print("What property do you want to give?")
Action = int(input(">>> "))
if Turn == 1:
if (Action) in (Inventory1):
TProperty1.append((Action))
print("Added",(Action),"to the trade")
time.sleep(2)
break
else:
print("Item not found in your properties")
time.sleep(2)
break
if Turn == 2:
if (Action) in (Inventory2):
TProperty2 = (Action)
print("Added",(Action),"to the trade")
time.sleep(2)
break
else:
print("Item not found in your properties")
time.sleep(2)
break
if Action == 3:
if Turn == 1:
if JailCard1 == 1:
TCard1 = 1
print("Added Jail Free Card to the trade.")
time.sleep(2)
else:
print("You do not own a Jail Free Card")
time.sleep(2)
if Turn == 2:
if JailCard2 == 1:
TCard1 = 1
print("Added Jail Free Card to the trade.")
time.sleep(2)
else:
print("You do not own a Jail Free Card")
time.sleep(2)
if Action == 4:
break
if Action == 2:
while True:
replit.clear()
print("What would you like to remove?\n1: Money\n2: Property\n3: Jail Free Card\n4: Back")
Action = int(input(">>> "))
if Action == 1:
while True:
replit.clear()
if Turn == 1:
if TMoney1 == 0:
print("There wasn't any money to remove")
time.sleep(2)
else:
TMoney1 = 0
print("Removed Cash from offer")
time.sleep(2)
break
if Action == 2:
while True:
replit.clear()
print(TProperty1)
print("What property would you like to remove")
Action = input(">>> ")
Action = Action.lower()
if Turn == 1:
if Action == "back":
break
if (Action) in (TProperty1):
TProperty1.remove((Action))
print("Removed",(TProperty1),"from trade")
time.sleep(2)
break
else:
print("That item did not exist")
time.sleep(2)
if Turn == 2:
if (Action) in (TProperty2):
TProperty2.remove((Action))
print("Removed",(TProperty2),"from trade")
time.sleep(2)
else:
print("That item did not exist")
time.sleep(2)
if Action == 3:
if Turn == 1:
if JailCard1 == 1:
print("Removed Jail Free Card from trade")
TCard1 = 0
break
else:
print("Card does not exist in trade")
if Turn == 2:
if JailCard2 == 1:
print("Removed Jail Free Card from trade")
TCard2 = 0
break
else:
print("Card does not exist in trade")
if Action == 4:
break
if Action == 3:
TMoney1 = 0
TMoney2 = 0
TProperty1.clear()
TProperty2.clear()
TCard1 = 0
TCard2 = 0
if Action == 4:
if Turn == 1:
while True:
print("This is what",(Name1),"offers:\n--------------------")
time.sleep(2)
print("You get:\nMoney:",(TMoney1),"\nProperty:",(TProperty1),"\nGet out of Jail Free Card:",(TCard1),"\n")
time.sleep(2)
print("You give",(Name1)+":\nMoney:",(TMoney2),"\nProperty:",(TProperty2),"\nGet out of Jail Free Card:",(TCard2),"\n")
time.sleep(2)
print("Do you accept this Offer? (Y/N):")
Action = input(">>> ")
Action = Action.lower()
if Action == "y":
print("This is beyond what I can do at this point. Very sorry you took a long time not knowing that it wouldnt work. But this will soon be fixed as soon as I know how to do this")
time.sleep(5)
else:
print("Trade has been rejected")
time.sleep(2)
break
if Action == 5:
if Turn == 1:
Turn = 2
else:
Turn = 1
if Action == 6:
print("This is beyond what I can do. Please wait until I learn how to do this. Thank you.")
You should implement a single While True loop and that will reset the user input each loop (so long as you overwrite it inside the loop)! I would also advise you recreate your code into functions instead of several nested logic statements. An example of code that gets user input each loop (in the terms of your question clears user input):
while True:
big_prompt = """What would you like to do?
1) say hi
2) say bye
3) pay taxes
4) ???
5) profit
6) Exit D:"""
action = input(big_prompt) # reset user input each loop
if action not in ["1", "2", "3", "4", "5", "6"]:
print("Sorry I didn't understand that")
continue # get a new user input
# at this point we know user input fits our criteria
if action == "1":
print("Hi!")
elif action == "2":
print("Bye!")
# ... you should be putting function calls in these for more complex tasks
elif action == "6":
break # this only exits one loop, I think you are trying to use it to
With sample output:
What would you like to do?
1) say hi
2) say bye
3) pay taxes
4) ???
5) profit
6) Exit D:
>>>1
Hi!
What would you like to do?
1) say hi
2) say bye
3) pay taxes
4) ???
5) profit
6) Exit D:
>>>6
Process finished with exit code 0
It also might be a good idea to review The Zen of Python by opening an interactive terminal and running import this:
>>>import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Where of special note we find a couple things that apply here:
Flat is better than nested.
Readability counts.
Maintaining a single while loop greatly helps both of these. At one point in your code you get trapped inside 3 while True: loops and then try to break multiple with a single break, but will always stay trapped at least 2 levels deep...
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 4 years ago.
I've been driving myself insane trying to troubleshoot and fix this. I cerated this dice rolling game with bets. I'm pretty new to coding, so I'm sure it's a simple error that I just keep overlooking.
The only issue is that it will not end the game if the user inputs "no".
The function doesn't return any errors. It runs and even prints GAME OVER before it returns the values used to find out if the player wants to play another round.
What happens is that it prints the game over, and then loops the diceRoll function without stopping it.
Picture uploaded to show what I mean.
And the code:
#pylint:disable=W0312
#python 3.6
from random import randint
import math
# Static Variables
START_BALANCE = 2500
# Game messages
BAD_GUESS = "ERROR! You can only enter a number between 1 and 6.\n- Your input was '{}'.\n"
BAD_BET = "ERROR! You can not bet less than 0 or more than your current balance {}$.\n"
userName = input("What is your name, player?\n").title()
print("Hello, {}! Welcome to the dice rolling game v.2!\n".format(userName))
def get_guess():
try:
guess = input("Enter a guess from 1 to 6, {}\n".format(userName))
guess = int(guess)
while (guess <= 0 or guess > 6):
print(BAD_GUESS.format(guess))
return get_guess()
except ValueError:
print(BAD_GUESS.format(guess))
return get_guess()
else:
print("Your guess is: {}.".format(guess))
return guess
def get_bet(balance):
try:
bet = input("\nHow much do you want to bet? Your balance is: {}$\n".format(balance))
bet = int(bet)
while (balance < bet) or (bet < 0):
print(BAD_BET.format(balance))
return get_bet(balance)
except ValueError:
print(BAD_BET.format(balance))
return get_bet(balance)
else:
print("You have bet {}$!\n- Your remaining balance is: {}$".format(bet, balance - bet))
return bet
#### FUNC START ####
def diceRoll(balance):
bet = get_bet(balance)
guess = get_guess()
balance -= bet
roll = randint(1,6)
if (roll == guess):
prize = bet * float(3.75)
prize = math.ceil(prize)
balance += prize
print("\nYOU WIN {}$!".format(prize))
print("You guessed: {} - The roll was {}!\n".format(guess, roll))
print("-- Your balance is now {}$ -- \n".format(balance))
elif (roll != guess):
print("\nYOU LOSE {}$".format(bet))
print("The roll was: {} - You guessed: {}.".format(roll,guess))
print("-- Your balance is now {}$ --\n".format(balance))
#
choice = input("Would you like to try again? Y/N\n").upper()
#
if (balance <= 0 or choice == "YES" or "Y"):
print("New round! Your balance is {}$".format(balance))
return [True, balance]
else:
print("GAME OVER! \n Balance: {}$".format(balance))
return [False, balance]
# Initialize game_state, which is a variable that keeps track of your rounds and balance.
game_state = [True, START_BALANCE]
# game_state[0] contains True if the user wants to play again, False if not.
# So if it's false, while (game_state[0]) will evaluate to false and stop the while loop.
while game_state[0]:
game_state = diceRoll(game_state[1])
# TODO: Build a while loop that executes any time the first item in game_state is True (i.e., while the
# user still wants to play a new round. Note that I initialized game_state[0] to True, assuming that
# if they started the program, they want to play the first round.
Inside diceRoll() function this should be changed from:
if (balance <= 0 or choice == "YES" or "Y")
to
if (balance <= 0 or choice == "YES" or choice == "Y")
to properly compare with the choice value.
In your case to make it clearer you are having 3 condition:
balance <= 0
choice == "YES"
"Y"
with the third one being always True. It doesn't check if choice has Y value but if the string provided "Y" in your case is equal to None or not and obviously it's not so it's always True.
In addition to the answers given, I recommend a list of positive choice strings and check if choice is in it.
acceptables = ["yes", "y", "yup", "yeah", "sure", "absolutely", "1", "roger"]
if (balance <= 0 or choice.lower() in acceptables)
.lower() converts the input string into lower case, so you don't have to bother about that. If you want to allow more than the examples in the above case, you can always add them as you wish. Same for, "no", "nope", "no way", "never", "0", ...
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.
I'm working on a code with python, where we've been asked to create a game of Rock, Paper, Scissors using an external file of options (rock, paper, scissors) as opposed to having the code use any user input. However, for some reason, my code doesn't work. When someone inputs "yes", it prints "Let us play now," but that's it. Nothing else happens.
Why isn't the game completing when a user provides "yes" as input?
from random import randrange
def sample():
computer_input = randrange(1,3)
return computer_input
def main():
a = []
infile = open("input2.txt", "r")
for line in infile:
a.append(line)
computer_input = sample()
tied = 0 #games tied
user_won = 0 #games won by user
comp_won = 0 #games won by computer
user_input = ""
computer_input = ""
print("Rules of the game...")
print("Would you like to turn up with a game of rock, paper, or scissors? ;) Yes or no? -->")
answer = input()
if (answer == "yes"):
play = True
print("Let us now play.")
## elif(answer == "no" or "No"):
## play = False
## print("Sorry. Maybe we can play next time ;)")
## else:
## play = False
## print("Please try again!")
## main()
while True:
if(computer_input == "1"):
if(user_input == a[0]):
tied = tied + 1
print("Game is tied!")
elif(user_input == a[1]):
user_won = user_won + 1
print("You won! Paper covers Rock")
elif(user_input == a[2]):
comp_won = comp_won + 1
print("You lost! Rocks knocks out scissors")
## else:
## print("Try again!")
elif (computer_input == "2"):
if (user_input == a[0]):
comp_won = comp_won + 1
print("You lost! Paper covers Rock")
elif(user_input == a[1]):
tied = tied + 1
print("Game is tied!")
elif(user_input == a[2]):
user_won = user_won + 1
print("You won! Scissors cuts Paper")
## else:
## print("Try again!")
else :
if(user_input == a[0]):
user_won = user_won + 1
print("You won! Rock knocks out scissors")
elif(user_input == a[1]):
comp_won = comp_won + 1
print("You lost! Scissors cuts Paper")
elif(user_input == a[2]):
tied = tied + 1
print("Game is tied!")
## else:
## print("Try again!")
##
##print("Game over")
##print("Statistics")
##print("Games tied -->", tied)
##print("Game won by comp -->", comp_won)
##print("Game won by user -->", user_won)
##
main()
Notice that on line 5 below, you set computer_input to the result of sample():
def main():
a = []
infile = open("input2.txt", "r")
for line in infile:
a.append(line)
computer_input = sample()
But then a few lines later, you set it to "":
user_input = ""
computer_input = ""
Your while loop is checking against the value of computer_input, but it assumes it will be a number. It has no case to handle the empty string. I would recommend removing that line.
Also note that your while loop is checking the value of user_input, but you never seem to actually read input into that variable.
There are many, many problems with this code.
Every time you define or use a variable, you should have a clear idea of
why it is defined this way or exactly what this use of the variable is
going to accomplish.
You have a loop, which seems to indicate that you meant for more than
one round of the game to be played when you run the code once.
But there is only one place where the computer's choice is set
to a number 1, 2, or 3, and it occurs only once.
(Besides, as has already been pointed out, then you change the
computer's choice to "" without even reading the number once.)
You have no apparent way to get out of the loop within the logic of the code.
It is unclear what you think you are supposed to be reading from the
user's input file. You put the contents of the file in the array a line
by line, but then you only ever look at a[0], a[1], and a[2].
What were the first three lines of the file supposed to contain?
Why only three lines? What does it mean to ask whether
user_input == a[0]?
(I have a hunch that you were supposed to set the user input on each
round to a member of a, not compare user_input to a member of a.)
(Also notice that you set user_input = "" earlier, so unless you read
empty strings into the entries of a, expressions like
user_input == a[0] will always be false.)
What is the point of setting play = True? (Or even setting
play = False as in the commented-out code?) You never do anything that
would read the value of play.
What is the point of keeping count in the variables tied,
user_won, and computer_won? You never read those variables either,
except when you're setting new values of them.
It might help if you write some smaller functions with very clear
purpose, input and output. The sample() function is promising, but
everything else is in main().
For example, figuring out who won, given the computer's choice and
the player's choice, could be a function.
By writing such a function you would remove dozens of lines of code from
the loop in main(), replacing them with perhaps one line of code.
It's much, much easier to write well-designed loops when
the block of code inside the loop is short.