# sign.py class Sign(object): def __init__(self, name): self.name = name self.signsWinsWith = [] self.signsLosesWith = [] self.signsDrawsWith = [] @staticmethod def addToWins(self, sign): self.signsWinsWith.append(sign) @staticmethod def addToLosts(self, sign): self.signsLosesWith.append(sign) @staticmethod def addToDraws(self, sign): self.signsDrawsWith.append(sign) def fillArray(self, thisFunction, thatFunction, *args): for other in args: thisFunction(self, other) thatFunction(other, self) return other def beats(self, *signs): return self.fillArray(Sign.addToWins, Sign.addToLosts, *signs) def isVictoriousWith(self, that): return that in self.signsWinsWith def loses(self, *signs): return self.fillArray(Sign.addToLosts, Sign.addToWins, *signs) def isBeatenBy(self, that): return that in self.signsLosesWith def draws(self, *signs): return self.fillArray(Sign.addToDraws, Sign.addToDraws, *signs) def isADraw(self, that): return that in self.signsDrawsWith # game.py class Game(object): PLAYER_ONE = "Player 1 wins" PLAYER_TWO = "Player 2 wins" DRAW = "It's a draw" def __init__(self, *signs): self.callbacks = { "playerOneWins": [], "playerTwoWins": [], "nobodyWins": [] } self.signs = {} for s in signs: sign = Sign(s) sign.draws(sign) self.signs[sign.name] = sign def setRules(self, callback): for sign in self.signs: eval(sign + " = self.signs[" + sign + "]") eval(inspect.getsource(callback)) return self def whoWins(self, firstSign, secondSign): if firstSign.isVictoriousWith(secondSign): self.execute("playerOneWins", [firstSign, secondSign]) return PLAYER_ONE if firstSign.isBeatenBy(secondSign): self.execute("playerTwoWins", [firstSign, secondSign]) return PLAYER_TWO self.execute("nobodyWins", [firstSign, secondSign]) return DRAW def whenPlayerOneWins(self, callback): self.callbacks["playerOneWins"].append(callback) return self def whenPlayerTwoWins(self, callback): self.callbacks["playerTwoWins"].append(callback) return self def whenPlayersDraw(self, callback): self.callbacks["nobodyWins"].append(callback) return self def execute(self, callbackArray, *arguments): for callback in self.callbacks[callbackArray]: callback(*arguments) rockPaperScissors = Game ("rock", "paper", "scissors") rockPaperScissors.setRules(lambda : scissors.beats(paper).beats(rock).beats(scissors)) print rockPaperScissors.whoWins(rockPaperScissors.signs["rock"], rockPaperScissors.signs["paper"])
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question