NLTK: Slot Machine


Enter Letters, Get Lucky

Today we’re going to build a variant of the classic slot machine. However, rather than the traditional game, we’re adding our own twist. In place of matching symbols, we will try to generate valid English words.

To further develop this idea, we’ll give the user more of an input on the game. The user will be asked to enter 3 letters, with a minimum of 1 vowel. We’ll generate all possible permutations of the three letters, and then generate an NLTK corpus of valid English words to cross-reference our permutations and identify the possible valid words that will result in a ‘win’.

We want the game to run multiple times, so let’s also add a user control to ‘pull’ the slot machine’s lever with the space bar specifically, any other key will end the simulation.

Let’s start with our modules!

Imports

Imports
import itertools
from msvcrt import getch
from nltk.corpus import words
import random
#Note: Need to install nltk.words before use

Class

class LetterToWordSlotMachine():

Building Words Through User Interaction

Let’s build the aforementioned user input, to acquire the letters they prefer to use.

Collecting Target Letters Via User Input
    def letterCollector(self):
        cases = ["A", "E", "I", "O", "U"]
        active = bool
        while active:
            char1 = input("Enter a Vowel")
            if char1.upper() in cases:
                break
            else:
                print("Try Again, Enter A, E, I, O, or U")
        while active:
            char2 = input("Enter a Vowel or Consonant")
            if char2.isdigit():
                print("Error, please enter a letter")
            else:
                break
        while active:
              char3 = input("Enter another Vowel or Consonant")
              if char3.isdigit():
                  print("Error, please enter a letter")
              else:
                  break
        letters = [char1.lower(), char2.lower(), char3.lower()]
        return letters


Are These Words Real? Let’s Do A Validation Test.

Now, we can cross-reference our permutations with the NLTK Corpus results, and return a list of our letters and our valid permutations.

Generate an NLTK Corpus of Valid Dictionary Words Using Collected Letters
    def valid_words_generator(self):
        validPermutations = []
        checking = bool
        while checking:
            letters = LetterToWordSlotMachine().letterCollector()
            permutations = [''.join(i) for i in itertools.product(letters, 
                                                                  repeat = 3)]
            for each in permutations:
                if each in words.words():
                    validPermutations.append(each)
            if not validPermutations:
                print("No words could be generated, please enter new letters")
            else:
                break
        print(', '.join(validPermutations))
        return letters, validPermutations

The Slot Machine

Here’s the guts of the logic. We’ll input our parameters, letters and wordlist and use a random generator to build each word upon each press of the space bar via getch().

    def slot_machine(self, letters, wordlist):
        pullLever = bool
        while pullLever:
            a = random.choice(letters)
            b = random.choice(letters)
            c = random.choice(letters)
            result = a.upper()+b+c
            print(result)
            if result.lower() in wordlist:
                print("Success")
                print("Try Again?\nPress Space to Pull the Lever\n\
                                      Press Any Other Key to Quit")
                keypress = ord(getch())
                if keypress == 32:
                   pass
                else:
                    break
            else:
                print("Fail")
                print("Try Again?\nPress Space to Pull the Lever\n\
                                       Press Any Other Key to Quit")
                keypress = ord(getch())
                if keypress == 32:
                    pass
                else:
                    break
        return None

Try:


Try Again:


Run It



if __name__ == "__main__":
    run = LetterToWordSlotMachine()
    userLetters, userWords = run.valid_words_generator()
    run.slot_machine(userLetters, userWords)


Bringing It All Together: A Code Summary

import itertools
from msvcrt import getch
from nltk.corpus import words
import random
import nltk

class LetterToWordSlotMachine(object):

   def letterCollector(self):
      cases = ["A", "E", "I", "O", "U"]
      active = bool
      while active:
         char1 = input("Enter a Vowel\n")
         if char1.upper() in cases:
            break
         else:
            print("Try Again, Enter A, E, I, O, or U")
      while active:
         char2 = input("Enter a Vowel or Consonant\n")
         if char2.isdigit():
            print("Error, please enter a letter\n")
         else:
            break
      while active:
         char3 = input("Enter another Vowel or Consonant\n")
         if char3.isdigit():
            print("Error, please enter a letter\n")
         else:
            break
      letters = [char1.lower(), char2.lower(), char3.lower()]
      return letters

   def valid_words_generator(self):
      validPermutations = []
      checking = bool
      while checking:
         letters = LetterToWordSlotMachine().letterCollector()
         permutations = [''.join(i) for i in itertools.product(letters,
                                                               repeat=3)]
         for each in permutations:
            if each in words.words():
               validPermutations.append(each)
         if not validPermutations:
            print("No words could be generated, please enter new letters\n\n")
         else:
            break
      return letters, validPermutations

   def slot_machine(self, letters, wordlist):
      pullLever = bool
      while pullLever:
         a = random.choice(letters)
         b = random.choice(letters)
         c = random.choice(letters)
         result = a.upper() + b + c
         print('Result: {}\n'.format(result))
         if result.lower() in wordlist:
            print("Success!\n")
            print("Try Again?\nPress Space to Pull the Lever\nPress Any Other Key to Quit\n\n")
            keypress = ord(getch())
            if keypress == 32:
               pass
            else:
               break
         else:
            print("Fail\n")
            print("Try Again?\nPress Space to Pull the Lever\nPress Any Other Key to Quit\n\n")
            keypress = ord(getch())
            if keypress == 32:
               pass
            else:
               break
      return None


if __name__ == "__main__":
   run = LetterToWordSlotMachine()
   userLetters, userWords = run.valid_words_generator()
   run.slot_machine(userLetters, userWords)

    
Written on June 5, 2018