I've programmed a game that takes a song and artist name from an external file. The program prints the artist name but masks the title of the song, and the user must guess the title correctly to earn points. That works fine, but I want to add a time limit, so they only have 60secs to get the highest score they possibly can.
Here's the part of the code I'm referencing:
def pickSong_random():
score=0
lives=5
songFile = open("F_Songs.txt","r")
songList = songFile.readlines() #Reads from the bridged file
songFile.close()
while True:
chosenSong = random.choice(songList)
chosenSong = chosenSong.strip("\n")
artistAndSong = chosenSong.split(":") #Defines song split
toDisplay = ""
toDisplay += artistAndSong[0] + ": "
songTitleWords = artistAndSong[1].split(" ")
for word in songTitleWords:
#loop through
toDisplay += word[0] + " "
print(toDisplay)
#print("2" +toDisplay)
toDisplay = toDisplay.strip("None")
guesses = 0
while guesses <2:
guesses += 1
guess = input("[Guess]: ")
#Guess checking
if guess.lower() == artistAndSong[1].lower():
print("Correct! The song was " + artistAndSong[1] + " by " + artistAndSong[0])
print("It took you", guesses, "guess(es)!")
if guesses == 1:
print ("(+3 points)")
print("\n")
score += 3
break
elif guesses == 2:
print ("(+1 point)")
print("\n")
score += 1
break
else:
print("That's incorrect, guess again.\n")
lives = lives-1
if lives == 0:
print ("You have no more lives to continue! Your score was:",score)
time.sleep(3)
slow_print ("Would you like to play again?")
playAgain = input("[Y/N]: ")
if playAgain == ("n") or playAgain == ("N"):
sys.exit()
if playAgain == ("Y") or playAgain == ("y"):
print ("Your last score was",score,", lets see if you can beat it this time...")
time.sleep(1)
print ("\n")
pickSong_random()
I've tried playing around with this concept, but no luck thus far:
import time
countdown=True
time=60
while countdown == True:
time = time-1
time.sleep(1.0)
print (time)
countdown=True
if time == 0:
print ("You've ran out of time!")
UPDATE 1
My projects code has now changed quite a far bit
#Casey_Neale
import sys
import random
import time
import math
import csv
import time, sys
newaccounts=True
loggedIn=False
yn=True
def tutorial(): #Games introduction
slow_print("Your aim is to get as many points as possible...")
print("\n")
time.sleep(1.5)
slow_print("You need to guess the name of each song to gain points...")
print("\n")
time.sleep(1.5)
slow_print("You have two guesses for each song...")
print("\n")
time.sleep(1.5)
slow_print ("The artist name is provided for you...")
time.sleep(0.5)
print("\n")
def slow_print(s):
for c in s:
sys.stdout.write( '%s' % c )
sys.stdout.flush()
time.sleep(0.03)
def leaderboard():
print ("\n")
print ("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
f = open('H_Highscore.txt', 'r')
leaderboard = [line.replace('\n','') for line in f.readlines()]
for i in leaderboard:
print(i)
f.close()
time.sleep(10)
sys.exit()
def loginsys():
doublecheck=True
while doublecheck == True:
verifyRegister = input ("➡Welcome | Are you a registered user?\n[Y/N]: ")
print (" ")
if verifyRegister == "n" or verifyRegister == "N": #If the user is not already registered
if newaccounts == True:
loop=True
while loop == True:
username = input ("Please enter a username\n[User]: ")#Prompts the user to provide a desired username
print (" ")#Prompts for username
checkusername = input ("Please retype your username\n[Verify]: ")#Verifys username
print (" ")#Prompts to verify username
if checkusername != username:
print ("Invalid, please try again")
loop=True
else:
loop=False
time.sleep(0.5)
passloop=True
while passloop == True:
password = input ("Please enter a password\n[Password]: ") #Prompts the user to provide a desired password
print (" ")#Prompts for password
checkpassword = input ("Please retype your password\n[Verify]: ") #Verifys password
print (" ")#Prompts to verify password
if checkpassword != password:
print ("Invalid, please try again")
print (" ")
passloop=True
else:
passloop=False
file = open("C_AccountData.txt","a") #Opens the file C_AccountData.txt in write mode/opens connection
file.write("USRN:") #Prefix Username to make the file easier to read
file.write(username) #Writes the username
file.write("|") #Partition for visual ease to make the file easier to read
file.write("PSWD:") #Prefix Password to make the file easier to read
file.write(password)#Writes the password
file.write("\n") #New line to make the file easier to read
file.close() #Closes file/ends connection
print ("✓Your account has been created") #Verifies that the account has been made to the user
time.sleep(2)
print ("\n")
doublecheck=True #Loop
if verifyRegister == "Y" or verifyRegister == "y":
loop=True
if loop == True:
user = input("[User]: ")
passw = input("[Password]: ")
f = open("C_AccountData.txt", "r")
for line in f.readlines():
uspwd = line.split("|")
us = uspwd[0]
pw = uspwd[1]
if (user in us) and (passw in pw):
loop=False
print("Login successful, welcome",user)
doublecheck=False
else:
if loop == True:
print ("\n")
print ("Sorry, your account details were not recognised. ")
else:
if verifyRegister != "Y" or verifyRegister != "y" or verifyRegister != "N" or verifyRegister != "n" or verifyRegister !="backup":
print("\n")
doublecheck=True
def pickSong_random():
score=0
lives=5
songFile = open("F_Songs.txt","r")
songList = songFile.readlines() #Reads from the bridged file
songFile.close()
while True:
chosenSong = random.choice(songList)
chosenSong = chosenSong.strip("\n")
artistAndSong = chosenSong.split(":") #Defines song split
toDisplay = ""
toDisplay += artistAndSong[0] + ": "
songTitleWords = artistAndSong[1].split(" ")
for word in songTitleWords:
#loop through
toDisplay += word[0] + " "
print(toDisplay)
#print("2" +toDisplay)
toDisplay = toDisplay.strip("None")
guesses = 0
while guesses <2:
guesses += 1
guess = input("[Enter your guess]: ")
#Guess checking
if guess.lower() == artistAndSong[1].lower():
print("✓Correct! The song was " + artistAndSong[1] + " by " + artistAndSong[0])
print("It took you", guesses, "guess(es)!")
if guesses == 1:
print ("\n")
print ("⬆(+3 points)⬆")
print("\n")
score += 3
break
elif guesses == 2:
print ("\n")
print ("⬆(+1 point)⬆")
print("\n")
score += 1
break
else:
print("❌The song name isn't",guess,"\n")
lives = lives-1
if guesses == 2:
print ("Sorry, you couldn't guess the song.")
print ("\n")
if lives == 0:
print ("You have no more lives to continue! Your score was:",score)
time.sleep(3)
print("\n")
slow_print ("Would you like to play again?")
playAgain = input("\n[Y/N]: ")
if playAgain == ("n") or playAgain == ("N"):
print ("\n")
user = str(input("Enter a name to save your highscore: ")) #user variable is not saved from the login system as it is defined as a function separately
file = open ("H_Highscore.txt","a")
file.write(user)
file.write(",")
file.write(str(score)) #(int(x)) can not be written
file.write("pts")
file.write("\n")
file.close()
time.sleep(0.5)
leaderboard()
sys.exit()
if playAgain == ("Y") or playAgain == ("y"):
print ("Your last score was",score,", lets see if you can beat it this time...")
time.sleep(1)
print ("\n")
pickSong_random()
loginsys() #LOGIN PROTOCOL
time.sleep(3)
print("\n")
tutorial() #TUTORIAL PROTOCOL
slow_print ("Prepare yourself! The game will begin in...\n")
time.sleep(0.5)
print("\n")
slow_print("5...")
time.sleep(0.5)
print("\n")
slow_print("4...")
time.sleep(0.5)
print("\n")
slow_print ("3...")
time.sleep(0.5)
print("\n")
slow_print ("2...")
time.sleep(0.5)
print("\n")
slow_print ("1...")
time.sleep(0.5)
print("\n")
pickSong_random() #GAME PROTOCOL
sys.exit() #EXIT PROTOCOL
Here's how to do it with the threading.Timer() class I suggested in a comment. These can be configured to delay a specified amount of time and the call as function of your choosing.
In the code below I've defined a callback function named timeout() and a global variable named time_ran_out that it sets to True when the timer expires. There's comments in the added code describing what's being done. All the callback function does is set the value of a variable. Other code in the pickSong_random() function checks the value of this variable to determine if the callback function got called or not.
The nice thing about Timer instances (and functions they callback) is that their execution occurs in the background, in parallel with the the main thread which is running the game itself—so using them doesn't impact game's execution or code very much.
Note I also reformatted your code so it follows PEP 8 - Style Guide for Python Code guides so it's a lot more readable (and easier to work on) in my opinion.
import random
import sys
import time
from threading import Timer
TIMELIMIT = 10.0 # Seconds (set low for testing).
def slow_print(s):
for c in s:
sys.stdout.write('%s' % c)
sys.stdout.flush()
time.sleep(0.03)
def pickSong_random():
# Local Timer callback function.
def timeout():
nonlocal time_ran_out # Reference variable defined in enclosing scope
# (so a local one isn't created automatically).
time_ran_out = True
score = 0
lives = 5
songFile = open("F_Songs.txt", "r")
songList = songFile.readlines() # Reads from the bridged file
songFile.close()
while True:
chosenSong = random.choice(songList)
chosenSong = chosenSong.strip("\n")
artistAndSong = chosenSong.split(":") # Defines song split
toDisplay = ""
toDisplay += artistAndSong[0] + ": "
songTitleWords = artistAndSong[1].split(" ")
for word in songTitleWords:
# loop through
toDisplay += word[0] + " "
print(toDisplay)
# print("2" +toDisplay)
toDisplay = toDisplay.strip("None")
guesses = 0
timer = Timer(TIMELIMIT, timeout) # Create a timer thread object.
time_ran_out = False # Define local variable the callback function modifies.
timer.start() # Start the background timer.
while guesses < 2:
if time_ran_out:
print('Times up!')
break
guesses += 1
guess = input("[Enter your guess]: ")
# Guess checking
if guess.lower() == artistAndSong[1].lower():
print("✓Correct! The song was " + artistAndSong[1]
+ " by " + artistAndSong[0])
print("It took you", guesses, "guess(es)!")
if guesses == 1:
print("\n")
print("↑(+3 points)↑")
print("\n")
score += 3
break
elif guesses == 2:
print("\n")
print("↑(+1 point)↑")
print("\n")
score += 1
break
else:
print("╳The song name isn't", guess, "\n")
lives = lives-1
if guesses == 2:
print("Sorry, you couldn't guess the song.")
print("\n")
if lives == 0:
print("You have no more lives to continue! Your score was:", score)
time.sleep(3)
print("\n")
slow_print("Would you like to play again?")
playAgain = input("\n[Y/N]: ")
if playAgain == ("n") or playAgain == ("N"):
print("\n")
# user variable is not saved from the login system as it is
# defined as a function separately
user = str(input("Enter a name to save your highscore: "))
file = open ("H_Highscore.txt", "a")
file.write(user)
file.write(",")
file.write(str(score)) # (int(x)) can not be written
file.write("pts")
file.write("\n")
file.close()
time.sleep(0.5)
leaderboard()
sys.exit()
if playAgain == ("Y") or playAgain == ("y"):
print("Your last score was", score,", lets see if you can beat it this time...")
time.sleep(1)
print("\n")
pickSong_random()
if __name__ == '__main__':
pickSong_random()
Simply record the start time, and break from your loop if the time is up. By sleeping you make your program hibernate and the user can not do anything. So "fasteness" does not make any difference because you can't do anything while the program sleeps:
import random
import datetime
correct = 0
start = datetime.datetime.now()
while True:
print("Math test. Add , dont screw up, you got {}s left".
format(20-(datetime.datetime.now()-start).seconds))
a,b = random.choices(range(1,20),k=2)
c = input(" {:>2} + {:>2} = ".format(a,b))
if (datetime.datetime.now()-start).seconds > 20:
print("Times up. Score: {}".format(correct))
break
try:
if a+b == int(c):
correct += 1
print("Correct")
else:
print("Wrong")
except:
print("Wrong")
Output:
Math test. Add , dont screw up, you got 20s left
17 + 8 = 23
Wrong
Math test. Add , dont screw up, you got 18s left
10 + 2 = 12
Correct
Math test. Add , dont screw up, you got 14s left
1 + 7 = 8
Correct
Math test. Add , dont screw up, you got 12s left
5 + 19 = 24
Correct
Math test. Add , dont screw up, you got 8s left
4 + 3 = 7
Correct
Math test. Add , dont screw up, you got 5s left
3 + 18 = 21
Correct
Math test. Add , dont screw up, you got 3s left
15 + 12 = 27
Correct
Math test. Add , dont screw up, you got 1s left
7 + 8 = 15
Times up. Score: 6
It turns out you were actually reassigning the "time" module to an integer of 60, overwriting the library, which is why it had no attribute ".sleep()". Also the countdown part is irrelevant and a bit redundant. Anyways, this revised bit of code worked for me:
import time
sec=60
while sec != 0:
print(sec)
sec = sec-1
time.sleep(1)
print ("You've ran out of time!")
Hope this helps!
While Om Agarwal may have a possible solution, you may also want to consider using a non-blocking approach in your game using the built-in pygame time.
start_ticks = pygame.time.get_ticks()
while guesses < 2:
# OTHER GAME CODE HERE
seconds = (pygame.time.get_ticks() - start_ticks) / 1000
if seconds > 60:
print ("You've ran out of time!")
break
Cheers!
Edit 1: Added example modification.
import pygame
import time
import random
import sys
def pickSong_random():
score = 0
lives = 5
songFile = open("F_Songs.txt", "r")
songList = songFile.readlines() # Reads from the bridged file
songFile.close()
while True:
chosenSong = random.choice(songList)
chosenSong = chosenSong.strip("\n")
artistAndSong = chosenSong.split(":") # Defines song split
toDisplay = ""
toDisplay += artistAndSong[0] + ": "
songTitleWords = artistAndSong[1].split(" ")
for word in songTitleWords:
# loop through
toDisplay += word[0] + " "
print(toDisplay)
# print("2" +toDisplay)
toDisplay = toDisplay.strip("None")
guesses = 0
start_ticks = pygame.time.get_ticks()
while guesses < 2:
guesses += 1
guess = input("[Guess]: ")
seconds = (pygame.time.get_ticks() - start_ticks) / 1000
if seconds > 60:
print("You've ran out of time!")
break
# Guess checking
if guess.lower() == artistAndSong[1].lower():
print("Correct! The song was " + artistAndSong[1] + " by " + artistAndSong[0])
print("It took you", guesses, "guess(es)!")
if guesses == 1:
print("(+3 points)")
print("\n")
score += 3
break
elif guesses == 2:
print("(+1 point)")
print("\n")
score += 1
break
else:
print("That's incorrect, guess again.\n")
lives = lives - 1
if lives == 0:
print("You have no more lives to continue! Your score was:", score)
time.sleep(3)
slow_print("Would you like to play again?")
playAgain = input("[Y/N]: ")
if playAgain == "n" or playAgain == "N":
sys.exit()
if playAgain == "Y" or playAgain == "y":
print("Your last score was", score, ", lets see if you can beat it this time...")
time.sleep(1)
print("\n")
pickSong_random()
Related
enter image description herei want to find out how
i can take in user’s inputs on the number of times user wishes to run/play, and execute accordingly. and also how can i provide user with an option on the game/run mode
allow the user to choose the complexity level of a game?
include a scoreboard that shows the top 5 players/scores.
[enter image description here](https://i.stack.enter image description hereimgur.com/CcJOM.png)
from IPython.display import clear_output
import random
NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
#Input for the word by game master
user = input("Please enter your name:")
print("Hi " + user + " good luck ")
no_of_time = input("How many times do you want to play: ")
answer_word = list(str.lower(input("input enter your word: "))) #https://stackoverflow.com/questions/1228299/change-one-character-in-a-string
clear_output()
win = False
#defining function
def guesscheck(guess,answer,guess_no):
clear_output()
if len(guess)==1:
if guess in answer:
print("Correct, ",guess," is a right letter")
return True
else:
print("Incorrect, ",guess, " is a not a correct letter. That was your chance number ",guess_no)
return False
else:
print("Enter only one letter")
#Storing the number of characters in different variable
answer_display=[]
for each in answer_word:
answer_display += ["*"]
print(answer_display)
#initializing number of allowable guesses
guess_no = 1
while guess_no<5:
clear_output
#Player input for guess letter
guess_letter=str.lower(input('Enter your guess letter: '))
#Calling a sub function to check if correct letter was guessed
guess_check=guesscheck(guess_letter,answer_word,guess_no);
#Conditional: if incorrect letter
if guess_check == False:
guess_no +=1
print(answer_display)
#Conditional: if correct letter
elif guess_check == True:
num = [i for i, x in enumerate(answer_word) if x == guess_letter] #https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list
for all in num:
answer_display[all]=guess_letter
print(answer_display)
#Conditional: if no remaining unknown letter then win screen
if answer_display.count('*')==0:
win = True
break
if win:
print("You won!")
else:
print("The correct answer was: ", answer_word)
print("You lost!")
To install random_words package in jupyter notebook.
run this command in code shell.
!pip install random_word
import package. from random_word import RandomWords
generate.
r = RandomWords()
print(r.get_random_word())
Code snippet:
import random
from random_word import RandomWords
# Input for the word by game master
user = input("Please enter your name:")
print("Hi " + user + " good luck ")
while True:
try:
no_of_time = int(input("How many times do you want to play: "))
played_time = no_of_time
break
except ValueError:
print("Please enter a number. specify in number how many time you want to play.")
r=RandomWords()
scorecard = 0
# defining function
def guesscheck(guess, answer, guess_no):
if len(guess) == 1:
if guess in answer:
print("Correct, ", guess, " is a right letter")
return True
else:
print("Incorrect, ", guess, " is a not a correct letter. That was your chance number ", guess_no)
return False
else:
print("Enter only one letter")
while no_of_time:
while True:
try:
difficulty_level = int(input(
"Enter the difficulty you want to play: press [1] for easy, press [2] for medium, press [3] for hard, press [4] for manually word"))
if difficulty_level in [1, 2, 3, 4]:
break
else:
print("Enter number 1 or 2 or 3 or 4 not other than that!!")
continue
except ValueError:
print("Please enter difficulty level specific.")
answer_word = ""
if difficulty_level == 1:
while len(answer_word)!=5:
answer_word = r.get_random_word()
elif difficulty_level == 2:
while len(answer_word)!=6:
answer_word = r.get_random_word()
elif difficulty_level == 3:
while len(answer_word)!=10:
answer_word = r.get_random_word()
else:
answer_word=input("Enter manually what word you wanted to set..!")
win = False
# Storing the number of characters in different variable
answer_display = []
for each in answer_word:
answer_display += ["*"]
print(answer_display)
# initializing number of allowable guesses
guess_no = 1
while guess_no <= 5: # User chances given 5
# Player input for guess letter
guess_letter = str.lower(input('Enter your guess letter: '))
# Calling a sub function to check if correct letter was guessed
guess_check = guesscheck(guess_letter, answer_word, guess_no)
# Conditional: if incorrect letter
if guess_check == False:
guess_no += 1
print(answer_display)
# Conditional: if correct letter
elif guess_check == True:
num = [i for i, x in enumerate(answer_word) if
x == guess_letter] # https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list
for all in num:
answer_display[all] = guess_letter
print(answer_display)
# Conditional: if no remaining unknown letter then win screen
if answer_display.count('*') == 0:
win = True
break
if win:
print("You won!")
scorecard += 1
else:
print("The correct answer was: ", answer_word)
print("You lost!")
no_of_time -= 1
print("You played " + str(played_time) + ":")
print("Won: " + str(scorecard) + " Guessed correctly!!")
print("Lose: " + str(played_time - scorecard) + "not Guessed correctly!!")
don't know why specific length is not working in random_word hence included while statement.. this code snippet is working you can go through this..!
I'm very new to programming and am starting off with python. I was tasked to create a random number guessing game. The idea is to have the computer guesses the user's input number. Though I'm having a bit of trouble getting the program to recognize that it has found the number. Here's my code and if you can help that'd be great! The program right now is only printing random numbers and won't stop even if the right number is printed that is the problem
import random
tries = 1
guessNum = random.randint(1, 100)
realNum = int(input("Input a number from 1 to 100 for the computer to guess: "))
print("Is the number " + str(guessNum) + "?")
answer = input("Type yes, or no: ")
answerLower = answer.lower()
if answerLower == 'yes':
if guessNum == realNum:
print("Seems like I got it in " + str(tries) + " try!")
else:
print("Wait I got it wrong though, I guessed " + str(guessNum) + " and your number was " + str(realNum) + ", so that means I'm acutally wrong." )
else:
print("Is the number higher or lower than " + str(guessNum))
lowOr = input("Type in lower or higher: ")
lowOrlower = lowOr.lower()
import random
guessNum2 = random.randint(guessNum, 100)
import random
guessNum3 = random.randint(1, guessNum)
while realNum != guessNum2 or guessNum3:
if lowOr == 'higher':
tries += 1
import random
guessNum2 = random.randint(guessNum, 100)
print(str(guessNum2))
input()
else:
tries += 1
import random
guessNum3 = random.randint(1, guessNum)
print(str(guessNum3))
input()
print("I got it!")
input()
How about something along the lines of:
import random
realnum = int(input('PICK PROMPT\n'))
narrowguess = random.randint(1,100)
if narrowguess == realnum:
print('CORRECT')
exit(1)
print(narrowguess)
highorlow = input('Higher or Lower Prompt\n')
if highorlow == 'higher':
while True:
try:
guess = random.randint(narrowguess,100)
print(guess)
while realnum != guess:
guess = random.randint(narrowguess,100)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
elif highorlow == 'lower':
while True:
try:
guess = random.randint(1,narrowguess)
print(guess)
while realnum != guess:
guess = random.randint(1,narrowguess)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
This code is just a skeleton, add all of your details to it however you like.
I'm writing a hangman.
The script consist of two functions:
setup() which initializes all the variables (the word, number of guesses, lists of letters to check etc) and main (which is the main game loop).
The last thing setup() does is calling the main().
From main() you can invoke setup() to reset the game.
By design, the main() function needs to access the variables created by setup() and vice versa. It requires me to heavily use "global" statements - for all declarations within setup().
How should I approach it to avoid having "bad" global variables?
import random
def setup():
with open("Ex30_Pick_a_word/sowpods.txt", "r") as f:
lines = [x for x in f.readlines()]
count = 0
for line in lines:
count += 1
global selected_word
selected_word = lines[random.randint(1, count)].rstrip()
## initialize variables
global guess_state
guess_state = ['-' for letter in selected_word]
global bad_letters
bad_letters = ""
global chances
chances = 6
## start game
print("\n\n\n#### WELCOME TO HANGMAN ###")
print("Word to guess is: " + selected_word + ".") ## debug only ;)
main()
def main():
while True:
success = False
print("\n""The word is:")
display = "".join(guess_state)
print(display)
global chances
print("You've got " + str(chances) + " chances left.")
guess_letter = input("Guess a letter:").capitalize()
## logic
for letter_id, letter in enumerate(selected_word):
if guess_letter == letter: ## if found
if guess_state[letter_id] == "-": ## if not yet found
guess_state[letter_id] = letter
success = True
break
if not success:
global bad_letters
if guess_letter in bad_letters:
print("You've aread tried: \"" + guess_letter + "\"")
else:
bad_letters += guess_letter + " "
chances -= 1
if ''.join(guess_state) == selected_word:
print("You've won, the word was: " + selected_word)
again = input("Do you want to play again? (y/n)")
if again == "y":
setup()
break
if len(bad_letters) > 0:
print("\nBad letters: " + bad_letters)
if chances == 0:
print("Game Over.")
again = input("Do you want to play again? (y/n)")
if again == "y":
setup()
break
setup()
This code is from a small game i've been working on over the past day or so, i know i shouldn't really post the whole code but i'm not entirely sure which part of the code is not working as intended, any help would be appreciated. the code is a hangman game and i am aware of the huge amount of repetition in the code but am unsure how to reduce it to one of every function that will work with each difficulty setting.
import random
import time
#Variables holding different words for each difficulty
def build_word_list(word_file):
words = [item.strip("\n") for item in word_file]
return words
EASYWORDS = open("Easy.txt","r+")
MEDWORDS = open("Med.txt","r+")
HARDWORDS = open("Hard.txt","r+")
INSANEWORDS = open("Insane.txt", "r+")
easy_words = build_word_list(EASYWORDS)
medium_words = build_word_list(MEDWORDS)
hard_words = build_word_list(HARDWORDS)
insane_words = build_word_list(INSANEWORDS)
#Where the user picks a difficulty
def difficulty():
print("easy\n")
print("medium\n")
print("hard\n")
print("insane\n")
menu=input("Welcome to Hangman, type in what difficulty you would like... ").lower()
if menu in ["easy", "e"]:
easy()
if menu in ["medium", "med", "m"]:
med()
if menu in ["hard", "h"]:
hard()
if menu in ["insane", "i"]:
insane()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
def difficulty2():
print("Easy\n")
print("Medium\n")
print("Hard\n")
print("Insane\n")
print("Quit\n")
menu=input("Welcome to Hangman, type in the difficulty you would like. Or would you like to quit the game?").lower()
if menu == "hard" or menu == "h":
hard()
elif menu == "medium" or menu == "m" or menu =="med":
med()
elif menu == "easy" or menu == "e":
easy()
elif menu == "insane" or menu == "i":
insane()
elif menu == "quit" or "q":
quit()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
#if the user picked easy for their difficulty
def easy():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
print ("the word was, ", word)
difficultyEASY()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyEASY()
#if the user picked medium for their difficulty
def med():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyMED()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyMED()
#if the user picked hard for their difficulty
def hard():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyHARD()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyHARD()
#if the user picked insane for their difficulty
def insane():
global score
print ("This words may contain an apostrophe. \nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyINSANE()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyINSANE()
def start():
Continue = input("Do you want to play hangman?").lower()
while Continue in ["y", "ye", "yes", "yeah"]:
name = input("What is your name? ")
print ("Hello, %s, Time to play hangman! You have ten guesses to win!" % name)
print ("\n")
time.sleep(1)
difficulty()
else:
quit
#whether they want to try a diffirent difficulty or stay on easy
def difficultyEASY():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
easy()
#whether they want to try a diffirent difficulty or stay on medium
def difficultyMED():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
med()
#whether they want to try a diffirent difficulty or stay on hard
def difficultyHARD():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
hard()
#whether they want to try a diffirent difficulty or stay on insane
def difficultyINSANE():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
insane()
score = 0
start()
When i run this code the error i get is:
Traceback (most recent call last):
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 316, in <module>
start()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 274, in start
difficulty()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 41, in difficulty
insane()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 227, in insane
word = random.choice(words).lower()
NameError: name 'words' is not defined
I'm not sure what is wrong with words or how to fix it.
Your words variable is only defined in the scope of build_word_list function.
All the other functions don't recognize it so you can't use it there.
You can have a "quickfix" by defining it as a global variable, although usually using global variables isn't the best practice and you might want to consider some other solution like passing words to your other functions that use it or use it within the confines of a class.
(If avoiding global variables interests you, maybe you would like to read this and this)
You have words defined in the method build_word_list.
You should declare words as a global variable so that it can be accessed everywhere or restructure you program into a class and use self to reference it.
EDIT:
I solved this by implementing #L3viathan's solution. Here is the updated code:
import operator
import random
from time import time
import sys
def menu():
menu = input("\n\n\n--------\n Menu \n--------\nPress:\n- (1) to play \n- (2) to exit\n: ")
if menu == "1":
play_game()
if menu == "2":
print("Exiting...")
sys.exit()
while menu != "1" or menu != "2":
print("Please enter a valid choice")
menu = input("--------\n Menu \n--------\nPress:\n- (1) to play \n- (2) to exit\n: ")
if menu == "1":
play_game()
if menu == "2":
print("Exiting...")
break
def game_over():
print("Game over.")
file = open("score.txt", "r")
highscore = file.read()
if int(highscore) < score:
file = open("score.txt", "w")
file.write(score)
file.close()
print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
else:
print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
def play_game():
print("Type in the correct answer to the question\nYou have 3 seconds to answer each question\nThe game will continue until you answer a question incorrectly") #displays the welcome message
counter = 1
score = 0
while counter == 1:
ops = {"+":operator.add,
"-":operator.sub,
"x":operator.mul}
num1 = random.randint(0, 10)
op = random.choice(list(ops.keys()))
num2 = random.randint(1, 10)
print("\nWhat is {} {} {}? ".format(num1, op, num2))
start = time()
guess = float(input("Enter your answer: "))
stop = time()
answer = ops.get(op)(num1,num2)
if guess == answer:
if stop - start > 3:
print("You took too long to answer that question. (" + str(stop - start) + " seconds)")
def game_over():
print("Game over.")
file = open("score.txt", "r")
highscore = file.read()
if int(highscore) < score:
file = open("score.txt", "w")
file.write(score)
file.close()
print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
else:
print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
menu()
game_over()
break
else:
score = score + 1
print("Correct!\nScore: " + str(score))
else:
print("Game over.")
counter = counter - 1
file = open("score.txt", "r")
highscore = file.read()
if int(highscore) < score:
file = open("score.txt", "w")
file.write(score)
file.close()
print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
else:
print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
if counter != 1:
menu()
menu()
Thank you all for your contributions.
------ EDIT END -------
I have been searching Stack Overflow for a solution however I could not find anything which works with my game, therefore I appologise if this is a duplicate question.
I am making a math game where a user has to answer a simple arithmetic question, each time the user enters the correct answer, the score increases by one. However, if the user enters a wrong answer, the game ends.
I would like to add a timeout feature to the game, for example when a user is entering an answer to one of the questions, if the user takes more than 3 seconds to answer, the game ends. Does anyone know how to do this?
All of the solutions I could find were for Unix, not Windows.
Here is my code:
import operator
import random
def play_game():
print("Type in the correct answer to the question\nYou have 3 seconds to answer each question\nThe game will continue until you answer a question incorrectly") #displays the welcome message
counter = 1
score = 0
while counter == 1:
ops = {"+":operator.add,
"-":operator.sub,
"x":operator.mul}
num1 = random.randint(0, 10)
op = random.choice(list(ops.keys()))
num2 = random.randint(1, 10)
print("\nWhat is {} {} {}? ".format(num1, op, num2))
guess = float(input("Enter your answer: "))
answer = ops.get(op)(num1,num2)
if guess == answer:
score = score + 1
print("Correct!\nScore: " + str(score))
else:
print("Game over.")
counter = counter - 1
file = open("score.txt", "r")
highscore = file.read()
if int(highscore) < score:
file = open("score.txt", "w")
file.write(score)
file.close()
print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
else:
print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
if counter != 1:
menu = input("\n\n\nMenu\n----\nPress:\n- (1) to play again\n- (2) to exit\n: ")
if menu == "1":
play_game()
elif menu == "2":
print("Exiting...")
break
while menu != "1" or menu != "2":
print("Please enter a valid choice")
menu = input("Menu\n----\nPress:\n- (1) to play again\n- (2) to exit\n: ")
if menu == "1":
play_game()
elif menu == "2":
break
print("Exiting...")
play_game()
The easiest way to do this would be to time the call to input:
from time import time
start = time()
answer = input("Answer this in 3 seconds: 1 + 1 = ")
stop = time()
if stop - start < 3:
if answer == "2":
print("Correct!")
else:
print("Wrong!")
else:
print("Too slow")
This way is simple, but you couldn't abort the user's ability to input after three seconds, only wait for it and then see if it was fast enough.