Skip to content

Instantly share code, notes, and snippets.

@joelburton
Last active March 1, 2017 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelburton/f23d8f78527f55ae55d9823aad1983e4 to your computer and use it in GitHub Desktop.
Save joelburton/f23d8f78527f55ae55d9823aad1983e4 to your computer and use it in GitHub Desktop.
Simple demonstration of using Python's stdlib "cmd" to make an interactive game.
"""Console-based guess-the-secret-word game."""
import cmd
import random
class WordGuess(cmd.Cmd):
"""REPL for a guess-the-secret-word game."""
prompt = "\nWordGuess > "
intro = "Guess the secret word! (Control-D quits)"
doc_header = "Commands (type 'help <name>' for help)"
misc_header = "Concepts (type 'help <topic>` to read)"
def preloop(self):
"""Set the secret word --- called at start"""
self.secret = random.choice(["apple", "berry", "cherry"])
def help_rules(self):
"""Print rules."""
print "It's easy. Guess a word and I judge your worth as a human."
def help_strategy(self):
"""Print strategy."""
print "It's always good to guess fruits."
def do_guess(self, arg):
"""guess <word>: Make a guess"""
if arg == self.secret:
print "You win!"
return True
else:
print "Nope"
def do_hint(self, arg):
"""hint: Ask for a hint"""
print "It starts with %s" % self.secret[0]
def do_EOF(self, arg):
"""EOF (Control-D): Quit"""
print "Goodbye."
return True
WordGuess().cmdloop()
@joelburton
Copy link
Author

joelburton commented Mar 1, 2017

Some notes:

  • methods with names like do_something become commands

  • methods that names like help_something provide a help topic

The arg parameter is needed for all do_ functions; it's whatever is typed after the command. For example, if the user typed "guess apple", arg becomes "apple".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment