I have to create this basic game for a high school project. I'm new to the timer in python. My code is as follows:
import random
from threading import Timer
score = -1
directions = ["RIGHT", "LEFT", "UP", "DOWN"]
accdirection=random.choice(directions)
def timeOut():
out_of_time = "yes"
print("TESTING ")
while accdirection:
TimeLimit = 1
score = score + 1
accdirection=random.choice(directions)
print(accdirection)
out_of_time = "no"
t=Timer(TimeLimit,timeOut)
t.start()
fast = input()
if out_of_time == "yes":
accdirection = None
if accdirection in directions:
t.cancel()
if accdirection == "RIGHT":
if fast == "d":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
elif accdirection == "LEFT":
if fast == "a":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
elif accdirection == "UP":
if fast == "w":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
elif accdirection == "DOWN":
if fast == "s":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
else:
print("Oof, too slow!")
accdirection = None
print("Your score is:", score)
The function of the code is that python outputs a direction, and then the user has to input w, a, s or d. If they get the wrong key, the game is over and they have lost. This part works fine.
When the time runs out it prints out "TESTING" which I have done simply to test if it even goes to the timeOut function. However, it feels like the value of out_of_time seems to always stay the same: "no" in this case. Therefore, the value for accdirection isn't able to reset to None to break the loop. I'm sorry if most of the code is just useless to my question. Please tell me how to fix this.
You set out_of_time = "yes" in the timeOut function, but never return the updated value of out_of_time.
And out_of_time is initially set in the global namespace, so indicate that, and you should get your expected behavior:
def timeOut():
global out_of_time
out_of_time = "yes"
print("TESTING ")
return out_of_time
Related
Whenever I run this is get:
Traceback (most recent call last):
File "main.py", line 130, in <module>
while is_playing_cg:
NameError: name 'is_playing_cg' is not defined
I want the user to be able to press 1 or 2 to select which game mode to use and then once pressed it starts. I don't know why it's doing this. Whenever it's fixed it should run through just fine.
New edit
Now it just loops and says 1 or 2 over and over again.
import random
is_playing_cg = False
is_playing_hg = False
def game_select_screen():
#Game Select Screen
print("""
._________________________________.
| |
| ~ Welcome To Guess-A-Number ~ |
| ~~~ |
| ~ Press 1 OR Press 2 ~ |
| You ^ Guess | PC ^ Guess |
|_________________________________|""")
selecting = True
while selecting:
print()
game_mode = input("1 OR 2: ")
try:
int(game_mode)
except ValueError:
print("This is not a Number.")
else:
game_mode = int(game_mode)
if game_mode == 1:
is_playing_hg = True
elif game_mode == 2:
is_playing_cg = True
#Defining Random Number for human guess
def play_human_guess():
num = random.randint (1,10)
print()
print("Im Thinking of a Number 1 Through 10.")
print("You Have 3 Chances.")
chances = 3
game_fisnished = False
#Game is playing (Human Guesses)
while not game_fisnished:
guess = input("> Take A Guess: ")
#Accept only numbers
try:
int(guess)
except ValueError:
print("This is not a Number.")
else:
guess = int(guess)
if guess < num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too Low. ("+str(chances)+") Chance(s) Remaining.")
elif guess > num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too High. ("+str(chances)+") Chance(s) Remaining.")
else:
print()
print("Congradulations, You Won!")
game_fisnished = True
#Game Ended
def end():
print()
print("Thanks For Playing!")
#Setting up for computer guess
def play_computer_guess():
print()
print("Pick a Number 1 Through 10")
print("I Have 3 Chances to Guess Your Number.")
chances = 3
game_fisnished = False
#Game is playing (Computer Guess)
while not game_fisnished:
guess1 = input("Is your number 5?")
#Show Game Select Screen
game_select_screen()
while is_playing_cg:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while is_playing_hg:
#Start Game
selecting = False
play_human_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_hg = False
end()
The variable is_playing_cg is only available in the "block" that creates it.
Block is function / loop / if statement / etc.
In your program you need to initialize the variable globally so you can call them in multiple functions.
Good luck!
You are defining is_playing_cg inside of a conditional statement at the top of your code. So if that option is not selected, then when you get to the latter conditional statement, it has never heard of that variable.... and it is not defined in the namespace. So you could either define it at the top and give it a default (False) or more better, because you only have 2 options, just use one variable to control the computer / human.
Here is a toy example:
selection = int(input('enter 1 for human, 2 for computer: '))
if selection == 1:
human_play = True
elif selection == 2:
human_play = False
else:
# make some loop that asks for input again or such...
pass
# later on...
if human_play:
# ask human for input...
else:
# have AI make turn
#if needed, you can also handle special cases like this:
if not human_play:
# do something unique to computer turn ...
Additional info...
So you got bit by the scope of the variables in your update. You are defining these variables inside of a function and when you put the defaults outside of the function, they are not in the same scope, so whatever you do inside the function is lost. So, you need to change your function into something that returns the mode you want, and catch that in the function call like such:
def ... :
# input ...
if game_mode == 1:
human_playing = True
selecting = False
elif game_mode == 2:
human_playing = False
selecting = False
return human_playing # this will return T/F back to the function call
And then later:
#Show Game Select Screen
human_playing = game_select_screen()
while not human_playing:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while human_playing:
#Start Game
This (above) works for me, but there are still other logic errors popping up! :) Have fun
This particular error is probably there because you have not defined is_playing_cg as global before using it in your function game_select_screen. Simply put global is_playing_cg at the start of your game_select_screen function to tell python you want to use the global variable instead of creating a scoped variable.
d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in d.items():
userinput == (input(color_key))
if userinput == (d[color_key]):
print("correct")
else:
print("wrong")
Hi everyone, i am trying to simulate a quiz with this dictionary. I want to iterate through the dictionary and prompt the user for the questions (which is the key) (i.e what is the number for the colour: color_key). I then want the user to put the value for the key that corresponds to the right colour.
I am getting this error:
userinput == input(color_key)
NameError: name 'userinput' is not defined
Can anyone help me please.
Based on assumptions that you want to make kind of "memory" game with colors and integers, code proposal for your game would be something like this:
import random
d = {'Red': 1, 'Green': 2, 'Blue': 3}
while 1==1:
rand1 = random.choice(list(d))
user_input = input("Please guess the code of "+rand1+" color:\n")
try:
int(user_input)
if(int(user_input) == d[rand1]):
print("Color code is correct!")
else:
print("Color code is incorrect!")
except ValueError:
if(user_input.lower() == "quit"):
print("Program will terminate now")
else:
print("Invalid input provided.")
Take in consideration few things important for these kind of exercises:
Despite python is not strictly typizied language, you have to take
care of exceptions in the user input
"While 1==1" generates something
called "dead loop". Make sure you always have exit condition for this
one - In our case out here, that is keyword "quit" on the input.
In case of keyword "quit" on the input, it has to be validated for both
upper and lowercase
EDIT:
According to your newest update, I am providing you the example of simple 3-operations based game:
import random
def detect_string_operation(elem1, elem2, operator):
result = ""
if(operator == "+"):
result = str(elem1 + elem2)
elif(operator == "-"):
result = str(elem1 - elem2)
elif(operator == "*"):
result = str(elem1 * elem2)
elif(operator == "/"):
result = str(elem1/elem2)
return result
operators_list = ["+", "-", "*"]
while 1==1:
elem1 = random.randint(0, 10)
elem2 = random.randint(0, 10)
operator_index = random.randint(0, len(operators_list)-1)
result_operation = detect_string_operation(elem1, elem2, operators_list[operator_index])
user_input = input("Please calculate following: "+str(elem1)+str(operators_list[operator_index])+str(elem2)+"=")
try:
int(user_input)
if(user_input == result_operation):
print("Result is correct!")
else:
print("Result is incorrect!")
except ValueError:
if(user_input.lower() == "quit"):
print("Program will terminate now")
break
else:
print("Invalid input provided.")
Note that I didn't implement division for a reason: for division totally random choice of values is not an option, since we need an integer as a result of division. Algorithm for generating divisor and divider pair is quite simple to be implemented in iterative way, but it is out of scope of your initial question.
Its showing"line 42, in
if input_ !='no':
NameError: name 'input_' is not defined" error when i input 'no'
The code is :
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
input_=input(y+z+"?")
if input_ == "no":
return
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
How can i rectify it? (this is just a small part of the entire program but i think this should do...)
Variable input_ is initialised inside function rock_paper_scissors() which means outside of it (function scope) is undefined. So we need to put it inside function or make input_ global.
def rock_paper_scissors():
comp_score = your_score = 0
y, z = "This is a rock paper scissors game. ", "Do you wish to play"
x= ["rock", "paper", "scissors"]
input_=input(y + z + "?")
if input_ == "no":
return
else: # no need for: if input_ != "no"
a = input("Do you wanna play again?")
rock_paper_scissors()
Hope this helps.
Here is my take on it, still needs some work, it functional...
# Tested via Python 3.7.4 - 64bit, Windows 10
# Author: Dean Van Greunen
# License: I dont care, do what you want
####################################
# Some Defines
####################################
# imports
import random
# global vars
comp_score = 0
your_score = 0
input_ = ''
ai_input = ''
# strings
string_1 = 'This is a rockpaper scissors game.'
question_1 = 'Do you wish to play? '
question_2 = 'Enter your move: '
question_3 = 'Do you wanna play again? '
string_4 = 'Valid Moves: '
string_5 = 'Thank you for playing!'
string_6 = 'Scores: Player {0} V.S. AI {1}'
yes = 'yes'
no = 'no'
# vaild moves
moves = ["rock","paper","scissors"]
####################################
# Code Setup
####################################
def displayWinner(player_move_str, ai_move_str):
# Vars
winner = ''
tie = False
# Winner Logic
if player_move_str == ai_move_str:
tie = True
elif player_move_str == 'paper' and ai_move_str == 'rock':
winner = 'Player'
elif player_move_str == 'scissor' and ai_move_str == 'rock':
winner = 'AI'
elif player_move_str == 'rock' and ai_move_str == 'paper':
winner = 'AI'
elif player_move_str == 'scissor' and ai_move_str == 'paper':
winner = 'Player'
elif player_move_str == 'rock' and ai_move_str == 'scissor':
winner = 'Player'
elif player_move_str == 'paper' and ai_move_str == 'scissor':
winner = 'AI'
# display Logic
if tie:
print('It Was A Tie!')
else:
global your_score
global comp_score
if winner == 'AI':
comp_score = comp_score + 1
elif winner == 'Player':
your_score = your_score + 1
print(winner + ' Won!')
def start():
global your_score
global comp_score
print(string_1)
print(string_6.format(your_score, comp_score))
input_ = input(question_1)
if input_ == yes:
print(string_4)
[print(x) for x in moves]# make sure input is valid.
input_ = input(question_2)
ai_input = random.choice(moves) # let AI pick move
print('AI Picked: ' + ai_input)
displayWinner(input_, ai_input)
input_ = input(question_3) # Play Again?
if input_ == yes:
start() # Restart Game (Recursive Call)
else:
print(string_5) # Thank you Message
####################################
# Game/Script Entry Point/Function
####################################
start()
Thanks yall. Fixed my program. Now it goes like:
import time
import random
input_ =""
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
global input_
input_=input(y+z+"?")
if input_ == "no":
return
max_score=("Enter max score : ")
while True:
input_=input("Enter your choice among rock, paper and scissors ('stop' to
quit):")
if input_ not in x and input_!='stop'and input_ != 'enough':
print("Invalid answer. Are you blind? Pick one from the 3.")
continue
n = random.randint(0,2)
k=x[n]
if n<2:
if input_==x[n+1]:
your_score+=1
elif input_==k:
pass
else:
comp_score+=1
else:
if input_=="paper":
comp_score+=1
elif input_=="rock":
your_score+=1
elif input_=="scissors":
pass
else:
pass
if input_!="stop" and input_ != "enough":
print(3)
time.sleep(1.5)
print(2)
time.sleep(1.5)
print(1)
time.sleep(1.5)
print("Your choice : "+input_ +"\nComputers move : "+k)
elif input_=="stop" and input_=="enough":
input_=input("Play again?")
if (your_score == max_score or comp_score==max_score) or (input_=="stop"
or input_=="enough"):
print("Your score is : ",your_score)
print("AI's score is : ",comp_score)
break
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
if a =="yes":
rock_paper_scissors()
print("k.bye! \n :(")
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!
Working on Python 3.4.3
Let's say I have created three fuctions:
def choosing(mylist=[]):
print("We will have to make a list of choices")
appending(mylist)
done = False
while(done == "False"):
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(mylist)))
done = True
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
appending(mylist)
done = False
elif(action == "Delete"):
removing(mylist)
done = False
def appending(mylist1 = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
mylist1.append(c)
print("You have inserted {} choices".format(len(mylist1)))
print("Please verify them below: ")
for x in range(0, len(mylist1)):
print(mylist1[x])
def removing(mylist2 = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
mylist2.remove(r)
print("{} successfully removed!".format(r))
Now problem is I can't just call choices() in append or remove function as choices() function will call append again and again infinitely.
So how do I get back in choices after appending or removing data in list?
As suggested by tobias_k, you should add the contents of choices() into a while loop.
I also found
some other problems:
False does not equal "False", so your while loop never runs.
You use terms like mylist, mylist1, and mylist2 - it's better to rename these to choosing_list, appending_list, and removing_list, so it's clearer.
You also shouldn't use False to define a while loop - instead, make a variable, then set it to True. When you have to stop, set it to False.
Here is the code with those problems fixed:
def appending(appending_list = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
appending_list.append(c)
print("You have inserted {} choices".format(len(appending_list)))
print("Please verify them below: ")
for x in range(0, len(appending_list)):
print(appending_list[x])
return appending_list
def removing(removing_list = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
removing_list.remove(r)
print("{} successfully removed!".format(r))
return removing_list
print("We will have to make a list of choices")
choosing_list = appending()
list_incomplete = True
while list_incomplete:
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(choosing_list)))
list_incomplete = False
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
choosing_list = appending(choosing_list)
elif(action == "Delete"):
choosing_list = removing(choosing_list)
Let me know if there's any problems with this code.