Created
October 14, 2012 10:40
-
-
Save dbr/3888222 to your computer and use it in GitHub Desktop.
Over-engineered Rock Paper Scissors game
This file contains hidden or 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
#!/usr/bin/env python2.6 | |
class RPSObject(object): | |
def __init__(self, name): | |
self.name = name | |
self.beats = [] | |
self.loses_to = [] | |
def against(self, opponent): | |
if opponent in self.loses_to: | |
print("Opponent %s beats %s" % (opponent, self)) | |
elif opponent in self.beats: | |
print("%s beats opponent %s" % (self, opponent)) | |
elif opponent == self: | |
print("Draw between %s and opponent %s" % (self, opponent)) | |
else: | |
raise ValueError("%s vs %s not defined") | |
def __gt__(self, b): | |
if b in self.loses_to: | |
raise ValueError("%s can't both beat and lose to %s" % (self, b)) | |
self.beats.append(b) | |
b.loses_to.append(self) | |
def __lt__(self, b): | |
if b in self.beats: | |
raise ValueError("%s can't both beat and lose to %s" % (self, b)) | |
self.loses_to.append(b) | |
b.beats.append(self) | |
def __repr__(self): | |
return "<%s>" % (self.name) | |
def main(): | |
# Set up the game objects | |
rock = RPSObject('rock') | |
paper = RPSObject('paper') | |
scissors = RPSObject('scissors') | |
# Define rules | |
rock > scissors | |
paper > rock | |
scissors > paper | |
# A few fixed games | |
scissors.against(paper) | |
scissors.against(rock) | |
scissors.against(scissors) | |
rock.against(scissors) | |
# Play a random object against rock | |
import random | |
random.choice([rock, paper, scissors]).against(rock) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment