如何解决带有pygame同步问题的Python游戏
我正在使用pygame库在python中制作一个太空侵略者游戏。我有一个存储球员记录的文件,在每次比赛结束时,都有一个功能检查球员是否击败了他的记录,如果是,则记录文件中的值会随着最后一场比赛的得分,玩家将看到文本“ You lost,new record n points
”或“ You lost,n points
”(如果未打破记录)。
问题在于此控件的速度约为90次/秒(fps),因此,第一次启动函数is_record()
时,如果函数返回true,则会显示“ You lost,new record n points
” “,但其他89次更改了文件中的记录,因此is_record()
函数返回false并显示“ You lost,n points
”。
因此,玩家总是看到“您输了n分”,而从未看到“您输了n分新记录”,因为最后的文本仅显示在90帧的第一帧中。 我该如何解决这个问题?
我的代码中需要修复的部分:
def is_record(points):
file = open('record','r')
line = file.readline()
file.close()
if points > int(line):
print("1")
file = open('record','w')
file.write(str(points))
file.close()
return True
else:
print("2")
return False
def redraw_window()
if lost:
lost_label = lost_font.render("Hai perso!",1,(255,255,255))
WIN.blit(lost_label,(WIDTH / 2 - lost_label.get_width() / 2,350))
#print(is_record(player.points))
if(is_record(player.points) == False):
final_points_label = lost_font.render(f"{player.points} Punti",255))
WIN.blit(final_points_label,400))
elif is_record(player.points) == True:
final_points_label = lost_font.render(f"Nuovo record! {player.points} punti",400))
解决方法
不要在每一帧中重写文件。设置一个标志以指示文件已更新。还要存储结果文本以用于下一个循环。
fileupdated = False
final_points_label = None
def redraw_window()
global fileupdated,final_points_label
if lost:
lost_label = lost_font.render("Hai perso!",1,(255,255,255))
WIN.blit(lost_label,(WIDTH / 2 - lost_label.get_width() / 2,350))
#print(is_record(player.points))
if not fileupdated: # update score file,check high score
res = is_record(player.points)
if(res == False):
final_points_label = lost_font.render(f"{player.points} Punti",255))
elif res == True:
final_points_label = lost_font.render(f"Nuovo record! {player.points} punti",255))
fileupdated = True # prevent rewrite
if final_points_label: # show results
WIN.blit(final_points_label,400))
游戏重新启动时,您需要重置写入标志:fileupdated = False
和文本对象:final_points_label = None
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。