Created
November 2, 2016 08:16
-
-
Save zsoldosp/4357c7f4ad719024d131dda9cc6fbfcd to your computer and use it in GitHub Desktop.
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
#### Tie display strings | |
class OnTieBothDisplayed(object): | |
def tie_str(self): | |
return '{}-All'.format(self) | |
def __str__(self): | |
return self.__class__.__name__ | |
class Deuce(object): | |
def tie_str(self): | |
return 'Deuce' | |
#### Score states | |
class Score(object): | |
can_win = False | |
def __init__(self, player, points): | |
self.player = player | |
self.points = points | |
def next(self): | |
return self.next_cls(self.player, self.points + 1) | |
def has_more_points_than(self, other): | |
return self.points > other.points | |
class EndGame(Score, Deuce): | |
can_win = True | |
def next(self): | |
return self | |
class Forty(Score, Deuce): | |
next_cls = EndGame | |
class Thirty(Score, OnTieBothDisplayed): | |
next_cls = Forty | |
class Fifteen(Score, OnTieBothDisplayed): | |
next_cls = Thirty | |
class Love(Score, OnTieBothDisplayed): | |
next_cls = Fifteen | |
#### gae state | |
class GameState(object): | |
def __init__(self, player_scores): | |
self.player_scores = player_scores | |
def get_score_by(self, predicate): | |
return list(ps for ps in self.player_scores if predicate(ps))[0] | |
def get_scoring(self, player): | |
return self.get_score_by(lambda ps: ps.player == player) | |
def get_other(self, player): | |
return self.get_score_by(lambda ps: ps.player != player) | |
def won_point(self, player): | |
return self.create_next( | |
scoring=self.get_scoring(player).next(), | |
other=self.get_other(player)) | |
class Tie(GameState): | |
def create_next(self, scoring, other): | |
return Ahead([scoring, other], ahead=scoring.player) | |
def __str__(self): | |
return self.player_scores[0].tie_str() | |
class Ahead(GameState): | |
def __init__(self, player_scores, ahead): | |
super(Ahead, self).__init__(player_scores) | |
self.ahead = ahead | |
def create_next(self, scoring, other): | |
if scoring.can_win: | |
return Won(scoring) | |
if scoring.points == other.points: | |
return Tie([scoring, other]) | |
return Ahead([scoring, other], ahead=scoring.player) | |
class Won(GameState): | |
def create_next(self, scoring, other): | |
raise NotImplementedError('Game Over Already') | |
class TennisGame(object): | |
def __init__(self, player1, player2): | |
self.state = Tie([ | |
Love(player1, 0), Love(player2, 0) | |
]) | |
def score(self): | |
return str(self.state) | |
def won_point(self, player): | |
self.state = self.state.won_point(player) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment