SUPER new to programming so bear with me, please. I am taking my first ever programming class and for a project, I was given a list of requirements I need to fulfill, creating a simple number guessing game has been the only thing I've not had a lot of trouble with so I decided to give it a go.
(i need 1 class, function, dictionary or list, for loop, and while loop) What I, well at least have tried to make is a guessing game that gives a limit of 2 guesss for a # between 0 and 10, any help would be greatly appreciated. :)
import random
class Player:
player = ""
playerscore = 0
def gamestart(self):
self.number = random.randint(0,7)
self.guesss = 0
self.list = []
self.limit = 3
print()
print("Guess what number I'm thinking off")
print()
print("Might even give you a hit if you do well enough")
print()
while self.limit > 0:
self.player_guess = int(input("Well? What are you waiting for? Start guessing:"))
print()
if self.player_guess > 7 or self.player_guess < 0:
print("Wow that was a terrible guess, think harder or we might be here all week long")
print("also,", self.player_guess , "is not in the range...")
print("Becareful though, you only have", self.limit, "guesss left")
elif self.player_guess > self.number:
self.guesss += 1
self.limit-= 1
print("WRONG")
print(self.player, "You only have", self.limit, "guesss left")
self.list.append(self.player_guess)
elif self.player_guess < self.number:
self.guesss += 1
self.limit -= 1
print("oh oh... wrong again!")
print()
print(self.player, "You only have", self.limit, "guesss left.")
self.list.append(self.player_guess)
else:
self.limit -= 1
self.playerscore += 1
self.list.append(self.player_guess)
print()
print("wow, you actually got it right")
print()
print(self.player_guess, "IS THE CORRECT ANSWER!")
print()
print("you only had",self.limit,"left too...")
print("Lets see all the numbers you guessed")
print()
for i in self.list:
print(i)
self.list.clear()
I found the question confusing, however the following code should work as a number guessing game, hope I answered your question.
import random
game = "true"
guesses = 2
while game == "true":
comp_number = int(random.uniform(1,8))
print("I have randomly selected a number between 1 and 7 (inclusive), you have 2 attempts to guess the number.")
while guesses > 0:
if guesses == 2:
turn = "first"
else:
turn = "final"
guess = int(input("Please submit your "+turn+" guess:"))
while guess < 1 or guess > 7:
print("Invalid guess, remember my number is between 1 and 7 (inclusive)")
guess = int(input("Resubmit a valid guess:"))
if guess == comp_number:
print("Congratulations you guessed my number, you win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
else:
print("Incorrect number, try again.")
guesses -= 1
print("You where unable to guess my number, I win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
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.
Why is my code not working? I am following UDEMY's 100 days of code and it is essentially the same as the instructor but I wanted to have keyword named arguments. First of all it's not printing the correct turn_left after each turn and it's not stopping the game.
from random import randint
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
def check_answer(user_guess, correct_answer, tracking_turns):
"""
Checks answer with guess.
"""
if user_guess > correct_answer:
print("Too high")
return tracking_turns - 1
elif user_guess < correct_answer:
print("Too low")
return tracking_turns - 1
elif user_guess == correct_answer:
print(f"Right the answer is {correct_answer}")
def set_difficulty(game_level):
"""
Sets game difficulty
"""
if game_level == "easy":
return EASY_LEVEL_TURNS
elif game_level == "hard":
return HARD_LEVEL_TURNS
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
answer_checked = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
game()
You can modify your game function like this, mainly by updating the turn_left value and setting the end-of-function condition
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
turn_left = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
elif not turn_left:
return
I am new to python and built this for practice. How come if you guess incorrectly the print function runs repeatedly. Additionally, if you make a correct guess the corresponding print function doesn't run.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
elif guess < rand:
print("Too Low")
If the number is incorrect we need to ask the player to guess again. You can use break to avoid having an infinite loop, here after 5 guesses.
The conversion of the input to integer will throw an error if the entry is not a valid number. It would be good to implement error handling.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
break
elif guess < rand:
print("Too Low")
if i >= 5:
break
guess = int(input("Try again\nPick a number from 1 - 9"))
in the first while loop, when player guesses the correct number we need to break.
Also for counting the number of rounds that player played we need a new while loop based on count.
When we use count in our code we should ask player every time that he enters the wrong answer to guess again so i used input in the while
import random
print("Welcome to the Guessing Game:")
rand = random.randint(1, 9)
count = 0
while count!=5:
guess = int(input("Pick a number from 1 - 9:"))
count += 1
if guess > rand:
print("Too High")
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
break
elif guess < rand:
print("Too Low")
print('you lost')
I'm new to Python and just starting to make a guessing game.
I finally managed to figure out a way to make the game work by allowing the user to try again if they run out of 3 guesses with this code (hopefully this is ok for you people)
from random import randint
random_number = randint(1, 10)
guesses_left = 3
guess = None
while True:
print(f"You have {guesses_left} guseses left")
guess = input("Pick a number between 1 and 10\n")
guess = int(guess)
if guess > random_number:
print("Too high")
guesses_left -= 1
elif guess < random_number:
print("Too low")
guesses_left -= 1
else:
guesses_left = 3
print("Good Job! You got it!")
if input("Would you like to play again (y/n)\n") == "y":
random_number = randint(1, 10)
else:
print("Thanks for Playing!")
break
if guesses_left == 0:
guesses_left = 3
print("You ran out of guesss :(")
if input("Would you like another try?\n") != "y":
print("Thanks for playing!")
break
However before I got to that conclusion, I had the final if statement placed above the 2nd to last else statement (I probably didn't say that well but hopefully the code explains it) and the code didn't work in the end (It said I got the number right even if the number was wrong) Could someone help me explain why I need to put that block of code at the bottom instead of the final else statement?
from random import randint
random_number = randint(1, 10)
guesses_left = 3
guess = None
while True:
print(f"You have {guesses_left} guseses left")
guess = input("Pick a number between 1 and 10\n")
guess = int(guess)
if guess > random_number:
print("Too high")
guesses_left -= 1
elif guess < random_number:
print("Too low")
guesses_left -= 1
**if guesses_left == 0:
guesses_left = 3
print("You ran out of guesss :(")
if input("Would you like another try?\n") != "y":
print("Thanks for playing!")
break**
else:
guesses_left = 3
print("Good Job! You got it!")
if input("Would you like to play again (y/n)\n") == "y":
random_number = randint(1, 10)
else:
print("Thanks for Playing!")
break
In the second code snippet, you are checking whether guesses_left is equals to 0. After the first guess, it isn't, and so it goes to the 'else', where Good job, you got it! is printed.
if guesses_left == 0:
guesses_left = 3
print("You ran out of guesss :(")
if input("Would you like another try?\n") != "y":
print("Thanks for playing!")
break
else:
guesses_left = 3
print("Good Job! You got it!")
```
Hi The reason is when you inserted the if after your elif you had reinitated another condition. thus, the else follows the condition on the second if statement and not the first condition. see the below example
a = 3
b = 'a dsistraction'
if a ==3:
print('yes 3')
elif a ==1:
print('yes 1')
if b == 2:
print('reseting the condition')
else:
print('broken out of the first if')
#yes 3
#a followin
What you will realise is there are two different conditions. thus rather than use if, you are better off using an elif statement
The if at the same indent level after an elif starts a new set of branches; its evaluation is largely independent of the previous branches (the exception being any state change, such as the alteration of guesses_left in the sample). Consider what you have going into the block (in particular, the value of guesses_left:
if guesses_left == 0:
guesses_left = 3
print("You ran out of guesss :(")
if input("Would you like another try?\n") != "y":
print("Thanks for playing!")
break
else:
guesses_left = 3
print("Good Job! You got it!")
if input("Would you like to play again (y/n)\n") == "y":
random_number = randint(1, 10)
else:
print("Thanks for Playing!")
break
This connects to general design principles that can help avoid this sort of mistake: decompose a task into discrete subtasks and reduce coupling. In this case, "check the guess" and "check for game end" are separate subtasks, which should reflect in the code (as was done in the final, working program). You can separate the tasks out into distinct functions, classes, modules or frameworks (as appropriate), but even if you don't, you can write your code in such a way as it can later be refactored into separate pieces.
I'm a very new beginner coder and I don't know much yet. I am trying to create a guessing game, and I want to add a timer to the program.
The way the timer would work would be that I set up a set amount of time i.e. 60 seconds and once the time has run out the program would stop and basically be like "sorry you ran out of time. Would you like to try again?"
I've already searched for some videos on YouTube and on Stackoverflow but I either don't understand it or I'm unable to do it.
https://www.youtube.com/watch?v=Mp6YMt8MSAU
I've watched this video like 4 times and still have no clue how to do it. So if anyone is willing to explain to me/show me how to add time that would be much appreciated
def main():
import random
n = random.randint(1, 99)
chances = 5
guess = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: " ))
while n != "guess":
chances -=1
if chances ==0:
print("out of chances, it is now player 2's turn to play. The number was", n)
break
if guess < n:
print("guess is low you have",chances,"chances left")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high you have",chances, "chances left")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances, "chances left")
break
import random
n1 = random.randint(1, 99)
chances1 = 0
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: "))
while n1 != "guess":
chances1 +=1
if chances1 ==5:
print("out of chances, the number was", n1)
break
if guess1 < n1:
print("guess is low you have",chances1,"chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high you have",chances1, "chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances1, "chances left")
break
retry=input("would you like to play again? (please choose either 'yes' or 'no' )")
if retry == "yes":
main()
elif retry == "no":
print("Okay. have a nice day! :D ")
else:
print("Invalid input")
main()
This is my code. Any feedback would be appreciated.
(I don't know how much do you know about python and programming so I'll use a really simple language)
Well, if your game don't have to run while the timer is active you could use the sleep function of the time library, and writhing something like this:
import time
time.sleep("time amount")
print("I'me sorry but you run out of time!")
print("Do you wanna retry ?")
Whit the "command" time.sleep, python will stop the entire program for the amount of time you've selected
(So if you have to play the game while the timer is running don't use the time.sleep method)
Instead if the timer have to be active while you're playing the game you should use "threading".
threading is a library that allows you to do really simple timers, but not only.
Making a timer with threading it could be more complex for you but not really.
You have to write a function to call when the timer is over like that:
def time_over():
print("I'm sorry but the time is over !")
print("Do you want to play again ? ")
After that you have to create the timer:
timer_name = threading.timer("time amount", function)
Eventually you have to start the timer writing:
timer_name.start()
In that way python will:
1 - Import the threading Library
2 - Create the timer whit the amount of time do you want
3 - Start the timer
4 - Activate the function you've wrote when the time will run out
If you need more info about one of these methods, write a comment and I will answer to your question as faster as I can.
Have a good day :)
To solve your problem, you will have to use a Thread. I took your code I added the Thread at the beginning, try to have a look.
A Thread is an object that can execute a function (its run function) beside the main program. It is so-called Parallel Programming.
Here you need that because you want to:
Check the Input of the player
Count Down
I do not correct your code or rewrite it, I just added the Thread and make it work. It is pretty easy:
I call sleep for a given amount of time (_TIME_LIMIT]
Make a little noise when the timer ended.
I set a variable to True, that means that the timer ended
With a bit of rewriting, you will be able to interrupt your main loop when the Thread change the variable. But that is out the scope of the initial question, feel free to improve your game.
For the moment, you need to enter a number to know if the time was ended or not. That is why I added the little noise (if not you would have no cue).
Please, be free to ask any questions.
Hope this will help you.
from threading import Thread
from time import sleep
import random
_TIME_OUT = [False, False]
_TIME_LIMIT = 1
class MyThread(Thread):
def __init__(self, time_out, player):
Thread.__init__(self)
self.time_out = time_out
self.player = player
def run(self):
sleep(self.time_out)
_TIME_OUT[self.player - 1] = True
print('\a', end="") # Make a noise
def main():
_TIME_OUT[0] = False
_TIME_OUT[1] = False
tread_1 = MyThread(_TIME_LIMIT, 1)
n = random.randint(1, 99)
chances = 5
tread_1.start()
print(f"You have {_TIME_LIMIT} sec")
guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: " ))
while n != "guess" and not _TIME_OUT[0]:
print(not _TIME_OUT, _TIME_OUT)
chances -=1
if chances == 0:
print("out of chances, it is now player 2's turn to play. The number was", n)
break
if guess < n:
print("guess is low you have",chances,"chances left")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high you have",chances, "chances left")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances, "chances left")
break
if _TIME_OUT[0]:
print("Sorry, out of time!")
tread_2 = MyThread(_TIME_LIMIT, 2)
n1 = random.randint(1, 99)
chances1 = 0
tread_2.start()
print(f"You have {_TIME_LIMIT} sec")
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: "))
while n1 != "guess" and not _TIME_OUT[1]:
chances1 +=1
if chances1 ==5:
print("out of chances, the number was", n1)
break
if guess1 < n1:
print("guess is low you have",chances1,"chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high you have",chances1, "chances left")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it and have", chances1, "chances left")
break
if _TIME_OUT[1]:
print("Sorry, out of time!")
retry=input("would you like to play again? (please choose either 'yes' or 'no' )")
if retry == "yes":
main()
elif retry == "no":
print("Okay. have a nice day! :D ")
else:
print("Invalid input")
if __name__ == "__main__":
main()