Last active
March 1, 2017 21:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some notes:
methods with names like
do_something
become commandsmethods that names like
help_something
provide a help topicThe
arg
parameter is needed for alldo_
functions; it's whatever is typed after the command. For example, if the user typed "guess apple",arg
becomes "apple".