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:
while
loops into two function user_play
and computer_play
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.