Skip to content

Instantly share code, notes, and snippets.

@jletourneau
Created October 24, 2012 14:50
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jletourneau/3946506 to your computer and use it in GitHub Desktop.
Masher, pre-Hydra integration
#!/usr/bin/env python
import sys, os, pickle
from collections import defaultdict
class Masher:
def __init__(self, savefile):
self._savefile = savefile
self._read_profile()
def __str__(self):
return "Rounds played: %d; score: %d." % \
(self.data['rounds'], self.data['score'])
def run(self):
self._hello()._loop()._goodbye()
return self
def _hello(self):
if 'name' not in self.data:
self.data['name'] = raw_input("Welcome! What's your name? ")
self._write_profile()._help()
else:
print "Welcome back, %s!" % self.data['name']
print self
return self
def _loop(self):
while True:
try:
user_input = raw_input("Input: ").lower()
except EOFError: break
if user_input == 'q': break
elif user_input == '?': self._help()
else:
points = len(user_input)
self._incr_score(points)
print self
return self
def _goodbye(self):
print "Goodbye, %s! Your totals...\n%s" % \
(self.data['name'], self)
return self
def _read_profile(self):
self.data = defaultdict(int)
if os.path.exists(self._savefile):
try:
self.savefh = open(self._savefile, 'rb')
except IOError as err:
print "Couldn't read your savefile (%s): %s" % \
(self._savefile, err.strerror)
else:
self.data = pickle.load(self.savefh)
self.savefh.close()
return self
def _write_profile(self):
try:
self.savefh = open(self._savefile, 'wb')
except IOError as err:
print "Couldn't write to your savefile (%s): %s" % \
(self._savefile, err.strerror)
else:
pickle.dump(self.data, self.savefh)
self.savefh.close()
return self
def _help(self):
print "Mash the keyboard for points! Type Q to quit."
print "Hit Enter after your input to update your score."
return self
def _incr_score(self, n):
self.data['score'] += n
self.data['rounds'] += 1
self._write_profile()
return self
if __name__ == '__main__':
try:
savefile = sys.argv[1]
except IndexError:
savefile = 'masher-savegame.pkl'
Masher(savefile).run()
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment