I have made a basic number guessing python game in which we have a number in mind and the ai will try to guess it but when I ran it , it just asks me the same number. What should I do? I have tried to use many things but it doesn't work.
import random
print("""
Hello there my friend
I am an AI
I have been made for a very Specific game
and i would like you to play
It is an number guesser
You will think of a number
and I will try to guess it
and you would say higher or lower
LEts Start
""")
print("Okk so what is the range?:")
rang = int(input())
print("Lets Start. Say (h) for higher and (l) for Lower and (c) for Correct!")
aig = random.randint(1, rang)
print("Is " + str(aig) + "the number?")
newag = 1
def newter():
newag - 1
def fewter():
newag + 1
while True:
letter = input()
if letter == "h":
fewter()
print("Is " + str(newag) + "the number?")
if letter == "l":
newter()
print("Is " + str(newag) + "the number?")
if letter == "c":
print("Finnally i got that Right")
else:
print("Sorry but i cant understand")
Try in newter and fewter put global newag in the beginning of the function, so it will permanently change the value of newag instead of discarding it after the function.
also you need to change newag - 1 and newag + 1 to newag -= 1 (newag = newag - 1) and newag += 1 (newag = newag + 1) to actually change the value, otherwise you are just saying what is newag minus one? and then it gets rid of the result.
Related
The word_chosen is "apple". However, when I enter the letter p, it only appears once in the word. I would also like to make my loop reset when the letter entered is not correct.
def guesses():
guess = 0
hangman_word = "_____"
while guess < 5:
guess_player = input("What is your letter? ")
for i in range(len(word_chosen)):
if guess_player == word_chosen[i]:
guess_player = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
print(guess_player)
continue
elif guess_player != word_chosen[i]:
guess += 1
Some issues:
The following assignment is wrong:
guess_player = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
You should not update guess_player which is the input letter. Instead you should update hangman_word. So:
hangman_word = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
The following condition will always be true when the execution gets there:
elif guess_player != word_chosen[i]:
The opposite was already checked in the preceding if statement, so the only possibility left is that the guess was wrong. No need to test that again.
guess += 1 should not appear within the loop. If the guess does not match the first letter, that doesn't mean it cannot still match with the second letter. So it is wrong to increment this counter when the comparison has not yet been made with all remaining letters of the secret word.
You can make use of the in operator to check whether there is at least one occurrence of the guessed letter:
if guess_player in word_chosen:
# ... here comes your loop to update `hangman_word` ... (without `elif`)
else:
guess += 1
The while loop should exit not only when the player has made five wrong guesses, but also if the player has found the word! You can do that as follows:
while guess < 5 and "_" in hangman_word:
When the while loop exits, you should probably report on the outcome of the game. Was it a success or not? It could be:
if "_" in hangman_word:
print("You guessed 5 times wrong. Game over.")
else:
print("You guessed the word. Well done!")
There should probably be some message when the player repeats a good guess a second time (optional).
Here is your code with corrections for the above points:
def guesses():
guess = 0
hangman_word = "_____"
while guess < 5 and "_" in hangman_word:
guess_player = input("What is your letter? ")
if guess_player in hangman_word:
print("But...but... you already guessed that letter!?")
elif guess_player in word_chosen:
print("Good going!")
for i in range(len(word_chosen)):
if guess_player == word_chosen[i]:
hangman_word = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
else:
print("That letter does not occur in the word.")
guess += 1
print(hangman_word)
if "_" in hangman_word:
print("You guessed 5 times wrong. Game over.")
else:
print("Well done!")
A couple aspects of the code can be improved.
def guesses():
# PreEnter the word for referece
word_chosen = "hangman"
guess = 0
# Creating a list instead of a string, to be able to update it, rather than creating new ones.
hangman_word = ["_" for _ in range(len(word_chosen))]
# Storing entered letters in a list for fair play in case wrong letters are entered.
entered_letters = []
while guess < 5:
guess_player = input("Enter a Letter: ")
# Checking if enterd string contains a single letter
if len(guess_player) > 1:
print("You can only enter one letter at a time.")
continue
if guess_player in entered_letters:
print("You already guessed that letter")
continue
# Using for loop only after checking if the letter is in the word.
elif guess_player in word_chosen:
for i in range(len(word_chosen)):
if guess_player == word_chosen[i]:
hangman_word[i] = guess_player
else:
print("That was an incorrect choice!")
guess += 1
# appending the entered letter to the list of entered letters.
entered_letters.append(guess_player)
# Using "".join to print the string from the list.
word = "".join(hangman_word)
print(word)
# Checking if the word is complete.
if word == word_chosen:
return "You Win!"
# If the player runs out of guesses, the game is over.
return "You Lose!"
print(guesses())
Since you are a beginner, try understanding the code through comments and see if you can figure out which aspects of your code I altered. Feel free to point out anything you have doubts about.
sRealWord = input("Write the Hangman Word in Capital Letters: ")
lShownWord = ["_"] * len(sRealWord)
sInput = ""
iAllowedGuesses = 10
iLetterNumber = 0 #was []
iRightGuesses = 0 #was []
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
print("Let the Game Begin!")
print("Type END to close game, or complete your 10 guesses")
while(sInput != "END" and iAllowedGuesses != 0):
print("The word you're looking for is: " + str(lShownWord)) ##FIXED
print("You have: " + str(iAllowedGuesses) + " guesses left") ##FIXED
sInput = input("Enter letter in Capital Letters: ")
iAllowedGuesses -= 1 ##VALUE 1 ##FIXED
while(iLetterNumber < len(sRealWord)) : **###THIS IS NOT WORKING**
if (sRealWord[iLetterNumber] == sInput) :
lShownWord[iLetterNumber] == sInput
iRightGuesses += 1
iLetterNumber += 1
iLetterNumber = 0
elif (iRightGuesses == len(sRealWord)): ###**THIS IS NOT WORKING**
print("Woho!, You've won!")
elif (iAllowedGuesses == 0):
print("You are out of guesses, Game Over!") ###fixed
break
I decided to take an old Hangman code from Python 2 and migrate into Python 3 for practice.
The lines that I think are preventing the code from working correctly are commented out and in bold.
What am I missing or doing wrong in the code or those lines that needs to be done differently or fixed in order for the game to work?
FYI
The output for running out of guesses is working. Although, the output of getting right guesses is not working, therefore, when you get the word right it just continues as if they are wrong.
There are multiple issues that I see. But none seem to have to do with python2 vs python3.
You probably want to assign the sInput to the lShownWord[iLetterNumber] if it is correct. For that, you need only a single =.
There is no point in incrementing iLetterNumber right before setting it to zero. I assume what you want to do is check every letter of the word, every time the user enters a word. You can do that with a while loop and resetting the variable manually, but it's more idiomatic and slightly leass error prone with a for loop. The for loop resets the counter variable automatically, and increments it every loop iteration.
Careful with the indentation. You don't want to first have the user try iAllowedGuesses times before showing the correct characters. Both the while loop and the ifs were in the wrong place. And once you put the if statements to the correct level of indentation, elif does not make sense there anymore.
You probably also want to break if the user has won.
This leaves us with this code.
sRealWord = input("Write the Hangman Word in Capital Letters: ")
lShownWord = ["_"] * len(sRealWord)
sInput = ""
iAllowedGuesses = 10
iRightGuesses = 0 #was []
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
print("Let the Game Begin!")
print("Type END to close game, or complete your 10 guesses")
while(sInput != "END" and iAllowedGuesses != 0):
print("The word you're looking for is: " + str(lShownWord)) ##FIXED
print("You have: " + str(iAllowedGuesses) + " guesses left") ##FIXED
sInput = input("Enter letter in Capital Letters: ")
iAllowedGuesses -= 1 ##VALUE 1 ##FIXED
for iLetterNumber in range(len(sRealWord)) :
if (sRealWord[iLetterNumber] == sInput) :
lShownWord[iLetterNumber] = sInput
iRightGuesses += 1
if (iRightGuesses == len(sRealWord)):
print("Woho!, You've won!")
break
if (iAllowedGuesses == 0):
print("You are out of guesses, Game Over!")
break
I'm trying to make a hangman game. At the moment I'm still trying to figure out how to store users inputted strings in a variable.
I need this because if a user guesses the word before the ten guesses it keeps asking them for another letter.
I've tried creating a variable and then updating the variable as the user entered more letters. However that doesn't work in cases the user doesn't enter all the letters in the correct order the program is obviously not going to recognize this as the correct word.
Basically I need a way to store the inputted strings (one letter at a time) and to be able to check if all of those letters are contained in the five letter word.
import random
print("Welcome to hangman, guess the five letter word")
words =["china", "ducks", "glass"]
correct_word = (random.choice(words))
trials = 10
for trial in range(trials):
guess = input(str("Enter Character:"))
if (len(guess) > 1):
print("You are not allowed to enter more than one character at a time")
continue
if guess in correct_word:
print("Well done " + guess + " is in the list!")
else:
print("Sorry " + guess + " is not included")
It seems like a set is what you need.
You start with an empty set() and add the letter every time. To check if the letters are enough, use saved_set == set(correct_word).
With the help of an auxiliar list, this little guy will do the trick (I put some comments to better explain what I did):
import random
import sys
print("Welcome to hangman, guess the five letter word")
words =["china", "ducks", "glass"]
correct_word = (random.choice(words))
trials = 10
trial = 0
#the list starts empty, since the user didn't guessed any letter
guessed_letters = []
while(trial < trials):
guess = input(str("Enter Charcter:"))
if (len(guess) > 1):
print("You are not allowed to enter more than one charcter at a time")
continue
if (guess in correct_word) and (guess not in guessed_letters):
#once our user guesses a letter that he didn't guessed before, it will be added to our list of guessed letters
print("Well done " + guess + " is in the list!")
guessed_letters += guess
#in here we compare the size of the list with the size of the correct_word without duplicates
#if it's the same size, boom: the user won!
if (len(guessed_letters) == len(set(correct_word))):
print("Congratulations! You won!")
sys.exit()
else:
#just to avoid confusing the user with duplicate letters
if (guess in guessed_letters):
print("You already tried letter " + guess + "! Try another letter")
trial -= 1
else:
print("Sorry " + guess + " is not included")
print("Remaining chances: " + str(trials - trial))
trial += 1
print("\n\n\nGame over!!!!")
All you need is to replace:
guess = input(str("Enter Charcter:"))
by:
guess = str(sys.stdin.readline().rstrip('\n'))
Thank you for your patience everyone.
Thank you Ben10 for your answer. (posted below with my corrected print statements) My print statements were wrong. I needed to take the parenthesis out and separate the variable with commas on either side.
print("It only took you ", counter, " attempts!")
The number guessing game asks for hints after a certain number of responses as well as the option to type in cheat to have number revealed. One to last hints to to let the person guessing see if the number is divisible by another number. I wanted to have this hint available until the end of the game to help narrow down options of the number.
Again thank you everyone for your time and feedback.
guessing_game.py
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: ", random_) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 10:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by ", divisor, ". ")
else:
print("Not it quite yet, The random number is NOT divisible by ", divisor, ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is ", cheat, ".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you ", counter, " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")
I rewrite the code, to allow it to be more versitile. Noticed quite a few errors, like how you forgot to put a closing bracket at the end of a print statement. Also in the print statements you were doing String concatenation (where you combine strings together) incorrectly.
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: " + str(random_)) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 5:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by " + str(divisor) + ". ")
else:
print("Not it quite yet, The random number is NOT divisible by " + str(divisor) + ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is " + str(cheat) +".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you " + str(counter) + " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")
I am working on a guessing game in python, i think i have everything only, i want to make the program to guess between numbers it already guessed for example, if the users number is 5, and it picks 3 the user input '+' and it knows the number is higher, and if the program guess 6 the user input '-' and it knows the number is lower than 6, but sometimes it guesses a 2, its obvious that if the number is higher than 3 it can't possibly be 2 right, so how do i write that? I am a beginner at this and i would appreciate if you could make it simple, below is my code.
print("Hello,")
print("welcome to the guessing game")
print('I shall guess a number between 1 and 99, and then ask you if am right')
print('I have a maximum of 20 chances\n')
import random
guess = random.randint(1,99)
print("Your number is %f, Am i right?" % guess)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
print("You chose %s" % ans)
minguess = 1
maxguess = 99
count = 0
while (count < 20):
count = count + 1
if ans == '+':
##I am using these prints to keep track of the numbers and if everything is working correctly
maxguess1 = guess + 1
print('THe maxguess is', maxguess1)
newguess = random.randint(maxguess1, maxguess)
print('The newguess is', newguess)
newguess = int(newguess)
print("Is it %d?" % newguess)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
elif ans == "-":
maxguess2 = guess - 1
print('The minus maxguess is', maxguess2)
newguess = random.randint(minguess, maxguess2)
print('The minus newguess is', newguess)
newguess1 = int(newguess)
print("Is it %d?" % newguess1)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
if ans == "=":
print('YAAAAAAS MAN')
i wanted it to change the numbers whenever it guessed a new number
guess = newguess
NOTE: This example is in Python 2.7, NOT Python 3, but the concepts are the same.
Break down the problem into its individual elements:
import random
# Possible Range is [1-99], 1 inclusive to 99 inclusive
min_possible = 1
max_possible = 99
# Number of Guesses
max_guesses = 20
# Process
for i in xrange(max_guesses): # Loops through the process 'max_guesses' times
# Program Takes a Guess
guess = random.randint(min_possible, max_possible)
print 'My guess is ' + str(guess)
# Ask for User Feedback
user_feedback = ''
while not user_feedback in ['+', '-', '=']:
user_feedback = raw_input('Is the number higher (+), lower (-), or equal (=) to my guess?')
# Use the User Feedback
if user_feedback == '+':
min_possible = guess + 1 # B/c low end is inclusive
elif user_feedback == '-':
max_possible = guess - 1 # B/c high end is inclusive
else:
print 'I knew the answer was ' + str(guess)
break