python两队乒乓球比赛面向对象
时间: 2023-11-20 07:58:58 浏览: 98
以下是一个面向对象的Python乒乓球比赛模拟程序,其中包括两个类:Player和Game。
```python
from random import random
class Player:
def __init__(self, name, prob):
self.name = name
self.prob = prob
self.score = 0
def winServe(self):
return random() <= self.prob
def incScore(self):
self.score += 1
def getScore(self):
return self.score
def getName(self):
return self.name
class Game:
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
self.serve = player1
def switchServe(self):
if self.serve == self.player1:
self.serve = self.player2
else:
self.serve = self.player1
def play(self):
while not self.isOver():
if self.serve.winServe():
self.serve.incScore()
else:
self.switchServe()
def isOver(self):
return self.player1.getScore() == 21 or self.player2.getScore() == 21
def getWinner(self):
if self.player1.getScore() > self.player2.getScore():
return self.player1
else:
return self.player2
def printInfo(player1, player2):
print('This program simulates a game between two')
print('There are two players, {} and {}'.format(player1.getName(), player2.getName()))
print('Probability({}): {}'.format(player1.getName(), player1.prob))
print('Probability({}): {}'.format(player2.getName(), player2.prob))
def simNGames(n, player1, player2):
wins = {player1: 0, player2: 0}
for i in range(n):
game = Game(player1, player2)
game.play()
winner = game.getWinner()
wins[winner] += 1
return wins
def printSummary(wins, player1, player2):
n = sum(wins.values())
print('\nPlayed', n, 'games between', player1.getName(), 'and', player2.getName())
print('Wins for', player1.getName(), ':', wins[player1], '({0:0.1%})'.format(wins[player1]/n))
print('Wins for', player2.getName(), ':', wins[player2], '({0:0.1%})'.format(wins[player2]/n))
player1 = Player('Chinese team', 0.6)
player2 = Player('Japanese team', 0.5)
printInfo(player1, player2)
wins = simNGames(10000, player1, player2)
printSummary(wins, player1, player2)
print('Chinese team:{},Japanese team:{}'.format(wins[player1], wins[player2]))
```
阅读全文