-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
58 lines (51 loc) · 1.69 KB
/
game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import time
import hashlib
import re
from mongokit import Document
class GameState(object):
CREATED = u"CREATED"
RUNNING = u"RUNNING"
CORRECT_GUESS = u"CORRECT_GUESS"
INCORRECT_GUESS = u"INCORRECT_GUESS"
OVER_SAVED = u"OVER_SAVED"
OVER_HUNG = u"OVER_HUNG"
class AlreadyGuessedException(Exception):
pass
MAX_INCORRECT_GUESSES = 11
class HangmanGame(Document):
__collection__ = "games"
__database__ = "hangman"
structure = {
"channel": unicode,
"state": unicode,
"word": unicode,
"wordstate": [unicode],
"failed": [unicode],
"last_guess": unicode
}
default_values = { "state": GameState.CREATED }
use_dot_notation = True
def create(self, word):
self.word = word.upper()
self.channel = unicode(hashlib.md5(word.encode("utf-8") + str(time.time())).hexdigest())
self.wordstate = [u"_"] * len(word)
def join(self):
self.state = GameState.RUNNING
def guess(self, letter):
upper_letter = letter.upper()
if upper_letter in self.failed:
raise AlreadyGuessedException()
self.last_guess = upper_letter
if upper_letter not in self.word:
self.failed.append(upper_letter)
if len(self.failed) == MAX_INCORRECT_GUESSES:
self.state = GameState.OVER_HUNG
else:
self.state = GameState.INCORRECT_GUESS
else:
for m in re.finditer(upper_letter, self.word):
self.wordstate[m.start()] = upper_letter
if "_" in self.wordstate:
self.state = GameState.CORRECT_GUESS
else:
self.state = GameState.OVER_SAVED