Variable initialization and loops - python-3.x

I'm new to coding and was trying to make a hangman game. My code works but it does not add and remove letters from the sets above. Could somebody please explain what I'm doing wrong. Thank you in advance. The code is written below;
from random_word import RandomWords
import string
lives = 160
number_of_plays = 0
all_letters = set(string.ascii_lowercase)
print("Please type a letter to play or 1 to quit")
print('You only have 6 chances to guess the correct word')
correct_word = RandomWords()
generated_word = correct_word.get_random_word() # a random word
while number_of_plays < lives:
player_command = input('> ').lower() # player letter input
generated_word_letters = set(generated_word) # tabulates letters in the aforementioned word
guessed_letters = set() # input from the player
correct_guessed_word = (letter if letter in guessed_letters else '_' for letter in generated_word)
if player_command == '1':
print('Game over')
break
elif player_command in all_letters:
guessed_letters.add(player_command)
if player_command in generated_word_letters:
generated_word_letters.remove(player_command)
print('Current correct guessed word: ', ''.join(correct_guessed_word))
continue
elif player_command not in generated_word_letters:
number_of_plays += 1
print('You have lost one life')
print('You have used these letters: ', ''.join(guessed_letters))
print('Current correct guessed word: ', ''.join(correct_guessed_word))
continue
elif player_command not in all_letters:
number_of_plays += 1
print('You have lost one life')
print('Please type in a letter!')

You are on the right track. You just made the mistake of initializing your sets inside the loop. So, what is happening is that every time your loop starts again, you are wiping out what was in them before. Simply initialize your sets before jumping into the loop as shown below. Note: I just overrode your RandomWords with a fixed word for troubleshooting. Nice game!
#from random_word import RandomWords
import string
lives = 160
number_of_plays = 0
all_letters = set(string.ascii_lowercase)
print("Please type a letter to play or 1 to quit")
print('You only have 6 chances to guess the correct word')
#correct_word = RandomWords()
generated_word = "lunch" #correct_word.get_random_word() # a random word
generated_word_letters = set(generated_word) # tabulates letters in the aforementioned word
guessed_letters = set() # input from the player
while number_of_plays < lives:
player_command = input('> ').lower() # player letter input
correct_guessed_word = (letter if letter in guessed_letters else '_' for letter in generated_word)
if player_command == '1':
print('Game over')
break
elif player_command in all_letters:
guessed_letters.add(player_command)
if player_command in generated_word_letters:
generated_word_letters.remove(player_command)
print('Current correct guessed word: ', ''.join(correct_guessed_word))
continue
elif player_command not in generated_word_letters:
number_of_plays += 1
print('You have lost one life')
print('You have used these letters: ', ''.join(guessed_letters))
print('Current correct guessed word: ', ''.join(correct_guessed_word))
continue
elif player_command not in all_letters:
number_of_plays += 1
print('You have lost one life')
print('Please type in a letter!')

Related

Python Word guessing game, cannot get While loop to repeat program

I am trying to create a word guessing game in python. I can get the program to run once,
but I want it to run five times in a row keeping track of wins and losses, and this is where
I am running into issues. I have tried adding a counter and nesting the while loop but this does not seem to work. Any help or suggestions would be greatly appreciated. Thanks.
Here is the code I have written:
import random
print('Welcome to the word guessing game!')
input("What is your name? ")
print('Try to guess the word letter by letter, you have ten guesses, good luck!')
words = ['cowboy', 'alien', 'dog', 'airplane',
'trees', 'bridge', 'snake', 'snow',
'popcorn', 'apples', 'road', 'smelly',
'eagle', 'boat', 'runner']
word = random.choice(words)
print("Guess the word!")
guesses = ''
trys = 5
wins = 0
losses = 0
rounds = 0
while rounds < 5:
while trys > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("*")
failed += 1
if failed == 0:
print("You Win")
print("The word is: ", word)
wins = wins + 1
rounds = rounds + 1
break
print()
guess = input("Enter your letter:")
guesses += guess
if guess != word:
trys -= 1
print("Plesae try again, You have", + trys, 'more guesses')
if trys == 0:
print("You Loose, better luck next time")
losses = losses + 1
rounds = rounds + 1
print('Wins:', wins )
print('Losses:', losses)

index-error: string out of range in wordle similar game

So i'm making a Wordle clone and i keep getting a "indexerror: string is out of range" and i dont know what to do and every time i do the second guess it will say indexerrror string is out off range
at line 30
import random
def Wordle():
position = 0
clue = ""
print("Welcome to Wordle, in this game your're going to be guessing a random word of 5 letters, if the word have a a correct letters it will tell you, if the letter is in the word but isn't at the place that it's supposed to be it will say that the letter is in the word but ins't at the correct place, and if it ins't at the word it will say nothing.And you only have 6 tries")
user_name = input("Enter your name:")
valid_words = ['sweet','shark','about','maybe','tweet','shard','pleat','elder','table','birds','among','share','label','frame','water','earth','winds','empty','audio','pilot','radio','steel','words','chair','drips','mouse','moose','beach','cloud','yours','house','holes','short','small','large','glass','ruler','boxes','charm','tools']
TheAnswer = random.choice(valid_words)
print(TheAnswer)
number_of_guesses = 1
guessed_correct = False
while number_of_guesses < 7 and not guessed_correct:
print(' ')
TheGuess = input('Enter your guess (it have to be a 5-letter word and not captalied letters):')
if len(TheGuess) > 5:
print('word is not acceptable')
else:
print(' ')
for letter in TheGuess:
if letter == TheAnswer[position]:
clue += ' V'
elif letter in TheAnswer:
clue += ' O'
else:
clue += ' F'
position += 1
print(clue)
if TheGuess == TheAnswer:
guessed_correct = True
else:
guessed_correct = False
number_of_guesses += 1
clue = ""
if guessed_correct:
print('Congradulations', user_name,', you won and only used', number_of_guesses,'guesses, :D')
else:
print(user_name,'Unfortunatealy you usead all your guesses and lost :( . the word was', TheAnswer)
You are indexing TheAnswer[position] which basically means if TheAnswer is x length long, then the position should be,
But since the position variable is a local variable of the function, it continuously increases on each guess. Does not get reset on each guess.
Try moving the
position = 0
Into top of the while loop.
Code,
import random
def Wordle():
clue = ""
print("Welcome to Wordle, in this game your're going to be guessing a random word of 5 letters, if the word have a a correct letters it will tell you, if the letter is in the word but isn't at the place that it's supposed to be it will say that the letter is in the word but ins't at the correct place, and if it ins't at the word it will say nothing.And you only have 6 tries")
user_name = input("Enter your name:")
valid_words = ['sweet', 'shark', 'about', 'maybe', 'tweet', 'shard', 'pleat', 'elder', 'table', 'birds', 'among', 'share', 'label', 'frame', 'water', 'earth', 'winds', 'empty', 'audio',
'pilot', 'radio', 'steel', 'words', 'chair', 'drips', 'mouse', 'moose', 'beach', 'cloud', 'yours', 'house', 'holes', 'short', 'small', 'large', 'glass', 'ruler', 'boxes', 'charm', 'tools']
TheAnswer = random.choice(valid_words)
print(TheAnswer)
number_of_guesses = 1
guessed_correct = False
while number_of_guesses < 7 and not guessed_correct:
position = 0
print(' ')
TheGuess = input(
'Enter your guess (it have to be a 5-letter word and not captalied letters):')
if len(TheGuess) > 5:
print('word is not acceptable')
else:
print(' ')
for letter in TheGuess:
if letter == TheAnswer[position]:
clue += ' V'
elif letter in TheAnswer:
clue += ' O'
else:
clue += ' F'
position += 1
print(clue)
if TheGuess == TheAnswer:
guessed_correct = True
else:
guessed_correct = False
number_of_guesses += 1
clue = ""
if guessed_correct:
print('Congradulations', user_name, ', you won and only used',
number_of_guesses, 'guesses, :D')
else:
print(
user_name, 'Unfortunatealy you usead all your guesses and lost :( . the word was', TheAnswer)
Thanks!

How do i make my input take all int and str type of data

I'm trying to get a guessing game with the user input as an answer and if the user type exit the game will show the amount of time the player tried but the program won't run because it can only take either interger or string type.
import random
while True:
number = random.randint(1,9)
guess = int(input('guess the number: '))
time = 0
time += 1
if guess == number:
print('you guessed correct')
elif guess < number:
print('your guessed is lower than the actual number')
elif guess > number:
print('your guessed is higher than the actual number')
elif guess == 'exit':
print(time)
break
something like this
import random
time = 0
number = random.randint(1,9)
while True:
guess = input('guess the number: ')
time += 1
if guess == "exit":
print(time)
break
elif int(guess) < number:
print('your guessed is lower than the actual number')
elif int(guess) > number:
print('your guessed is higher than the actual number')
elif int(guess) == number:
print('you guessed correct')
print(time)
break
note that time and number have to be initializate outside the while loop, because if not, we would get different random numbers for each iteration, and also time would be initializate to 0 each time.
You can test the input as a string first before converting it to an integer:
while True:
response = input('guess the number: ')
if response == 'exit':
break
guess = int(response)
# the rest of your code testing guess as a number

Why doesn't my hangman game work the way it's supposed to

import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
play_func()
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append()
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
I think the problem is here:
besides from no
if secret_word[x] == guess:
guess_word[x] == guess
print(guess_word)
if not '-' in guess_word:
print('You Won!')
break
else:
print('The letter is not in the word. Try Again!')
guess_taken += 1
if guess_taken == 8:
print('You Lost, the secret word was: ', secret_word)
change()
guessing()
print('Game Over!')
if secret_word[x] == guess:
guess_word[x] == guess
I think the problem is on these lines of code because they don't actually replace guess_word
This should hopefully get you on the right track. I just created a new method/function to contain all of your other functions, and fixed the append statement. Good Luck!
import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def main():
play_func()
change()
guessing()
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append(guess)
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
print(x)
main()

Python number guessing game not displaying feedback correctly. What's the problem?

So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()

Resources