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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #!/usr/bin/env python3
# coding: utf-8
import random
# Objet qui gère le jeu
class cGame(object):
RCK=0x01
PPR=0x02
SCS=0x03
LZD=0x04
SPK=0x05
pieces={
RCK : {
"label" : "Rock",
"win" : (SCS, LZD),
},
PPR : {
"label" : "Paper",
"win" : (SPK, RCK),
},
SCS : {
"label" : "Scissors",
"win" : (LZD, PPR),
},
LZD : {
"label" : "Lizard",
"win" : (SPK, PPR),
},
SPK : {
"label" : "Spock",
"win" : (SCS, RCK),
},
}
def __init__(self, p1, p2, rnd):
super(cGame, self).__init__()
self.__p1=p1
self.__p2=p2
self.__rnd=rnd
# __init__()
def debug_rules(self):
for v in cGame.pieces.values():
yield "%s éclate %s" % (
v["label"],
", ".join(cGame.pieces[x]["label"] for x in v["win"]),
)
# for
# debug_rules()
# Evaluation résultat
def __evaluate(self, m1, m2):
if m2 in cGame.pieces[m1]["win"]: return m1
if m1 in cGame.pieces[m2]["win"]: return m2
return 0
# __evaluate()
def play_round(self):
move1 = self.__p1.move()
move2 = self.__p2.move()
self.__p1.learn(move1, move2)
self.__p2.learn(move2, move1)
print("Player1 played : %s" % cGame.pieces[move1]["label"])
print("Player2 played : %s" % cGame.pieces[move2]["label"])
e=self.__evaluate(move1, move2)
if e == move1:
print("Player1 win")
self.__p1.win()
elif e == move2:
print("Player2 win")
self.__p2.win()
else:
print("Draw")
print("Player 1: %d" % self.__p1.score)
print("Player 2: %d" % self.__p2.score)
# play_round()
# Function for playing multiple games
def play_game(self):
print("\nGame start! \n")
for rnd in range(1, self.__rnd + 1):
print("\nRound %d/%d:" % (rnd, self.__rnd))
self.play_round()
# for
print("Game over! \n")
print("Score p1 : %d" % self.__p1.score)
print("Score p2 : %d" % self.__p2.score)
# play_game()
# class Game
# Objet qui gère un joueur
class cJoueur(object):
score=property(lambda self: self.__score)
moves=property(lambda self: self.__moves)
def __init__(self):
self.__score=0
self.__moves=[]
def win(self):
self.__score+=1
def learn(self, m1, m2):
self.__moves.append((m1, m2))
# class cJoueur()
# Objet qui joue aléatoirement
class cJoueurRandom(cJoueur):
def move(self):
return random.choice(tuple(cGame.pieces.keys()))
# class cJoueurRandom()
# Objet qui joue le dernier coup de son adversaire
class cJoueurReflect(cJoueurRandom):
def move(self):
return self.moves[-1][1] if self.moves else super(cJoueurReflect, self).move()
# class cJoueurReflect()
# Programme principal
import sys
g=cGame(cJoueurRandom(), cJoueurReflect(), int(sys.argv[1]))
g.play_game() |