I'm trying to make a game like Mastermind in Python but by using numbers [1-9] instead of colours. The game needs to be a little complex however and that is where I am struggling. I want to be able to randomly generate a password of 5 digits between [0-9] and make the user have 10 tries to get it right. If they guess a number correctly, I want to tell them where it is in their list and ask them to keep going as well. So far, I have this:
import random
random_password = [random.randint(0,9) for i in range (5)]
for counter in range (10):
guess = input ("Crack the Mastermind code ")
if guess != random_password :
print ("Guess again ")
#Here I am trying to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
elif guess
else print ("Sorry, you lose :( ")
if guess == random_password :
print ("Congrats, you win! ")
Any help is appreciated overflow bros, I am lost. I know that I need it to access items from a list. Would using a function like append work?
EDIT: This is my new code. Sorta works however my output is now showing it is wrong even when I guess the number correctly. It wants me to input with '' and , to separate the list but I shouldn't have to have the user do that to make the game function.
import random
random_password = [str (random.randint(0,9)) for i in range (5)]
for counter in range (10):
guess = input(str ("Crack the Mastermind code ") )
if guess != random_password :
print ("Guess again ")
#Here I am tryin to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
for i in random_password:
if(i in guess):
print (i)
if guess == random_password :
print ("Congrats, you win! ")
else :
print ("Sorry, you lose :( the correct answer was.... ")
print (random_password)
One way to do it quickly is to create a small function that will check if any of your string answer (from input) match with any characters of the password list
Also I change the order of your condition statement to make it more clear and efficient.
Finally I change your random_password from LIST to STRING because then you will be able to do guess == random_password properly.
Hope it helps!
PS:
IF you use Python2.X you should change input to raw_input (to get string value) else if you use Python3.X just keep it this way
import random
def any_digits(guess,password):
for character in guess:
if character in password:
return True
return False
random_password = ''.join([str(elem) for elem in [random.randint(0,9) for i in range (5)]])
print(random_password)
print(type(random_password))
for counter in range (10):
guess = input ("Crack the Mastermind code ")
if guess == random_password :
print ("Congrats you win! ")
elif any_digits(guess, random_password):
print ("Some numbers are correct! ")
else:
print ("Guess again ")
print("No more chances, you lose...")
print("The code was ", random_password)
Related
I'm new to coding and started with a python course now.
I was trying to work on a word bingo game but can't seem to make it work.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter your bingo words: ")
# split up the sentence into a list of words
list = bingo.split()
print
print "Okay, let's go! "
random.shuffle(list)
for choice in random.shuffle(list):
user = raw_input()
if user == "":
print(choice)
raw_input("")
else:
print "That's the end of the game ^.^"
break
#for words in range(len(list)):
#user = raw_input()
#if user == "":
#print(random.sample(list, 1))
#raw_input("")
#else:
#print "That's the end of the game ^.^"
#break
If i use choice in random.shuffle(list) I get a NonType error
before I used a for loop with random.sample (seen in the ## parts at the end)
That worked except in each iteration the words were still repeated.
I tried to search for similar questions but they all either had numbers or more automatic loops.
I want it so the user enters words, then each time they press enter, a new word appears from the list without repetition.
I can't seem to figure out how to get that into a loop - any help?
I tried to use random.choice and random.sample but the words still kept repeating in a for loop.
Tried shuffle and had a nonType error
Two comments:
Don't use list for variable name, it is a keyword in Python for type list
random.shuffle(l) does operation in-place (i.e. after you called it, l will be shuffled). So, you just supply l into the loop. Hope this helps.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter your bingo words: ")
# split up the sentence into a list of words
l = bingo.split()
print
print "Okay, let's go! "
random.shuffle(l)
for choice in l:
user = raw_input()
if user == "":
print(choice)
raw_input("")
else:
print "That's the end of the game ^.^"
break
P.S.
Why did you decide to use Python 2? If you are new to Python it can be better to work with Python 3. It is your decision to make. FYI, https://www.python.org/doc/sunset-python-2/#:~:text=We%20have%20decided%20that%20January,as%20soon%20as%20you%20can.
This is my code so far (in PyCharm), I am writing a very simple number guessing game that has integers from 1-9. I am still trying to master thought & flow as well as loops, and I hit a roadblock:
import random
Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)
guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))
def number_game():
if guess == random_num:
print(f"You guessed right, the number is confirmed to be {random_num}.")
else:
print(f"You guessed the wrong number. Try again.\n")
number_game()
I called the function and ran the code... everything appears to be working except I really can't figure out how to keep the game going in a loop until the player gets the right number out of 1-9...and end it when I need to. I tried searching all my resources and am quite stuck on this beginner practice coding. Any help is appreciated.
What I wrote and tried is above... googling and stackoverflow just confused me more.
Honestly, there are many ways to do what you want. But using your code as base, this is one possible solution.
import random
Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)
def number_game():
guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))
if guess == random_num:
print(f"You guessed right, the number is confirmed to be {random_num}.")
return True
else:
print(f"You guessed the wrong number. Try again.\n")
return False
while True:
guessed_right = number_game()
if guessed_right:
quit()
else:
number_game()
while True:
number_game()
Replace the last line of your script with this!
This question already has answers here:
Numeric comparison with user input always produces "not equal" result
(4 answers)
Closed 4 years ago.
whats up? I'm playing around with my mastermind project for school, only recently started dabbling into Python - and I've ran into a problem I simply cannot figure out? I've looked at other people's questions, who seem to have the same problem as me, but it seems to be more selective, and my code is kind of different. Can anyone tell me why whenever I reply to the question, it immediately skips to "Try again!", even if I know for a fact rnumber == tnumber? (Using Python 3.4.2).
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = input("Guess the four digit number. ")
type(tnumber)
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
elif rnumber != tnumber:
print ("Try again!")
numot = numot+1
you need to make your input an int so it considers it a number, try this
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = int(input("Guess the four digit number. "))
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
else rnumber != tnumber:
print ("Try again!")
numot = numot+1
#Guess my number
import random
print ("Welcome to the guess my number game")
print ("***********************************")
print ("You will choose a random number between 1-100")
print ("and the computer must guess what it is.")
print ()
number = int(input("Please choose a number between 1-100: "))
guesses = 0
guess = 0
while guess != number:
guess = ("My guess is: ",random.randint(1,100))
guesses=guesses+1
if guess > number:
print("Lower...")
continue
elif guess < number:
print ("Higher...")
else:
print ("Well done you have guessed my number and it took you") print ("guesses,"guesses!")
Basically you choose a number and the computer has to keep guessing until it gets it right but I can't seem to get it to work.
You should learn basic debugging skills. The simplest way to debug this program would be to add print() statements to see what values are in your variables.
Your basic problem is that you set guess to a tuple with two values: the string "My guess is: " and a random number from 1 to 100. You probably intended to set guess to just the number.
You probably want something like this:
guess = random.randint(1,100)
print("My guess is: {}".format(guess))
This will get you one step closer. Then you will need to figure out how to change the program so that it narrows down the guess range. If you have trouble with that, maybe you should find someone to tutor you a bit.
I have created a Python program that guesses the number programmer thinks in mind. Everything is working file but i don't know how to use guess in print statement in a way that print statement display number as well. I tried adding word "guess" but it is not working. I am C programmer and working with Python for the first time, so i am unable to figure it out.
hi = 100
lo = 0
guessed = False
print ("Please think of a number between 0 and 100!")
while not guessed:
guess = (hi + lo)/2
print ("Is your secret number " + //Here i need to Display the guessed Number + "?")
user_inp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too"
"low. Enter 'c' to indicate I guessed correctly: ")
if user_inp == 'c':
guessed = True
elif user_inp == 'h':
hi = guess
elif user_inp == 'l':
lo = guess
else:
print ("Sorry, I did not understand your input.")
print ("Game over. Your secret number was: " + //Here i need to display final number saved in guess.)
Just convert it to string.
print ("Game over. Your secret number was: " + str(guess))
You could also use string formatting.
print("Game over. Your secret number was {}".format(guess))
Or, since you come from a C background, old style string formatting.
print("Game over. Your secret number was %d." % guess)
Try this in your print statement and let me know if it works.
str(guess)
Python has very nice string formatting, which comes in handy when you need to insert multiple variables:
message = "Game over after {n} guesses. Your number was {g} (pooh... got it in {n} times)".format(g=guess, n=number)
print(message)