Python球队比赛模拟程序积分计算偶发异常排查求助
问题分析与修复方案
核心bug定位
你的积分计算函数add_point存在逻辑错误:第三个判断条件误写为elif point2>point1,但实际应该比较的是比赛比分score2>score1,而非当前积分。
当比赛结果是score2 > score1时,由于初始积分point1和point2都是0,point2>point1的条件不成立,程序会进入最后的else分支打印"Error",导致获胜方的积分无法被正确添加——这就是你遇到的"每运行约4次就出现积分不增加"的根本原因。
修复后的完整代码
将add_point函数的第三个条件修正为elif score2>score1即可,同时还修复了一个潜在的出牌逻辑bug(原代码中给非参赛队出牌的问题):
import random # 球队与动作参数列表 action=['teamplay1','yellow','red','teamplay2'] teamplay1=['score','defence','almost','offside','var'] teamplay2=['score','defence','almost','offside','var'] teams=['Chelsea','Arsenal','Barcelona','Madrid'] # 初始化比分与积分 score1=0 score2=0 point1=0 point2=0 # 随机选择两支不同的参赛球队 a=random.choice(teams) teams.remove(a) b=random.choice(teams) # 处理随机动作逻辑 def action_choices(): global score1,score2 x=random.choice(action) if x =='teamplay1': y=random.choice(teamplay1) if y == 'score': print(a + ' scores') score1=score1+1 elif y == 'defence': print('Good defence by ' + a + ', they broke down the ' + b + ' attack') elif y == 'almost': print(a + ' almost scored') elif y == 'offside': print(a + ' are offside') elif y == 'var': print(a + "'s goal is ruled out by offside") else: print('ERROR') elif x =='teamplay2': y=random.choice(teamplay2) if y == 'score': print(b + ' scores') score2=score2+1 elif y == 'defence': print('Good defence by ' + b + ', they broke down the ' + a + ' attack') elif y == 'almost': print(b + ' almost scored') elif y == 'offside': print(b + ' are offside') elif y == 'var': print(b + "'s goal is ruled out by offside") else: print('ERROR') elif x=='yellow': z=random.choice([a,b]) print('Yellow card for '+ z) elif x=='red': z=random.choice([a,b]) print('Red card for '+ z) # 模拟比赛时间流程 def process(clock=0): print('Minute ' + str(clock) + ' : ') action_choices() clock=clock+10 if clock==90: print('Match is over.') print(a + ' : ' + str(score1) + ' ' + b + ' : ' + str(score2)) else: process(clock) # 计算并打印积分 def add_point(): global point1, point2 if score1>score2: point1=point1 + 3 elif score1==score2: point1=point1 + 1 point2=point2 + 1 elif score2>score1: point2=point2 + 3 else: print('Error') print(a + ' points : ' + str(point1) + ' ' + b + ' points : ' + str(point2)) # 启动比赛 def play(): print("Today's match is between " + a + " and " + b) process() add_point() play()
额外优化说明
原代码中yellow和red分支使用random.choice(teams)会导致给非当前参赛队出牌的问题(因为teams列表已经移除了选中的两支球队),修复后改为从当前参赛队[a,b]中随机选择,更符合比赛逻辑。
内容的提问来源于stack exchange,提问作者Alaya Isuekebhor
相关产品推荐
相关产品推荐

