jamyn
jamyn

Reputation: 1943

letter/word guessing game in python

background

I'm attempting to code a basic letter game in python. In the game, the computer moderator picks a word out of a list of possible words. Each player (computer AI and human) is shown a series of blanks, one for each letter of the word. Each player then guesses a letter and a position, and are told one of the following:

That letter belongs in that position (the best outcome) That letter is in the word, but not in that position That letter is not in any of the remaining blank spaces When the word has been fully revealed, 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. In the basic game, both players share the same set of blanks they're filling in, so the players benefit from each other's work.

question

I'm working on the computer AI portion right now (bottom of the code). I want it to select a random letter from a list of letters that HAVEN'T already been guessed. What's the best way to do this?

import random

#set initial values
player1points= 0
ai= 0
userCorrectLetters= ''
aiCorrectLetters=''
wrongPlace=''
wrongLetters=''
correctLetters = ''
notInWord = ''
endGame = False
alreadyGuessed = 'a'
userGuessPosition = 0

###import wordlist, create mask
with open('/Users/jamyn/Documents/workspace/Lab3/Lab3/wordlist.txt') as wordList:
    secretWord = random.choice(wordList.readlines()).strip()

print (secretWord) 
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 ()


def addAlreadyGuessed():
    alreadyGuessed= userCorrectLetters + aiCorrectLetters + wrongLetters + correctLetters

def displayGame():
    print ('letters are in word but not in correct location:', wrongPlace)
    print ('letters not in word:', notInWord)
    ##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:
    print ('which character place would you like to guess. Enter number?')
    userGuessPosition = int(input())

    slice1 = userGuessPosition - 1  
    print (secretWord)  


    ##player types in letter
    guess = getUserGuess(wrongLetters + correctLetters)
    if guess== (secretWord[slice1:userGuessPosition]):
        correctLetters = correctLetters + guess
        print ('you got it right! ')
        break
    elif guess in secretWord:
            userCorrectLetters = userCorrectLetters + guess 
            correctLetters = correctLetters + guess
            print ('that letter is in the word, but not in that position')
            break
    else:
            wrongLetters = wrongLetters + guess
            print ('nope. that letter is not in the word')
            break

print ('its the computers turn')

aiTurn=True

while aiTurn == True:
    aiGuess=random.choice('abcdefghijklmnopqrstuvwxyz')
    print (aiGuess) 

Upvotes: 3

Views: 6251

Answers (1)

pyInTheSky
pyInTheSky

Reputation: 1479

use pythons set, keep a set containing all 26 letters, and a set of the ones guessed, and just ask for the elements in the large set that are not in the larger set http://docs.python.org/2/library/sets.html ... then pull your random choice from that result

allletters = set(list('abcdefghijklmnopqrstuvwxyz'))
usedletters = set() # update this as you go
availletters = allletters.difference(usedletters) #s - t    new set with elements in s but not in t

to print the sets out nicely, you can do

print sorted(availletters)

or

print ', '.join(sorted(availletters))

to answer your followup on adding guesses, here is a quick example

allletters = set(list('abcdefghijklmnopqrstuvwxyz'))
usedletters = set() # update this as you go
while( len(usedletters) != len(allletters) ):
    guessedletter = raw_input("pick a letter")
    availletters = allletters.difference(usedletters)
    usedletters.update(guessedletter)

you could also just have one list and subtract letters as they've been guessed, such as:

allletters = set(list('abcdefghijklmnopqrstuvwxyz'))
while( len(usedletters) != len(allletters) ):
    guessedletter = raw_input("pick a letter")
    allletters.difference_update(guessedletter)

Upvotes: 5

Related Questions