Python游戏与pygame同步问题
我正在用python和pygame库制作一个空间入侵者游戏。我有一个存储球员记录的文件,在每场比赛结束时,有一个函数检查球员是否打破了记录,如果是真的,记录文件中的值会随着最后一场比赛的分数而改变,球员会看到一个文本“Python游戏与pygame同步问题,python,pygame,Python,Pygame,我正在用python和pygame库制作一个空间入侵者游戏。我有一个存储球员记录的文件,在每场比赛结束时,有一个函数检查球员是否打破了记录,如果是真的,记录文件中的值会随着最后一场比赛的分数而改变,球员会看到一个文本“你输了,新记录n分”,或者“你输了,n分”如果没有打破记录 问题是这个控件被设置为大约90次/秒(fps),因此第一次启动函数is_record(),如果函数返回true,它会显示“您丢失了,新记录n个点””,但其他89次,文件中的记录被更改,因此是_record()函数返回fal
你输了,新记录n分
”,或者“你输了,n分
”如果没有打破记录
问题是这个控件被设置为大约90次/秒(fps),因此第一次启动函数is_record()
,如果函数返回true,它会显示“您丢失了,新记录n个点”
”,但其他89次,文件中的记录被更改,因此是_record()
函数返回false并显示“您丢失了n个点”
”
因此,玩家总是看到“You lost,n points”,而从不看到“You lost,new record n points”文本,因为最后一个文本仅在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", 1, (255, 255, 255))
WIN.blit(final_points_label, (WIDTH / 2 - lost_label.get_width() / 2, 400))
elif is_record(player.points) == True:
final_points_label = lost_font.render(f"Nuovo record! {player.points} punti", 1, (255,255,255))
WIN.blit(final_points_label, (WIDTH / 2 - lost_label.get_width() / 2, 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", 1, (255, 255, 255))
elif res == True:
final_points_label = lost_font.render(f"Nuovo record! {player.points} punti", 1, (255,255,255))
fileupdated = True # prevent rewrite
if final_points_label: # show results
WIN.blit(final_points_label, (WIDTH / 2 - lost_label.get_width() / 2, 400))
当游戏重新启动时,您需要重置写入标志:
fileupdated=False
和文本对象:final\u points\u label=None
解决此问题的一种可能方法是将游戏编号存储在文件中,这样您就可以简单地检查游戏是否与在其中获得高分的游戏相同。每次播放r开始一个新游戏,你更改游戏编号。如果你想了解更多信息,请询问。我复制了你的代码,但收到错误:NameError:name'fileupdated'未定义,我将其放在所有方法/类之外,但现在游戏不起作用在类中,您应该尝试self.fileupdated
和self.final\u points\u label
它不在类中,redraw\u window()是函数中的函数