I am trying to create a program similar to the game Mastermind. I am having an issue in my while loop where it constantly prints "You got " + str(correct) + " correct!"
import random
import replit
def useranswer(input):
userinput.append(input)
return input
number = 0
answer = 0
guesses = 0
correct = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
for i in range(0,4):
answer = str(input('Give me a number: '))
useranswer(answer)
print(generation)
while userinput != generation:
guesses += 1
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got " + str(correct) + " correct! ")
correct = 0
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " + str(guesses) + " tries!")
If you want it to exit the while loop after printing the line print("You got " + str(correct) + " correct! ") then you'll need to do something within the while loop to make the check not true.
Right now if userinput != generation is true then it will loop forever because nothing in the loop ever changes that to be false.
You need to get the player's input within the while loop if you want it to keep looping until something happens, otherwise an if statement might be better.
Ive made couple of changes to your code. Take a look at it
Removed def userinput().
Moved userinput inside the while loop.
import random
import replit
number = 0
answer = 0
guesses = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
while userinput != generation:
guesses += 1
correct = 0
userinput = []
for i in range(0,4):
answer = int(input('Give me a number: '))
userinput.append(answer)
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got ",correct, " correct! ")
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " ,guesses, " tries!")
Related
i'm trying to make a guessing game, and i want to give the user 5 chances, but the loop keeps going after the chances given if the answer is incorrect.
if the answer is correct the program will print the losing text
i think the problem is with the value of full but the solutions i've tried broke the code
def proceso(ingreso, correcto, usos, usos_completos, usos_visibles, full):
if usos < usos_completos:
while ingreso != correcto and not full:
print("you have " + str(usos_visibles) + " chances")
ingreso = input("guess the word: ")
usos += 1
int(usos_visibles)
usos_visibles -= 1
else:
full = True
if full:
print("you lost. Correct answer was: " + correcto)
else:
print("you won")
palabra_secreta1 = "cellphone"
palabra_ingresada = ""
oportunidades = 0
limite_oportunidades = 5
contador_visible = 5
sin_oportunidades = False
print("5 oportunities")
proceso(palabra_ingresada, palabra_secreta1, oportunidades, limite_oportunidades, contador_visible, sin_oportunidades)
You should use break if the correct word is inputted and then count the number of chances taken in the while loop and then use else to print if the correct input has not been given after the desired number of attempts. I've removed some arguments because they seemed to be the same and I'm not sure what they mean, but maybe they're useful? Also, you should use f-strings for formatting variables into strings:
def proceso(correcto, usos_completos):
usos = 0
while usos != usos_completos:
print(f"you have {usos_completos-usos} chances")
ingreso = input("guess the word: ")
if ingreso == correcto:
print("you won")
break
else:
usos += 1
else:
print(f"you lost. Correct answer was: {correcto}")
palabra_secreta1 = "cellphone"
limite_oportunidades = 5
print("5 oportunities")
proceso(palabra_secreta1, limite_oportunidades)
I am creating a random number generator. I want to add up the guess tries I had for different trials and find the average. However, when I add up the list, it will only calculate how many guesses I had for the first trials divided by the number of trials. How could I fix this problem?
import random
import string
#get the instruction ready
def display_instruction():
filename = "guessing_game.txt"
filemode = "r"
file = open(filename, filemode)
contents = file.read()
file.close()
print(contents)
#bring the instruction
def main():
display_instruction()
main()
#set the random letter
alpha_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
letter = random.choice(alpha_list)
print(letter)
guess = ''
dist = []
number_of_guess = []
number_of_game = 1
guess_number = 1
game = True
if guess_number < 5:
rank = 'expert'
elif guess_number >= 5 and guess_number < 10:
rank = 'intermidiate'
else:
rank = beginner
while game == True:
guess_number = int(guess_number)
guess_number += 1
#add the input of user
guess = input("I am thinking of a letter between a and z" + "\n" + "Take a guess ")
#what happens if it is not a letter?
if guess not in alpha_list:
print("Invalid input")
elif alpha_list.index(guess) > alpha_list.index(letter):
print("too high")
dist.append(alpha_list.index(guess) - alpha_list.index(letter))
number_of_guess.append(guess)
#what happens if the guess is less than the letter?
elif alpha_list.index(guess) < alpha_list.index(letter):
print("too low")
dist.append(alpha_list.index(letter) - alpha_list.index(guess))
number_of_guess.append(guess)
elif guess == letter:
print("Good job, you guessed the correct letter!")
guess_number = str(guess_number)
print("---MY STATS---" + "\n" + "Number of Guesses:", guess_number + "\n" + "Level", rank)
replay = input("Would you like to play again? Y/N")
if replay == 'y' or replay == 'Y':
number_of_game += 1
game = True
else:
game = False
print(number_of_guess)
print("---MY STATS---" + "\n" + "Lowest Number of Guesses:" + "\n" + "Lowest Number of Guesses:" + "\n" + "Average Number of Guesses:", str(len(number_of_guess)/number_of_game))
If you want to get the average guesses per game, why you divide the length of the guess list? Why it is even a list? You can save it as an int do:
... "Average Number of Guesses:", (number_of_guess / number_of_game))
Also, note the following:
You initialize number_of_guess with 1, means that you will always count one more guess for the first round.
You do not choose a new letter between each round!
This is my current HiLo game, I want to integrate a menu with 4 options, 1. read csv file 2. play game 3. show results and 4. exit, any help is appreciated.
Because I don't know where to start.
import\
random
n = random.randint(1,20)
print(n)
guesses = 0
while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)
guesses = guesses + 1
if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break
if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")`enter code here`
You could place your game loop inside a menu loop, and all the code for csv file, etc. inside these loops...
However, it is surely preferable to learn a little bit about functions, in order to organize your code a little bit:
Here, I placed your game loop inside a function, and also created functions for the other options; right now, they only print what they should be doing, but as you add features, you will fill this with code.
import random
def read_csv():
print('reading csv')
def show_results():
print('showing results')
def play_game():
n = random.randint(1,20)
# print(n)
guesses = 0
while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)
guesses = guesses + 1
if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break
if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")
while True:
choice = int(input("1. read csv file 2. play game 3. show results and 4. exit"))
if choice == 4:
break
elif choice == 2:
play_game()
elif choice == 3:
show_results()
elif choice == 1:
read_csv()
I am new and a beginner. I need help condensing play_game() below. I need to get it to 18 lines. I would like to call the if and else function from within this code to shorten it by that many lines.
def play_game(): # def the plag game function which is the main control of the game
level = get_level()
quiz = game_data[level]['quiz']
print quiz
answers_list = game_data[level]['answers']
blanks_index = 0
answers_index = 0
guesses = 3
while blanks_index < len(blanks):
user_answer = raw_input("So what's your answer to question " + blanks[blanks_index] + "? : ") #while, if and else to increment the blanks, answers, and guesses
if check_answer(user_answer,answers_list,answers_index) == "right_answer":
print "\n Lucky Guess!\n"
quiz = quiz.replace(blanks[blanks_index], user_answer.upper()) #prints appropriate responses
blanks_index += 1
answers_index += 1
guesses = 3
print quiz
if blanks_index == len(blanks):
return you_win()
else:
guesses -= 1
if guesses == 0:
return you_lost()
break
print "Incorrect. Try again only " + str (guesses) + " guesses left!"
play_game()
Here's the play_game() subroutine reduced to 18 lines of code:
def play_game():
data = game_data[get_level()]
quiz, answers = data['quiz'], data['answers']
index, guesses = 0, 3
print quiz
while index < len(blanks):
user_answer = raw_input("So what's your answer to question " + blanks[index] + "? : ")
if check_answer(user_answer, answers, index) == "right_answer":
quiz = quiz.replace(blanks[index], user_answer.upper())
print "\nLucky Guess!\n\n" + quiz
guesses = 3
index += 1
else:
guesses -= 1
if guesses == 0:
return you_lost()
print "Incorrect. Try again only " + str(guesses) + " guesses left!"
return you_win()
Tricky to do without being able to actually run the code. Mostly just code cleanup.
I am a beginner coder for couple weeks and this is my first program after learning some basics. It is a hangman game but its a very crude version of it with no visuals (that will come later). When I run it, it allows me to pick one letter but then after that it gives me the error "noneType object is not iterable"
Can anyone explain why this is?
Sorry for the ultra-noobness in the quality of code but when I was browsing through other questions of similar errors, the code was too complex for me to apply to my situation
import time
import random
"""This is a hang man game
"""
name = input("what is your name?")
print("Hello" + " " + name)
time.sleep(1)
print("Ok, lets paly hangman, let me choose a word......")
time.sleep(1)
print("Thinking, thinking, thinking....")
time.sleep(3)
print("AHA! got it, ok " + name + ", take your first guess")
time.sleep(1)
def hangman_game():
word_list = ["herd", "heaven", "manly", "startle"]
number = random.randint(0, len(word_list) - 1)
secret_word = word_list[number] #chooses a word from the word list
blank_char = "-"
word_length = len(secret_word) * blank_char
word_length_split = list(word_length)
print("Try and guess the word: ", word_length) #displays the length of the word in '_'
previous_guesses = []
guesses_taken = 0
turns = 10
secret_word_list = list(secret_word)
while turns > 0:
letter_guessed = input("Pick a letter: ")
if letter_guessed in previous_guesses:
print("You have already guessed this letter")
else:
previous_guesses = previous_guesses.append(letter_guessed)
if letter_guessed in secret_word_list:
secret_word_list = secret_word_list.remove(letter_guessed)
guesses_taken = guesses_taken + 1
print("That is correct," + letter_guessed + " is in the word")
time.sleep(1)
else:
turns = turns - 1
guesses_taken = guesses_taken + 1
print("Try again")
print("Sorry mate, no turns left, play again?")
hangman_game()
change previous_guesses = previous_guesses.append(letter_guessed)
to previous_guesses.append(letter_guessed)
Also secret_word_list = secret_word_list.remove(letter_guessed)
to secret_word_list.remove(letter_guessed)
If you try the following:
In [5]: l = [1,2,3,4]
In [6]: print (type(l.remove(1)))
<class 'NoneType'>
if I used l = l.remove(1), I am setting it to a method which is a Nonetype as it does not return a list it mutates the original and returns None, not an updated list.
Appending is also the same:
`In [7]: print (type(l.append(5)))
<class 'NoneType'>`
`