## 1-10 1 class Player: ## written by LiSongbo def __init__(self,name): self._name = name self._score = 0 def reset_score(self): self._score = 0 def incr_score(self): self._score = self._score + 1 def get_name(self): return self._name def __str__(self): return "name = %s,score=%s" % (self._name,self._score) def __repr__(self): return 'Player(%s)' % str(self) class Human(Player): ## Player ,## written by LiSongbo def __repr__(self): return 'Human(%s)' % str(self) def get_move(self): while True: try: n = int(input('%s move (1-10): ' % self.get_name())) if 1 <= n <= 10: return n else: print('0ops!') except: print('0ops!') import random class Computer(Player): ## Player,## written by LiSongbo def __repr__(self): return 'Computer(%s)' % str(self) def get_move(self): return random.randint(1,10) def play_undercut(p1, p2): ## written by LiSongbo p1.reset_score() p2.reset_score() m1 = p1.get_move() m2 = p2.get_move() print("%s move: %s" % (p1.get_name(), m1)) print("%s move: %s" % (p2.get_name(), m2)) if m1 == m2 - 1: p1.incr_score() return p1, p2, '%s wins!' % p1.get_name() elif m2 == m1 - 1: p2.incr_score() return p1, p2, '%s wins!' % p2.get_name() else: return p1, p2, 'draw:no winner' # # c = Computer('Aobot') # h = Human('Rocky Lee') # x = play_undercut(c,h) # print(x) c1 = Computer('Aobot') ## written by LiSongbo c2 = Computer('Lisa') ## written by LiSongbo x1 = play_undercut(c1,c2) ## written by LiSongbo print(x1) print() h1 = Human('Rocky Lee') ## written by LiSongbo h2 = Human('Rocky') ## written by LiSongbo x2 = play_undercut(h1,h2) ## written by LiSongbo
print(x2)
文章来源: 以例子说明python的类、继承和多态