I'm writing code with Python 2.7 that checks if a character is present in a input string but Python keeps skipping part of my if-statement.
Each time I run the code and enter a guess character value, the execution goes straight to the else statement and never executes the if(guess in PuzzleSetter) == True block at all.
What am I doing wrong?
PuzzleSetter = " "
List = []
def setPuzzle():
PuzzleSetter = raw_input("Puzzle setter set your word: ")
PuzzleSetter = PuzzleSetter.replace(" ", "")
print("Guessing player try guessing: "+PuzzleSetter.upper())
time.sleep(5)
print(chr(27) + "[2J")
List = [' __ ']*len(PuzzleSetter)
print("\n")
print(List)
while(True):
guess = raw_input("\nGuessing player make your guess: ")
if len(guess) != 1:
print("You are meant to enter a single letter")
continue
else:
guess = guess.upper()
print(guess)
if(guess in PuzzleSetter) == True:
finder = PuzzleSetter.find(guess)
print(PuzzleSetter+" contains "+str(PuzzleSetter.count(guess))+" "+guess+"'s")
for count in range(PuzzleSetter.count(guess)):
List[finder] = guess.upper()
finder = PuzzleSetter.find(guess, finder+1)
print(List)
if List.count("__") == 0:
print("Guessing player wins!")
break
else:
HangerMan()
enter += 1
if enter == 7:
print("Guessing player lost!")
print("\nPlayer two becomes the puzzle setter")
setPuzzle()
As I thought, you're leaving PuzzleSetter as input and not converting it to upper case like you are guess. If it contains any lower case letters they will never be found. Try this:
PuzzleSetter = raw_input("Puzzle setter set your word: ")
PuzzleSetter = PuzzleSetter.replace(" ", "")
PuzzleSetter = PuzzleSetter.upper()
print("Guessing player try guessing: "+PuzzleSetter)
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 just had a question about the code that I wrote below. I was just wondering about the if statement that I wrote with the "if guess not in secret_word:". When I run it as it's currently written, the condition doesn't even run or appear. However, when I swap it with the for statement which I wrote above, it runs just fine. I'm a bit new to programming, and I was just wondering if anyone could help me out with this. Why does the order of conditions matter here?
'''
import random
from words import words
secret_word = random.choice(words)
secret_letters = list(secret_word)
blanks = " _ " * len(secret_word)
already_guessed = []
lives = 10
print(blanks)
def valid_guess(): # function to make sure the letter guessed is valid (ie, not previously guessed)
is_letter = True
lives = 10
while True:
guess = (input("\nGuess a letter:"))
if guess in already_guessed:
print("You have already guessed this letter")
elif len(guess) != 1:
print("Please guess a single letter:")
is_letter = False
elif guess not in "abcdefghijklmnopqrstuvwxyz":
print("Please guess a LETTER:")
is_letter = False
if is_letter:
already_guessed.append(guess)
for guess in secret_word:
if guess in already_guessed:
print(guess + " ", end = "")
else:
print(" - ", end = "")
if guess not in secret_word:
lives -= 1
print(f"You lost a life! You only have {lives}/10 left!")
while True:
valid_guess()
'''
You could try this:
if guess in secret_word:
if guess in already_guessed:
print(guess + " ", end = "")
else:
print(" - ", end = "")
elif guess not in secret_word:
lives -= 1
print(f"You lost a life! You only have {lives}/10 left!")
I've recently wrote 'hangman' in python. Then added few things and now I am trying to clean this up a bit.
Any ideas how to get rid of these two while (...) true statements?
Also I think there's too many if (...) else statements.
Any tips and other suggestions would be appreciated :)
word = "stackoverflow"
user_word = []
used_letters = []
def find_indexes(word, letter):
indexes = []
for index, letter_in_word in enumerate(word):
if letter == letter_in_word:
indexes.append(index)
return indexes
for _ in word:
user_word.append("_")
while True:
try:
no_of_tries = int(input("Enter number of tries: "))
break
except ValueError:
print("Enter numeric value :)")
while True:
letter = input("Enter a letter: ").lower()
if letter.isalpha():
if len(letter) == 1:
used_letters.append(letter)
found_indexes = find_indexes(word, letter)
if len(found_indexes) == 0:
print("There's no such letter in your word :(")
no_of_tries -= 1
print("Tries left: ", no_of_tries,)
if no_of_tries == 0:
print("It was nice...to meet you")
# sys.exit()
else:
for index in found_indexes:
user_word[index] = letter
whole_word = "".join(user_word)
if whole_word == word:
print("WOW, VICTORY!!! :D")
print("".join(user_word))
print("Used letters: ", used_letters )
else:
print("Enter ONE letter")
else:
print("Enter letter")
Your loop is even continuing if the word is complete or the chances are over.
Use a variable in the while loop:-
playing = True
while playing:
And to over the thing use this:-
if no_of_tries == 0:
print("It was nice...to meet you")
playing = False
if whole_word == word:
print("WOW, VICTORY!!! :D")
playing = False
Too broad question, perhaps.
A good rule is to handle trivial cases first and do the main processing last:
while True:
letter = input("Enter a letter: ").lower()
if not letter.isalpha():
print("Enter letter")
continue
if len(letter) != 1:
print("Enter ONE letter")
continue
used_letters.append(letter)
... etc ...
Notice how the indentation level has decreased.
There is one small problem with my code , after I get all the letters correct, I had to enter another letter only it will show that I got it right. What is the problem?
import random
import string
import sys
def split(word):
return list(word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
list(alphabet)
words = ['hat','pop' ,'cut' , 'soup' , 'you' , 'me' , 'gay' , 'lol' ]
guess_word = []
wrong_letters_storage = []
secret_word = random.choice(words)
word_length = print("the length of the word is " + str(len(secret_word)))
correct_letters = split(secret_word)
def words():
for letter in secret_word:
guess_word.append("-")
return print("the words that you are guessing is " + str(guess_word))
def guessing():
while True:
c = 0
b = 7
while c <= 7:
print("")
hide = ""
print("you have " + str(b) + " guess left")
print("Wrong letters : " + str(wrong_letters_storage))
command = input("guess: ").lower()
if not '-' in guess_word:
print("you win!")
break
elif command == 'quit':
print("thank you for playing my game")
break
else:
if not command in alphabet :
print("pick an alphabet")
elif command in wrong_letters_storage:
print("you have picked this word")
else :
if command in secret_word :
print("right")
c += 1
b -= 1
for x in range(0, len(secret_word)):
if correct_letters[x] == command:
guess_word[x] = command
print(guess_word)
elif not command in secret_word :
print("wrong")
wrong_letters_storage.append(command)
c += 1
b -= 1
else :
print("error")
print("*"*20)
return print("Thank you for playing my game")
words()
guessing()
print("the words that you are guessing is " + secret_word )
Your code has several "problems":
you check if the current solution has no more '-' in it, after you ask for the next character input()
return print("whatever") returns None because the print function prints and returns None
you use variables with single_letter_names that make it hard to know what they are for
you use list's instead of set()'s for lookups (its fine here, but not optimal)
You can fix your problem by moving the test statement before the input() command:
# your code up to here
while True:
c = 0
b = 7
while c <= 7:
if not '-' in guess_word:
print("you win!")
break
print("")
hide = ""
print("you have " + str(b) + " guess left")
print("Wrong letters : " + str(wrong_letters_storage))
command = input("guess: ").lower()
if command == 'quit':
print("thank you for playing my game")
break
else:
# etc.
It would probably be better to do some more refaktoring:
import random
import string
import sys
def join_list(l):
return ''.join(l)
def guessing():
# no need to put all this in global scope
alphabet = frozenset(string.ascii_lowercase) # unchangeable set of allowed letters
words = ['hat', 'pop', 'cut', 'soup', 'you', 'me', 'beautiful', 'lol']
secret = random.choice(words) # your random word
secret_word = list(secret.lower()) # your random word as lowercase list
wrong = set() # set of wrongly guessed characters
right = set() # set of already correctly guessed characters
correct = frozenset(secret_word) # set of letters in your word, not changeable
guess_word = ['-' for k in correct] # your guessed letters in a list
guesses = 7
guessed = 0
print("The length of the word is ", len(secret))
# loop until breaked from (either by guessing correctly or having no more guesses)
while True:
print("")
print(f"you have {guesses-guessed} guess left")
if wrong: # only print if wrong letters guessed
print(f"Wrong letters : {wrong}")
# print whats know currently:
print(f"Guess so far: {join_list(guess_word)}")
command = input("guess: ").strip().lower()
try:
if command != "quit":
command = command[0]
except IndexError:
print("Input one letter")
continue
if command == 'quit':
print("thank you for playing my game")
break
else:
if command not in alphabet:
print("pick an alphabet")
continue
elif command in (wrong | right):
print("you already picked this letter")
continue
else :
guessed += 1
# always lookup in set of lowercase letters
if command in correct:
right.add(command)
for i,letter in enumerate(secret_word):
if command == letter:
# use the correct capitalisation from original word
guess_word[i] = secret[i]
else:
print("wrong")
wrong.add(command)
print("*"*20)
# break conditions for win or loose
if join_list(secret_word) == join_list(guess_word):
print("You won.")
break
elif guessed == guesses:
print(f"You lost. Word was: {join_list(secret_word)}")
break
guessing()
I'm working on finishing my first simple program in python, a 2 player (user vs computer AI) word/letter guessing game.
I've got the bulk of the code finished, but I'm trying to get my loops sorted out so that the game will properly alternate between the user and the AI. I want to make it so that the game alternates back and forth between user and AI turns, until the world has been fully revealed. At that point, the player to guess the most letters correctly wins a point. The computer moderator picks another word and starts again. The first player to five points wins the game.
I'm not sure where to start with this. I'm still quite new to python/coding in general and I have a difficult time understanding the order in which events occur. I know I need some kind of master loop that remains True as long as the word has yet to be fully revealed, but that's about it.
Also, any other suggestions as to how to optimize the code below or clean it up in anyway would be appreciated!
import random
#set initial values
player1points= 0
ai= 0
userCorrectLetters= ''
aiCorrectLetters=''
wrongLetters=''
wrongPlace= ''
correctLetters = ''
notInWord = ''
endGame = False
allLetters = set(list('abcdefghijklmnopqrstuvwxyz'))
alreadyGuessed = set()
userGuessPosition = 0
availLetters = allLetters.difference(alreadyGuessed)
#import wordlist, create mask
with open('wordlist.txt') as wordList:
secretWord = random.choice(wordList.readlines()).strip()
print (secretWord)
secretWordLength = len(secretWord)
def displayGame():
mask = '_' * len(secretWord)
for i in range (len(secretWord)):
if secretWord[i] in correctLetters:
mask = mask[:i] + secretWord[i] + mask [i+1:]
for letter in mask:
print (letter, end='')
print (' ')
print ('letters in word but not in correct location:', wrongPlace)
print ('letters not in word:', wrongLetters)
##asks the user for a guess, assigns input to variable
def getUserGuess(alreadyGuessed):
while True:
print ('enter your letter')
userGuess = input ()
userGuess= userGuess.lower()
if len(userGuess) != 1:
print ('please enter only one letter')
elif userGuess in alreadyGuessed:
print ('that letter has already been guessed. try again')
elif userGuess not in 'abcdefjhijklmnopqrstuvwxyz':
print ('only letters are acceptable guesses. try again.')
else:
return userGuess
def newGame():
print ('yay. that was great. do you want to play again? answer yes or no.')
return input().lower().startswith('y')
userTurn=True
while userTurn == True:
displayGame ()
print ('which character place would you like to guess. Enter number?')
userGuessPosition = int(input())
slice1 = userGuessPosition - 1
##player types in letter
guess = getUserGuess(wrongLetters + correctLetters)
if guess== (secretWord[slice1:userGuessPosition]):
correctLetters = correctLetters + guess
print ('you got it right! ')
displayGame()
break
elif guess in secretWord:
wrongPlace = wrongPlace + guess
print ('that letter is in the word, but not in that position')
displayGame()
break
else:
wrongLetters = wrongLetters + guess
print ('nope. that letter is not in the word')
displayGame()
break
print ("it's the computers turn")
aiTurn=True
while aiTurn == True:
aiGuessPosition = random.randint(1, secretWordLength)
print (aiGuessPosition)
aiGuess=random.sample(availLetters, 1)
print ('the computer has guessed', aiGuess, "in position", + aiGuessPosition)
if str(aiGuess) == (secretWord[slice1:userGuessPosition]):
correctLetters = correctLetters + guess
print ('this letter is correct ')
break
elif str(aiGuess) in secretWord:
aiCorrectLetters = aiCorrectLetters + guess
correctLetters = correctLetters + guess
print ('that letter is in the word, but not in that position')
break
else:
wrongLetters = wrongLetters + guess
print ('that letter is not in the word')
break
displayGame()
break
It looks like it will only do two turns and then exit?
What is happening is that it hits your first while loop, and starts to evaluate the code inside. It does some stuff, and then hits the break which breaks you out of the loop and execution resume after the end of your first loop. It then does the same thing with the second loop, hits the end of you program and exits.
I would suggest the following refactoring:
put all of the stuff you have under your while loops into two function user_play and computer_play
write a loop something like
this
usr_pts = 0
cmp_pts = 0
while (usr_pts < 5 and cmp_pts < 5):
solved_word = False
# set up word
user_turn = False
user_correct_guess = 0
ai_correct_guess = 0
while not solved_word:
user_turn = not user_turn
if user_turn:
guess = play_user(...)
else:
guess = computer_play(...)
# what ever accounting you need to do
is_guess_in_word = test_guess_in_word(guess, ...)
if is_guess_in_word:
if user_turn:
user_correct_guess += 1
else:
ai_correct_guess += 1
solved_word = sort_out_if_word_solved(...)
if user_correct_guess > ai_correct_guess:
usr_pts += 1
elif user_correct_guess < ai_correct_guess:
cmp_pts +=1
else:
# a tie
pass