python博客作业2

羽毛球比赛模拟程序,采用三局两胜赛制
ps:使用os库是因为pycharm使用命令窗口输出结果时会快速关闭

import random
import os


# 介绍比赛以及程序
def print_introduce():
    print("This is a badminton game simulation program")
    print("The program requires two players' ability values (expressed in decimals from 0 to 1)")
    print("The last two student number: 19")
    '''
    羽毛球比赛规则
    1. 21分制,3局2胜为佳
    2. 每球得分制
    3. 每回合中,取胜的一方加1分
    4. 当双方均为20分时,领先对方2分的一方赢得该局比赛
    5. 当双方均为29分时,先取得30分的一方赢得该局比赛
    6. 一局比赛的获胜方在下一局率先发球
    '''


# 获得输入
def get_inputs():
    a = eval(input("Please enter the ability value of player A: "))
    b = eval(input("Please enter the ability value of player B: "))
    return a, b


# 模拟n场比赛
def sim_n_games(pow_a, pow_b):
    a_wins, b_wins = 0, 0
    while not race_over(a_wins, b_wins):
        a_score, b_score = sim_one_game(pow_a, pow_b)
        if a_score > b_score:
            a_wins += 1
        else:
            b_wins += 1
    return a_wins, b_wins


# 单局比赛结束
def game_over(a, b):
    if (a == 21 and b < 20) or (b == 21 and a < 20):
        return True
    elif 20 <= a < 30 and 20 <= b < 30 and abs(a-b) == 2:
        return True
    elif a == 30 or b == 30:
        return True


# 比赛结束
def race_over(a, b):
    return a == 2 or b == 2


# 模拟单局比赛
def sim_one_game(pow_a, pow_b):
    score_a, score_b = 0, 0
    serving = 'A'
    while not game_over(score_a, score_b):
        if serving == 'A':
            if random.random() < pow_a:
                score_a += 1
            else:
                score_b += 1
                serving = 'B'
        else:
            if random.random() < pow_b:
                score_b += 1
            else:
                score_a += 1
                serving = 'A'
    return score_a, score_b


# 输出结果
def print_summary(a_wins, b_wins):
    print(f"A : B --- {a_wins}:{b_wins}")
    if a_wins > b_wins:
        print("Player A took the lead in winning two games and won.")
    else:
        print("Player B took the lead in winning two games and won.")


def main():
    print_introduce()
    a_pow, b_pow = get_inputs()
    wins_a, wins_b = sim_n_games(a_pow, b_pow)
    print_summary(wins_a, wins_b)


main()
os.system('pause')

image
篮球

from random import random

countdown = 0


def get_inputs():
    while True:
        try:
            foul_a_score, prob_a, prob_a3 = input('请输入 A 队的参数,用逗号隔开').split(',')
            foul_bscore, prob_b, prob_b3 = input("请输入 B 队的参数,用逗号隔开").split(',')
            foul_a_score = float(foul_a_score)
            foul_bscore = float(foul_bscore)
            prob_a = float(prob_a)
            prob_b = float(prob_b)
            prob_a3 = float(prob_a3)
            prob_b3 = float(prob_b3)
            break
        except:
            print('您的输入有误,请重新输入')
            continue
    return (foul_a_score, prob_a, prob_a3), (foul_bscore, prob_b, prob_b3)


def foul(score_a, score_b, foulAscore, foulBscore):
    side = random()
    if side > 0.5:
        if score_a > random():
            score_a += 1
        else:
            score_b += 1
    else:
        if score_b > random():
            score_b += 1
        else:
            score_a += 1
    return score_a, score_b


def simOneGame(argA, argB, ser):
    global countdown
    scoreA, scoreB = 0, 0
    fawl = 0.3
    serving = ser
    i = 1
    countdown = 50
    foulAscore = argA[0]
    probA = argA[1]
    probA3 = argA[2]
    foulBscore = argB[0]
    probB = argB[1]
    probB3 = argB[2]
    while not gameOver(scoreA, scoreB):
        judge = random()
        if judge < fawl:
            scoreA, scoreB = foul(scoreA, scoreB, foulAscore, foulBscore)
        else:
            if serving == 'A':
                if random() < probA:
                    scoreA += 3 if probA3 > random() else 2
                else:
                    scoreB += 3 if probB3 > random() else 2
            else:
                if random() < probB:
                    scoreB += 3 if probB3 > random() else 2
                else:
                    scoreA += 3 if probA3 > random() else 2
    print(scoreA, '--', scoreB)
    return Winner(scoreA, scoreB)


def gameOver(scoreA, scoreB):
    global countdown
    if countdown == 0:
        if scoreA == scoreB:
            countdown += 5
            return False
        else:
            return True
    else:
        countdown -= 1
        return False


def switchServing(serving):
    if serving == 'A':
        serving = 'B'
    else:
        serving = 'A'
    return serving


def Winner(scoreA, scoreB):
    return 'A' if scoreA > scoreB else 'B'


def simOneChampion():
    B = 0
    A = 0
    round = 1
    argA, argB = get_inputs()
    serving = 'A'
    while True:
        print('第{}节'.format(round))
        r = simOneGame(argA, argB, serving)
        serving = switchServing(serving)
        round += 1
        if r == 'A':
            A += 1
        else:
            B += 1
        if A == 3:
            print('A 队胜出')
            break
        elif B == 3:
            print('B 队胜出')
            break
        else:
            continue


simOneChampion()

羽毛球循环赛

# 定义一个羽毛球队类,包含队名和能力值属性
class BadmintonTeam:
    def __init__(self, name, ability):
        self.name = name
        self.ability = ability


# 定义一个羽毛球比赛类,包含两个队伍和比赛结果属性
class BadmintonMatch:
    def __init__(self, team1, team2):
        self.team1 = team1
        self.team2 = team2
        self.result = None  # 比赛结果,格式为 (team1的局数, team2的局数)

    # 定义一个模拟一局比赛的方法,返回获胜的队伍
    def simulate_one_game(self):
        score1 = 0  # team1的得分
        score2 = 0  # team2的得分
        serve = 1  # 发球方,1表示team1,2表示team2
        while True:
            # 生成一个0到1之间的随机数,表示本回合的胜率
            import random
            prob = random.random()
            # 根据能力值和发球方,计算team1的胜率
            win_rate = self.team1.ability / (self.team1.ability + self.team2.ability)
            if serve == 2:
                win_rate = 1 - win_rate
            # 根据胜率和随机数,判断本回合的胜方
            if prob < win_rate:
                winner = 1  # team1胜
            else:
                winner = 2  # team2胜
            # 根据胜方,更新得分和发球方
            if winner == 1:
                score1 += 1
                serve = 1
            else:
                score2 += 1
                serve = 2
            # 判断是否达到结束条件,即一方达到21分或者双方均为29分
            if score1 == 21 or score2 == 21 or (score1 == 29 and score2 == 29):
                break
            # 判断是否达到延长条件,即双方均为20分或者双方均为30分
            if (score1 == 20 and score2 == 20) or (score1 == 30 and score2 == 30):
                # 延长比赛,直到一方领先2分
                while abs(score1 - score2) < 2:
                    # 重复上述步骤
                    prob = random.random()
                    win_rate = self.team1.ability / (self.team1.ability + self.team2.ability)
                    if serve == 2:
                        win_rate = 1 - win_rate
                    if prob < win_rate:
                        winner = 1
                    else:
                        winner = 2
                    if winner == 1:
                        score1 += 1
                        serve = 1
                    else:
                        score2 += 1
                        serve = 2
                break
        # 返回获胜的队伍
        if score1 > score2:
            return self.team1
        else:
            return self.team2

    # 定义一个模拟三局两胜的方法,返回比赛结果
    def simulate_best_of_three(self):
        game1 = self.simulate_one_game()  # 模拟第一局
        game2 = self.simulate_one_game()  # 模拟第二局
        if game1 == game2:  # 如果前两局同一队伍获胜,直接返回结果
            self.result = (2, 0) if game1 == self.team1 else (0, 2)
            return self.result
        else:  # 如果前两局不同队伍获胜,模拟第三局
            game3 = self.simulate_one_game()
            if game3 == game1:  # 如果第三局和第一局同一队伍获胜,返回结果
                self.result = (2, 1) if game1 == self.team1 else (1, 2)
                return self.result
            else:  # 如果第三局和第二局同一队伍获胜,返回结果
                self.result = (1, 2) if game1 == self.team1 else (2, 1)
                return self.result


# 定义一个羽毛球联赛类,包含参赛队伍和排名属性
class BadmintonLeague:
    def __init__(self, teams):
        self.teams = teams  # 参赛队伍,是一个列表
        self.ranking = None  # 排名,是一个字典,键为队伍,值为胜场数

    # 定义一个模拟循环赛的方法,返回排名
    def simulate_round_robin(self):
        self.ranking = {}  # 初始化排名
        for team in self.teams:
            self.ranking[team] = 0  # 初始化每个队伍的胜场数为0
        # 对每一对队伍进行比赛
        import itertools
        for team1, team2 in itertools.combinations(self.teams, 2):
            match = BadmintonMatch(team1, team2)  # 创建比赛对象
            match.simulate_best_of_three()  # 模拟比赛
            if match.result[0] > match.result[1]:  # 如果team1获胜,更新排名
                self.ranking[team1] += 1
            else:  # 如果team2获胜,更新排名
                self.ranking[team2] += 1
        # 根据胜场数降序排序排名
        self.ranking = dict(sorted(self.ranking.items(), key=lambda x: x[1], reverse=True))
        return self.ranking


# 输入四个队伍的队名和能力值,创建队伍对象
teamA = BadmintonTeam("A队", 0.8)
teamB = BadmintonTeam("B队", 0.7)
teamC = BadmintonTeam("C队", 0.6)
teamD = BadmintonTeam("D队", 0.5)

# 创建联赛对象,传入队伍列表
league = BadmintonLeague([teamA, teamB, teamC, teamD])

# 模拟联赛,输出排名
league.simulate_round_robin()
print("羽毛球联赛的排名如下:")
for i, (team, wins) in enumerate(league.ranking.items()):
    print(f"{i + 1}. {team.name},胜场数:{wins}")
posted @ 2023-11-17 15:51  SnowDreamXUE  阅读(30)  评论(0编辑  收藏  举报