Im trying to make a 4 digit numbers guessing game in Python 3. It should work by generating a random number between 1000 and 10000 (random.range(1000,10000)) and then by the user guessing and it should return after each guess how many numbers you have got right. My code doesn't exactly work and, I can't think why it doesn't so help is appreciated.
import random as r
guessing = True
real_ans = r.randrange(1000, 10000, 2)
real_ans_str = str(real_ans)
correct = 0
class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(3):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False
while guessing:
Player()
There are several issues in your code:
You're creating a new instance of Player class inside the main loop. It works, but it's not the best approach IMHO.
You're using guessing to stop the main loop. In Python, all variables are local by default. In order to reference a global variable, you must identify it as global:
def evaluate(self, correct):
**global guessing**
for n in range(3):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False
However using global variables could lead to a messy code.
range provides values from the minimum (0 by default) inclusive and the maximum exclusive. That range(3) will provide the numbers 0, 1 and 2 (3 numbers total), which is not what you want.
Since you're using a class, I'd try the following:
Create a single instance of Player
Create a new method called guess
Change the evaluate method to return how many digits the player guessed right
Create a new method called run, that will call guess and evaluate
import random as r
class Player():
def __init__(self):
self.real_ans = str(r.randrange(1000,100000,2))
def guess(self):
self.player_guess = raw_input("Enter a guess")
def evaluate(self):
correct = 0
for n in range(4):
if self.player_guess[n] == self.real_ans[n]:
correct += 1
return correct
def run(self):
while True:
self.guess()
correct = self.evaluate()
if not correct == 4:
print(str(correct)," was correct")
else:
print("You guessed it! ")
break
Player().run()
#Digit Guessing Game by Deniz
#python 3.5.1 - Please note that from Python version 2.7 "Tkinter" has been renamed tkinter, with a lowercase "t".
import tkinter
import random
computer_guess = random.randint(1,10)
def check():
user_guess = int(txt_guess.get())
if user_guess < computer_guess:
msg = "Higher!"
elif user_guess > computer_guess:
msg = "Lower!"
elif user_guess == computer_guess:
msg = "Correct!"
else:
msg = "Houston we have a problem!..."
lbl_result["text"] = msg
txt_guess.delete(0, 5)
def reset():
global computer_guess
computer_guess = random.randint(1,10)
lbl_result["text"] = "Game reset. Guess again!"
root = tkinter.Tk()
root.configure(bg="white")
root.title("Guess the correct number!")
root.geometry("280x75")
lbl_title = tkinter.Label(root, text="Welcome to Deniz's guessing Game!", bg="White")
lbl_title.pack()
lbl_result = tkinter.Label(root, text="Good Luck!", bg="White")
lbl_result.pack()
btn_check = tkinter.Button(root, text="Check", fg="blue", bg="White", command=check)
btn_check.pack(side="left")
btn_reset = tkinter.Button(root, text="Reset", fg="red", bg="White", command=reset)
btn_reset.pack(side="right")
txt_guess = tkinter.Entry(root, width=7)
txt_guess.pack()
root.mainloop()
root.destroy()
After reading your comments, I think what you need is this:
class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(4):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
else:
print(str(correct)," was correct")
correct = 0
break
if correct == 4:
print("You guessed it! ")
guessing = False
You can integrate it along with #Robson's answer to end the loop.
Use range(4), range(3) has the values [0, 1, 2] so 3 is missing:
for n in range(4):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
The global guessing is not available inside the class method, so the loop never ends after guessing it right.
And working but ugly solution would be:
print("You guessed it! ")
global guessing
guessing = False
Here is a non infinite loop version without a class. I assumed you wanted to input one number at a time? If not, that could be changed.
Also, the 2 on the end of the randrange only included even numbers, so that wasn't necessary
import random as r
debug = True
real_ans = str(r.randrange(1000, 10000))
if debug:
print(real_ans)
correct = 0
for i in range(len(real_ans)):
player_guess = input("Enter a guess: ")
if str(player_guess) == real_ans[i]:
correct += 1
if correct == 4:
print('You guessed it!')
correct = 0
else:
print('Sorry!', real_ans, 'was correct')
Sample run (Correct)
9692
Enter a guess: 9
Enter a guess: 6
Enter a guess: 9
Enter a guess: 2
You guessed it!
Sample run (Incorrect)
4667
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Sorry! 4667 was correct
import random
from Tools.scripts.treesync import raw_input
x= random.randint(1000,9999)
num=0
while num < 1000 or num > 9999:
num = int(raw_input("Please enter a 4 digit number: "))
if num < 1000 or num > 9999:
print("///wrong input////")
print("system generated number is ",x)
print("The number you entered is ",num)
if num == x:
print("Congrats you win")
else:
rabbit=0
tortose=0
unum = str(num)
snum = str(x)
c1=0enter code here
for i in unum:
c1=c1+1
c2 = 0
for j in snum:
c2=c2+1
if(i==j):
if(c1==c2):
rabbit=1
else:
tortose=1
if rabbit==1:
print("you got rabbit")
elif rabbit==0 and tortose==1:
print("you got tortose")
else:
print("Bad Luck you dont have any match")
enter code here
what i did was just change n from n in range(3) to n in range(4) in line 14
import random as r
guessing = True
real_ans = r.randrange(1000, 10000, 2)
real_ans_str = str(real_ans)
correct = 0
class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(4):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False
while guessing:
Player()
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 am doing past coursework for practice, but I'm not sure what to do.
The task: create a game where the user has to guess a random 4 digit number(no repeated digits).
The problem: my code kind of works - like when you input a number with no repeating digits, it's fine, but when you enter, for example, 1223 I get the error:
TypeError: unsupported operand type(s) for divmod(): 'NoneType' and 'Int'
I have looked online and cannot find an answer. Any help would be greatly appreciated.
Thank you
Code below
import random
from collections import Counter
def rng():
num = []
i = 0
while i <=3:
rng = random.randrange(1,9)
if num.count(rng) == 0:
num.append(rng)
i+=1
return num
def menu():
userGuesses = 1
num = rng()#sort out a new num every time
print(num)
x = True
while x == True:
userExit = input("Would you like to exit(yes or no)")
if userExit == "yes":
print("Exiting...")
exit()
elif userExit == "no":
x = False
over = game(num)
while over !=True:
over = game(num)
userGuesses+=1
print("Congratulations you got it right, and it only took you ", userGuesses, " guesses!")
menu()
else:
print("Invalid entry")
def userInput():
userNum = int(input("Please enter a four digit number(no repeated digits)"))
if(userNum > 1000 or userNum < 9999):
print("...")
c = Counter(str(userNum))
if any(value > 1 for value in c.values()):
print ("Your number has repeating digits, please change it.")
else:
x = False
return userNum
else:
print("Invalid entry")
def convertToArray(userNum):
userArray = []
while userNum != 0:
userNum, x = divmod(userNum, 10)
userArray.append(int(x))
userArray.reverse()
print(userArray)
return userArray
def check(userArray, num):
i = 0
bulls = 0
cows = 0
while i<=3:
if num[i] == userArray[i]:
bulls +=1
elif int(userArray[i] in num):
cows +=1
i+=1
print("Bulls:")
print(bulls)
print("Cows:")
print(cows)
if bulls == 4:
return True
else:
return False
def game(num):
userNum = userInput()
userArray = convertToArray(userNum)
if check(userArray, num) == True:
return True
else:
return False
#Main-----------------------------------------------------------------
print("""Hello and welcome to the game \"Cows and Bulls\":
*In this game you enter a 4 digit number
*We compare it to a random number
*If you get the right number in the right 'place' then you get one bull
*If you get the right number in the wrong 'place then you get one cow'
*The game is over when you get 4 bulls, or all the numbers in the right place""")
menu()
Yes - your function doesn't actually return anything because of the print statements, hence an implicit None is returned - but there's another solution you can use.
Take advantage of the fact that userInput will return None if the input isn't valid. Have a condition just before userArray = convertToArray(userNum) to check if userNum is None:
def game(num):
userNum = userInput()
if userNum is None:
# Bad input was given
return False
userArray = convertToArray(userNum)
if check(userArray, num) == True:
return True
else:
return False
def userInput():
userNum = int(input("Please enter a four digit number(no repeated digits)"))
if(userNum > 1000 or userNum < 9999):
print("...")
c = Counter(str(userNum))
if any(value > 1 for value in c.values()):
print ("Your number has repeating digits, please change it.")
else:
x = False
return userNum
else:
print("Invalid entry")
when userNum is repeated, you return nothing. you should return something and pass it to convertToArray
import random
control = True
main = True
count = 0
user = input("Would you like to play Guess The Number?")
if (user == "yes"):
while (control == True):
randgen = random.randrange(0, 100)
print("Guess a random number")
while main == True:
number = int(input())
if (number == randgen):
print("Great Job you guessed the correct number")
print("You have tried ", count, "time(s)")
main = False
control = False
if (number < randgen):
count += 1
print("Your number is smaller than the random number")
print("You are at ", count, "trie(s)")
main = True
if (number > randgen):
count += 1
print("Your number is larger than the random number")
print("You are at ", count, "trie(s)")
main = True
again = int(input("Would you like to play again?1 for yes and 2 for no."))
if (again == 1):
control = True
user = ("yes")
if (again == 2):
control = False
print ("Ok bye bye")
##user ("no")
if (user == "no"):
print ("OK then Bye")
This Code works except for the part that when I want to play again it does not work. I have a coding background in java that's why I know some code but I made the guess the number game in java and I cannot figure out whats wrong with my python version(posted above).
Please make these changes:
if (again == 1):
control = True
main=True
user = ("yes")
I'm writing a simple warmer / colder number guessing game in Python.
I have it working but I have some duplicated code that causes a few problems and I am not sure how to fix it.
from __future__ import print_function
import random
secretAnswer = random.randint(1, 10)
gameOver = False
attempts = 0
currentGuess = int(input("Please enter a guess between 1 and 10: "))
originalGuess = currentGuess
while gameOver == False and attempts <= 6:
currentGuess = int(input("Please enter a guess between 1 and 10: "))
attempts += 1
originalDistance = abs(originalGuess - secretAnswer)
currentDistance = abs(currentGuess - secretAnswer)
if currentDistance < originalDistance and currentGuess != secretAnswer:
print("Getting warmer")
elif currentDistance > originalDistance:
print("Getting colder")
if currentDistance == originalDistance:
print("You were wrong, try again")
if currentGuess == secretAnswer or originalGuess == secretAnswer:
print("Congratulations! You are a winner!")
gameOver = True
if attempts >= 6 and currentGuess != secretAnswer:
print("You lose, you have ran out of attempts.")
gameOver = True
print("Secret Answer: ", secretAnswer)
print("Original Dist: ", originalDistance)
print("Current Dist: ", currentDistance)
It asks for input before I enter the loop, which is to allow me to set an original guess variable helping me to work out the distance from my secret answer.
However, because this requires input before the loop it voids any validation / logic I have there such as the if statements, then requires input directly after this guess, now inside the loop.
Is there a way for me to declare originalGuess inside the loop without it updating to the user input guess each iteration or vice versa without duplicating currentGuess?
Thanks
There doesn't seem to be a need to ask the user before you enter the loop... You can just check if guesses = 1 for the first guess...
gameOver=False
guesses = 0
while not gameOver:
guesses += 1
getUserInput
if guesses = 1 and userInput != correctAnswer:
print "try again!"
checkUserInput
print "good job!, it took you {} guesses!".format(guesses)
I am trying to make a game and I am really stuck. The problem is that I cant figur out how to use object oriented programming correctly. The program should launch gameboard function
everytime when the number doesnt equal to arv. It should return the new board with one "O"
less.
from random import randint
import time
class Game():
def __init__(self):
pass
def beginning(self):
print("How are you, and why are you playing my game?")
bla = str(input())
time.sleep(2)
print("Hello," + bla + ", I am glad to see you!")
time.sleep(2)
print("Anyways, the you have to guess a number from 1-20")
def gameboard(self):
self.__board = ["O","O","O","O","O"]
print(self.__board)
self.__board.pop()
return self.__board
def game(self):
number = randint(1,20)
print(number)
x = 1
arv = input()
self.arv__ = arv
while 5 > x:
if arv == number:
print("Lucky")
break
elif arv != number:
print ("haha, try again")
print("one life gone")
return gameboard()
print(self.board())
x += 1
def Main():
math = Game()
math.beginning()
math.game()
Main()
Using object-oriented programming when you only ever need one instance of the object tends to overcomplicate the program. I suggest having only one main function.
Nevertheless, I fixed your program. Try to find the changes yourself because I am too lazy to explain them, sorry.
from random import randint
import time
class Game():
def __init__(self):
pass
def beginning(self):
print("How are you, and why are you playing my game?")
bla = str(input())
time.sleep(2)
print("Hello," + bla + ", I am glad to see you!")
time.sleep(2)
print("Anyways, the you have to guess a number from 1-20")
self.__board = ["O","O","O","O","O"]
def gameboard(self):
print(self.__board)
self.__board.pop()
return self.__board
def game(self):
number = randint(1,20)
print(number)
x = 1
while 5 > x:
arv = input()
self.arv__ = arv
if arv == number:
print("Lucky")
break
elif arv != number:
print ("haha, try again")
print("one life gone")
self.gameboard()
print(self.__board)
x += 1
def Main():
math = Game()
math.beginning()
math.game()
Main()
Here is a version of your program that avoids OO and is much more simplified:
from random import randint
lives = 5
print("Guess a number from 1 to 20")
number = randint(1, 20)
while (lives > 1 and number != int(input())):
print("incorrect")
print("lives: " + "O" * lives)
lives -= 1
if lives == 0:
print("The number was actually " + str(number))
else:
print("You were right")