How to stop this while loop? - python-3.x

I'm a beginner in coding and I'm making a simple rpg. I'm currently making a floor with only 4 rooms. I want the game to loop infinitely. I also want the game to prompt the player to enter a valid command when they enter an invalid command, but the while loop repeats infinitely. Can someone give me a fix that a beginner can understand, and maybe some pointers? The while loop is
while foo(move) == False:.
def foo(m):
"""
"""
if m.lower == 'l' or m.lower == 'r' or m.lower == 'help' or m.lower == 'pokemon':
return True
else:
return False
print() #Put storyline here
print("You may input 'help' to display the commands.")
print()
gamePlay = True
floor4 = ['floor 4 room 4', 'floor 4 room 3', 'floor 4 room 2', 'floor 4 room 1']
floor4feature = ['nothing here', 'nothing here', 'stairs going down', 'a Squirtle']
currentRoom = 0
pokemonGot = ['Bulbasaur']
while gamePlay == True:
print("You are on " + floor4[currentRoom] + ". You find " + floor4feature[currentRoom] + ".")
move = input("What would you like to do? ")
while foo(move) == False:
move = input("There's a time and place for everything, but not now! What would you like to do? ")
if move.lower() == 'l':
if currentRoom > 0:
currentRoom = currentRoom - 1
print("Moved to " + floor4[currentRoom] + ".")
else:
print("*Bumping noise* Looks like you can't go that way...")
elif move.lower() == 'r':
if currentRoom < len(floor4) - 1:
currentRoom = currentRoom + 1
print("Moved to " + floor4[currentRoom] + ".")
else:
print("*Bumping noise* Looks like you can't go that way...")
elif move.lower() == 'help':
print("Input 'r' to move right. Input 'l' to move left. Input 'pokemon' to see what Pokemon are on your team. Input 'help' to see the commands again.")
elif move.lower() == 'pokemon':
print("The Pokemon on your team are: " + str(pokemonGot) + ".")
print()

In foo you are comparing a function definition, m.lower, to a character. Try m.lower () to call the function.

Related

Tic Tac Toe AI Bugs plz help me fix it

I am trying to create a Tic-Tac-Toe AI that will never lose. My code works sometimes but it does not work other times. Sometimes it will find the best move and print it out correctly but other times it will just fail. For example, once the AI takes the center if you press nine and take the top right corner then the AI will take a top left corner. Then if you take the bottom right corner the AI takes the middle left tile and then if you take the middle right tile then you will win. I wanted the AI to take the middle right to stop you from winning. I am a beginner programmer so please excuse me if the code is not written in the most optimal way. Why is that? Also can you please elaborate your explanation so I can understand what is wrong? Here is the code:
the_board = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
def print_board(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])
def check_for_win(current_state_of_the_board, player_sign):
if current_state_of_the_board["7"] == current_state_of_the_board["8"] == current_state_of_the_board["9"] == player_sign:
return "Victory"
elif current_state_of_the_board["4"] == current_state_of_the_board["5"] == current_state_of_the_board["6"] == player_sign:
return "Victory"
elif current_state_of_the_board["1"] == current_state_of_the_board["2"] == current_state_of_the_board["3"] == player_sign:
return "Victory"
elif current_state_of_the_board["1"] == current_state_of_the_board["4"] == current_state_of_the_board["7"] == player_sign:
return "Victory"
elif current_state_of_the_board["2"] == current_state_of_the_board["5"] == current_state_of_the_board["8"] == player_sign:
return "Victory"
elif current_state_of_the_board["3"] == current_state_of_the_board["6"] == current_state_of_the_board["9"] == player_sign:
return "Victory"
elif current_state_of_the_board["7"] == current_state_of_the_board["5"] == current_state_of_the_board["3"] == player_sign:
return "Victory"
elif current_state_of_the_board["9"] == current_state_of_the_board["5"] == current_state_of_the_board["1"] == player_sign:
return "Victory"
else:
return "No Victory"
def get_copy_of_the_board(current_board, move, player_sign):
copy_of_the_board = current_board
if copy_of_the_board[str(move)] == " ":
copy_of_the_board[str(move)] = player_sign
return copy_of_the_board
else:
return copy_of_the_board
def check_for_computer_win():
for number in range(1, 10):
print( check_for_win(get_copy_of_the_board(the_board, number, "X"), "X"))
if check_for_win(get_copy_of_the_board(the_board, number, "X"), "X") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_player_win():
for number in range(1, 10):
print(check_for_win(get_copy_of_the_board(the_board, number, "O"), "O"))
if check_for_win(get_copy_of_the_board(the_board, number, "O"), "O") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_computer_forks():
for number in range(1, 10):
first_copy = get_copy_of_the_board(the_board, number, "X")
for second_number in range(1, 10):
if check_for_win(get_copy_of_the_board(first_copy, second_number, "X"), "X") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_player_forks():
for number in range(1, 10):
first_copy = get_copy_of_the_board(the_board, number, "O")
for second_number in range(1, 10):
if check_for_win(get_copy_of_the_board(first_copy, second_number, "O"), "O") == "Victory":
return str(number)
else:
return "Check next condition"
def get_computer_move():
if check_for_computer_win() != "Check next condition":
comp_move = check_for_computer_win()
return comp_move
else:
if check_for_player_win() != "Check next condition":
comp_move = check_for_player_win()
return comp_move
else:
if check_for_computer_forks() != "Check next condition":
comp_move = check_for_computer_forks()
return comp_move
else:
if check_for_player_forks() != "Check next condition":
comp_move = check_for_player_forks()
return comp_move
else:
for move in ["5"]:
if the_board[move] == " ":
comp_move = "5"
return comp_move
for move in ["7", "9", "1", "3"]:
if the_board[str(move)] == " ":
return move
for move in ["4", "8", "6", "2"]:
if the_board[str(move)] == " ":
return move
def game():
count = 0
turn = "computer"
while count < 9:
if turn == "computer":
print("The computer move is: ")
final_computer_move = get_computer_move()
if the_board["1"] == "O":
pass
else:
if final_computer_move == "1":
pass
else:
the_board["1"] = " "
the_board[final_computer_move] = "X"
print_board(the_board)
if check_for_win(the_board, "X") == "Victory":
print("The computer has won!")
exit()
else:
turn = "player"
count += 1
else:
player_move = input("Where would you like to move?")
the_board[player_move] = "O"
print_board(the_board)
if check_for_win(the_board, "O") == "Victory":
print("You have won!")
exit()
else:
turn = "computer"
count += 1
game()
Thanks in advance!!

How would I trigger an automatic enter key press after an Input function?

choice = input(">>")
if choice.lower() == "+":
death = death0.IncreaseDeath()
elif choice.lower() == "-":
death = death0.DecreaseDeath()
elif choice.lower() == "r":
death = death0.ResetDeath()
elif choice.lower() == "q":
sys.exit()
I have this code, but its supposed to be a death counter, where the user should jus press + or - or r or q and it increments automatically, without the user needing to press enter. I tried keyboard.press_and_release('enter') and keyboard.add_hotkey('+', death = death0.IncreaseDeath()) but 2nd one doesn't work, and second one works AFTER input finishes and user presses Enter, and now its spamming enter on the input(which isnt what i want, i want the user to type one letter and then have it press Enter automatically. How would I do this to make it happen so user doesnt need to press "Enter" after the input
if msvcrt.kbhit():
key_stroke = msvcrt.getch()
if key_stroke == b'+':
death = death0.IncreaseDeath()
elif key_stroke == b'-':
death = death0.DecreaseDeath()
elif key_stroke == b'r':
death = death0.ResetDeath()
elif key_stroke == b'q':
sys.exit()
Also tried this BUT my code before which is:
def DeathCount(death,DEATH_NAME):
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print ("####################")
print (f" {DEATH_NAME}: {death} ")
print ("####################")
print (" * + : increase * ")
print (" * - : decrease * ")
print (" * r : reset * ")
print (" * q : quit * ")
print ("####################")
doesn't show up and it gives no clue to the user what to press and whether its actually incrementing or not.
hope this code helps
import sys
from getkey import getkey
death0 = 15
death = death0
print(death)
while True:
print(">>")
choice = getkey()
if choice.lower() == "+":
death += 1
elif choice.lower() == "-":
death -= 1
elif choice.lower() == "r":
death = death0
elif choice.lower() == "q":
sys.exit()
else:
print("invalid input")
print(death)

Number guessing game that requires suggestions for completion

how do I get the difficulty level to work? I have found other codes similar but the difficulty is based on the group of number that it will choose the number from i.e. easy(1,10), medium (1,50), hard (1,100). I need to know how to make it work for the number of guesses. It keeps telling me I don't have easy,medium, or hard defined. how do I define them in way to make this code work?
I can get through it asking for my name then it will ask for the difficulty level and when I type e,m,or,h this is what it gives me: Traceback (most recent call last): File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 58, in guesses = get_guesses(level) File "C:\Users\ajohn\OneDrive - Fairmont State University\BISM3800\Assign2.py", line 50, in get_guesses if diffuculty == hard: NameError: name 'diffuculty' is not defined
here is the objectives for the code:
You are to ask the user if they wish to play the game or continue playing the game after they have guessed the number
You are to ask the user if they want easy, medium or HARD (Easy = unlimited guesses, Medium = 10 guesses, HARD = 5 guesses)
Once the game begins play you are to tell the user that you have picked a number and they are to guess what that number is
your application is to accept the players guess and if their guess is larger than the number you had picked then tell them that, if their guess is smaller then tell them that as well.
The game continues to play until the player picks the number you had originally picked or they have ran out of guesses. I also need to have an exception.
Here is my code so far:
This is a guessing the number game.
import random
this statement will allow the options for playing and quiting the game.
play = True
while play:
difficulty = 0
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
easy = random.randint (1,100)
easy = random.randint (1,100)
easy = random.randint (1,100)
prompts the user to select a difficulty to play on
def select_level():
while True:
level = str(input("Would you like to play on easy, medium, or hard? \n"
"Type 'e' for easy, 'm' for medium, or 'h' for hard!\n"))
if level != "e" and level != "m" and level != "h":
print("Invalid input!\n")
if level == "e" or level == "m" or level == "h":
break
return level
function that prompts the user to guess depending on chosen difficulty
def guess_number(level):
if level == "e":
(easy == 500)
if level == "m":
(medium == 10)
if level == "h":
(hard == 5)
return guesses
selects number of guesses depending on difficulty selected
def get_guesses(level):
if difficulty == easy:
print ("Okay, " + myName + ". You have unlimited guesses")
if difficulty == medium:
print ("Okay, " + myName + ". You have 10 guesses.")
if diffuculty == hard:
print ("Okay, " + myName + ". You have 5 guesses.")
elif level != "e" and level != "m" and level != "h":
print ("Invalid input!")
get_guesses()
return guesses
level = select_level()
guesses = get_guesses(level)
print('Well, ' + myName + ', I am thinking of a number can you guess it?')
while guessesTaken < level:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed the number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
Here's the object oriented approach :
from random import randint
class Guessing_Game () :
def __init__ (self, users_name) :
self.difficulty = 10
self.name = users_name
self.start_the_game ()
def start_the_game (self) :
my_secret_number = randint (1, self.difficulty)
print ('Well, ' + self.name + ', I am thinking of a ', end = '')
print ('between 1 and ' + str (self.difficulty) + '.')
print ('Can you guess it?')
self.guess_the_number (my_secret_number)
def guess_the_number (self, the_secret_number) :
still_playing = True
while still_playing == True :
answer = int (input ('Take a guess : '))
if answer == the_secret_number :
print ('That is exactly correct! You win!')
still_playing = False
else :
if answer > the_secret_number :
print ('Sorry, you are too high.')
if answer < the_secret_number :
print ('Sorry, you are too low.')
if self.play_again () == True :
self.start_the_game ()
def play_again (self) :
self.difficulty = self.difficulty * 2
answer = input ('Would you like to play again? ')
if answer [0].lower () == 'y' : return True
return False
users_name = input ('Please enter your name : ')
my_game = Guessing_Game (users_name)

Python number guessing game not displaying feedback correctly. What's the problem?

So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()

How can I get my game to finish when the player runs out of health?

I'm currently making a simple rogue-like dungeon game for an assignment, i'm pretty new to coding so I've run into problems along the way. I want my game to end when the player's health reaches 0 so i've written this function
def main_game():
global room_count
global player_health
welcome_text()
while player_health >= 1:
room_enter(empty_room, ghost_room, monster_room, exit_room)
else:
print("Game Over :(")
print("Number of rooms entered: ", room_count)
time.sleep(7)
quit()
For whatever reason when the health reaches 0 the game continues to carry on and I can't figure out why, it's far from finished but here's the full game code below:
import time
import random
import sys
player_health = 1
room_count = 1
def scroll_text(s):
for c in s:
sys.stdout.write( "%s" % c )
sys.stdout.flush()
time.sleep(0.03)
def welcome_text():
scroll_text("\nYou wake up and find yourself in a dungeon.")
time.sleep(1.5)
scroll_text("\nYou have no idea how long you have been trapped for.")
time.sleep(1.5)
scroll_text("\nSuddenly, one day, for no apparent reason, your cell door opens.")
time.sleep(1.5)
scroll_text("\nEven though weak from having no food, you scramble out as the door closes behind you.")
time.sleep(1.5)
scroll_text("\nYou see many paths and many rooms ahead of you.")
print("\n ")
print( "-"*20)
def room_enter(empty_room, ghost_room, monster_room, exit_room):
global player_health
global room_count
security = True
while security == True:
direction = input("\nYou have the option to go Left (l), Forward (f), or Right (r), which direction would you like to go? ")
if direction == "l" or direction == "f" or direction == "r":
security == False
room_no = random.randint(1,8)
if room_no == 1 or room_no == 2 or room_no == 3:
empty_room()
room_count = room_count + 1
if room_no == 4 or room_no == 5 or room_no == 6:
ghost_room()
room_count = room_count + 1
if room_no == 7:
monster_room()
room_count = room_count + 1
if room_no == 8:
exit_room()
room_count = room_count + 1
else:
print("\nInvalid Entry")
return player_health
def empty_room():
global player_health
scroll_text("You enter a cold empty room, doesn't look like anyone has been here in years.")
player_health = player_health - 1
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
return player_health
def ghost_room():
global player_health
scroll_text("You enter a room and feel a ghostly presence around you")
time.sleep(1)
scroll_text("\nWithout warning, the ghostly mist surrounding you pools together and the shape of a human-like figure emerges.")
time.sleep(1)
scroll_text("\nI AM THE SPIRIT OF AN UNFORTUNATE EXPLORER KILLED IN THEIR PRIME, DOOMED TO SPEND AN ETERNITY TRAPPED IN THIS CHAMBER!")
time.sleep(1)
scroll_text("\nANSWER MY QUESTION MORTAL AND CONTINUE IN PEACE, GET IT WRONG HOWEVER AND YOU WILL BE BEATEN!")
time.sleep(1)
x = random.randint(1,500)
y = random.randint(1,500)
time.sleep(1)
print("\nTELL ME WHAT", x, "PLUS", y, "IS!")
okay = False
while not okay:
try:
player_answer = int(input("\nWHAT IS YOUR ANSWER?! "))
okay = True
if player_answer == x+y:
scroll_text("\nCONGRATULATIONS YOU GOT IT CORRECT! HAVE A BIT OF HEALTH!")
player_health = player_health + 2
else:
scroll_text("\nUNFORTUNATELY FOR YOU THAT ANSWER IS WRONG! PREPARE FOR THE BEATING!")
player_health = player_health - 1
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
except ValueError:
print("\nInvalid Entry")
return player_health
def monster_room():
global player_health
scroll_text("\nYou hear grunting noises as you enter the room and your worst fears are confirmed when your eyes meet the gaze of a giant monster guarding the other doors.")
time.sleep(1)
scroll_text("\nWith no way to fight the creature, you manage to slip around it however as you are making your escape the beast swipes at you and lands a blow to your back.")
player_health = player_health - 5
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
return player_health
def exit_room():
global player_health
scroll_text("\nYou stumble into the room, almost passing out from the lack of food and energy.")
time.sleep(1)
scroll_text("\nIs that...")
time.sleep(1)
scroll_text("\n... You can't believe your eyes! It's the exit from the dungeon at last!")
time.sleep(1)
print("\nWINNER WINNER CHICKEN DINNER")
print("\n ")
print("-"*21)
print("| Final Health: ", player_health, "|")
print("-"*21)
print("Number of rooms entered: ", room_count)
return player_health
def main_game():
global room_count
global player_health
welcome_text()
while player_health >= 1:
room_enter(empty_room, ghost_room, monster_room, exit_room)
else:
print("Game Over :(")
print("Number of rooms entered: ", room_count)
time.sleep(7)
quit()
main_game()
In room_enter you have a typo - security == False instead of security = False, causing an infinite loop in room_enter, so the condition in main_game is never checked.
it is very simple,
if direction == "l" or direction == "f" or direction == "r":
security == False
you basically never set security to false. It should be
if direction == "l" or direction == "f" or direction == "r":
security = False
Btw, if you declare playerHealth to be global, you don't need to return it at the end of every function you'll have the current value anyways.
Also, I think you don't need those parameters on "room_enter" since they are just functions to be executed. If you find an error saying that they are not declared, just move the declaration above the function room_enter
Let me know if something wasn't clear! Happy coding!

Resources