区块链技术博客
www.b2bchain.cn

退出暂停屏幕后如何解决时钟显示不正确的问题? – python程序员分享

本文介绍了退出暂停屏幕后如何解决时钟显示不正确的问题? – python程序员分享,有助于帮助完成毕业设计以及求职,是一篇很好的资料。

对技术面试,学习经验等有一些体会,在此分享。

我在pygame中创建了迷宫游戏(这是我的第一个)。但是,无论何时我进入然后离开暂停屏幕,时钟都停留在00:00:-15。甚至更奇怪的是,如果我再次进入并离开暂停屏幕,代码将按照我预期的方式工作(继续输入进入暂停视频之前的时钟)。

这是生成时钟的代码:

# creates the string that displays time def get_time(hours,minutes,seconds):     if len(str(hours)) > 1:         a = str(hours)     else:         a = "0" + str(hours)      if len(str(minutes)) > 1:         b = str(minutes)     else:         b = "0" + str(minutes)      if len(str(seconds)) > 1:         c = str(seconds)     else:         c = "0" + str(seconds)      return a + ":" + b + ":" + c  # creates the time counter def draw_time(start_time,pause_time):     hours = 0     minutes = 0     seconds = 0     current_time = time.time() - pause_time - start_time     if current_time > 3600:         while True:             if current_time - 3600 > 0:                 hours += 1                 current_time -= 3600             else:                 while True:                     if current_time - 60 > 0:                         minutes += 1                         current_time -= 60                     else:                         seconds += int(current_time)                         break                 break      else:         while True:             if current_time - 60 > 0:                 minutes += 1                 current_time -= 60             else:                 seconds += int(current_time)                 break      return [font1.render(get_time(hours, minutes, seconds), True, (0, 0, 0), (255, 255, 255)), get_time(hours, minutes, seconds)] 

显示它:

screen.blit(text[0], (700, 15)) 

这将激活/禁用暂停屏幕:

for event in pygame.event.get():      if event.type == pygame.QUIT:         done = True         running = False      if event.type == pygame.KEYDOWN:         if event.key == pygame.K_ESCAPE or event.key == pygame.K_p:             if pause:                 pause = False                 pause_time = time.time() - pause_time_start             else:                 pause = True                 pause_time_start = time.time() - game_time - start          if event.key == pygame.K_RETURN:             done = True 

这是整个代码:

import pygame import random import time  pygame.init() # all fonts used font1 = pygame.font.SysFont("comicsansms", 49, True) font2 = pygame.font.SysFont("comicsansms", 150, True) font3 = pygame.font.SysFont("comicsansms", 28, True)  # creates the string that displays time def get_time(hours,minutes,seconds):     if len(str(hours)) > 1:         a = str(hours)     else:         a = "0" + str(hours)      if len(str(minutes)) > 1:         b = str(minutes)     else:         b = "0" + str(minutes)      if len(str(seconds)) > 1:         c = str(seconds)     else:         c = "0" + str(seconds)      return a + ":" + b + ":" + c  # creates the time counter def draw_time(start_time,pause_time):     hours = 0     minutes = 0     seconds = 0     current_time = time.time() - pause_time - start_time     if current_time > 3600:         while True:             if current_time - 3600 > 0:                 hours += 1                 current_time -= 3600             else:                 while True:                     if current_time - 60 > 0:                         minutes += 1                         current_time -= 60                     else:                         seconds += int(current_time)                         break                 break      else:         while True:             if current_time - 60 > 0:                 minutes += 1                 current_time -= 60             else:                 seconds += int(current_time)                 break      return [font1.render(get_time(hours, minutes, seconds), True, (0, 0, 0), (255, 255, 255)), get_time(hours, minutes, seconds)]  class cell:     def __init__(self,up,down,left,right):         self.visited = False         self.walls = [up,down,left,right]  class labyrinth:     # generates the maze     def __init__(self,id):         self.id = id         self.walls = []         self.maze_walls = []         self.cells = []          x = 0         t = 0          # creates all cell within the maze         for f in range(22):             for s in range(28):                 # if command makes sure no cellls are created where the clock is supposed to be                 if not (f in (0,1,2) and s > 20):                     self.cells.append(cell((x + 8, t, 25, 8), (x + 8, t + 33, 25, 8), (x, t + 8, 8, 25), (x + 33, t + 8, 8, 25)))                 x += 33             x = 0             t += 33          # generates maze using prim's algorithm         for v in self.cells[0].walls:             self.maze_walls.append(v)             self.walls.append(v)          self.cells[0].visited = True          while len(self.walls) > 0:             wall = random.choice(self.walls)             # checks which cells are divided by the wall             divided_cells = []             for u in self.cells:                 if wall in u.walls:                     divided_cells.append(u)              if len(divided_cells) > 1 and (not ((divided_cells[0].visited and divided_cells[1].visited) or ((not divided_cells[0].visited) and (not divided_cells[1].visited)))):                 # checks which cells have been visited                 for k in divided_cells:                     k.walls.remove(wall)                      if k.visited == False:                         k.visited = True                      for q in k.walls:                         if not q in self.walls:                             self.walls.append(q)                          if not q in self.maze_walls:                             self.maze_walls.append(q)                      if wall in self.maze_walls:                         self.maze_walls.remove(wall)              self.walls.remove(wall)          for j in range(0,736,33):             for i in range(0,951,33):                 self.maze_walls.append((i, j, 8, 8))      # draws the maze     def draw(self, goal):         screen.fill((0, 0, 0))          for k in self.maze_walls:             pygame.draw.rect(screen, color, pygame.Rect(k[0],k[1],k[2],k[3]))          pygame.draw.rect(screen, color, pygame.Rect(695, 0, 300, 105)) # clock background         pygame.draw.rect(screen, (0, 255, 0), goal) # finish  id = 0 running = True while running:     screen = pygame.display.set_mode((930, 733))     done = False     color = (0, 128, 255) # color of the walls     x = 16     y = 16     clock = pygame.time.Clock()     start = time.time()     id += 1     maze = labyrinth(id)     goal = pygame.Rect(899,701,25,25)     victory = False     speed = 4 # movement speed     pause = False     pause_time = 0 # time spent in pause menue     game_time = 0 # time spent playingg      while not done:         for event in pygame.event.get():              if event.type == pygame.QUIT:                 done = True                 running = False              if event.type == pygame.KEYDOWN:                 if event.key == pygame.K_ESCAPE or event.key == pygame.K_p:                     if pause:                         pause = False                         pause_time = time.time() - pause_time_start                     else:                         pause = True                         pause_time_start = time.time() - game_time - start                  if event.key == pygame.K_RETURN:                     done = True          if pause:             screen.fill((0, 0, 0))             pause_text = font2.render("PAUSE",True,(255,255,255))             screen.blit(pause_text, (468 - (pause_text.get_width() // 2), 368 - (pause_text.get_height() // 2)))          # the actual game         if not victory and not pause:             game_time = time.time() - pause_time - start             move_up = True             move_down = True             move_left = True             move_right = True             pressed = pygame.key.get_pressed()              # movment             if pressed[pygame.K_w] or pressed[pygame.K_UP]:                 # checks if their is a overlap with the wall                 for m in maze.maze_walls:                     player = pygame.Rect(x, y - speed, 10, 10)                     if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])):                         move_up = False                         break                 if move_up:                     y -= speed              if pressed[pygame.K_s] or pressed[pygame.K_DOWN]:                 player = pygame.Rect(x, y + speed, 10, 10)                 for m in maze.maze_walls:                     if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])):                         move_down = False                         break                 if move_down:                     y += speed              if pressed[pygame.K_a] or pressed[pygame.K_LEFT]:                 player = pygame.Rect(x - speed, y, 10, 10)                 for m in maze.maze_walls:                     if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])):                         move_left = False                         break                 if move_left:                     x -= speed              if pressed[pygame.K_d] or pressed[pygame.K_RIGHT]:                 player = pygame.Rect(x + speed, y, 10, 10)                 for m in maze.maze_walls:                     if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])):                         move_right = False                         break                 if move_right:                     x += speed              # checks if player has reached the goal             if goal.colliderect((x, y, 10, 10)):                 victory = True              # draws the screen             maze.draw(goal)             text = draw_time(start, pause_time)             pygame.draw.rect(screen, (255, 100, 0), pygame.Rect(x,y,10,10))             screen.blit(text[0], (700, 15))          # victory screen         if victory:             screen.fill((0, 0, 0))             time_text = font1.render("Time Taken: " + text[1],True,(255,255,255))             victory_text = font2.render("VICTORY!",True,(255,255,255))             reset = font3.render("(Press Enter to Start New Game)",True,(255,255,255))              screen.blit(victory_text,(468 - (victory_text.get_width() // 2), 328 - (victory_text.get_height() // 2)))             screen.blit(time_text, (468 - (time_text.get_width() // 2), (248 - (time_text.get_height() // 2)) + victory_text.get_height()))             screen.blit(reset, (468 - (reset.get_width() // 2), (248 - (reset.get_height() // 2)) + victory_text.get_height() + time_text.get_height()))          clock.tick(60)         pygame.display.flip() 

参考方案

您在这里处理两种不同的时间度量,即瞬间和持续时间。您从time.time()那里得到的是瞬间-它描述了特定的时间点。当减去两个瞬间时,您得到一个持续时间-这两个特定点之间经过的时间。通过使两者混淆,您会看到令人困惑的结果。

start = time.time() # ... pause_time = 0 # time spent in pause menue game_time = 0 # time spent playingg 

在这里,您是说开始是游戏开始的瞬间。您说的是pause_time和game_time是持续时间。它们是自游戏开始以来在暂停/未暂停模式下花费的时间。

您不暂停的每一帧都更新game_time:

game_time = time.time() - pause_time - start 

在这里starttime.time()是瞬间,而pause_time是持续时间。尽管阅读有点尴尬,但这种方法有效。从start减去time.time()可以得出自游戏以暂停或未暂停模式开始以来的总经过时间,而减去pause_time则可以得出在未暂停模式下花费的时间。大。

这是您的暂停行为:

pause = True pause_time_start = time.time() - game_time - start 

因此time.time()start再次是即时的。减去它们可为您提供在任何游戏中的总经过时间。减去game_time可得出暂停模式下的总经过时间,即持续时间。我不确定这不是您真正想要的,因为下次使用它时,您的未暂停代码中将显示以下内容:

pause = False pause_time = time.time() - pause_time_start 

所以time.time()是一个瞬间,而pause_time_start是一个持续时间。像这样减去它们会在游戏开始前的某个瞬间给您带来另一个瞬间。但是您像持续时间一样使用此瞬间!瞬间仍然是一个数字,但通常它是一个相当大的数字。 (从技术上讲,这是自纪元以来的秒数,在大多数操作系统中,您可能要运行Pygame的时间是1970年1月1日午夜。)

再次更新game_time时,事情显然会出错:

game_time = time.time() - pause_time - start 

现在,pause_time的值不正确,您正尝试添加一个瞬间(time.time())并减去另外两个瞬间。这给您带来巨大的负面价值。当您尝试渲染时,您的时间渲染代码非常混乱,因为它不期望负数。它不显示“ -15”秒。它显示的数字不适合屏幕显示,例如“ -1545616400”!

它第二次工作的原因是错误被抵消了。此计算使game_time极大地变为负数,这会影响pause_start_time的下一次计算,使其成为极大的正数,并最终使pause_time的下一次计算恢复为较小的持续时间。

您可以通过确定pause_time_start应该是什么并修复相应的计算来最小化此问题。我想您可能是想将游戏暂停的那一刻。如果是这样,您可以更新您的暂停/暂停代码:

if pause:     pause = False     pause_time += time.time() - pause_time_start else:     pause = True     pause_time_start = time.time() 

在我们暂停的那一刻,我们要做的只是记住那一刻,以便以后使用。在我们取消暂停的那一刻,我们将暂停所花费的时间添加到累积的暂停时间中。我们的瞬间保持瞬间,我们的持续时间保持持续时间。

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

我目前使用的移动平均线列表有效,但我想看看去皮是实现此目的的更快方法。 strut[i].cpsi = round(bit2UntrimPSI(i) + float(strut[i].trim), 0) strut[i].rpsi.append([time.time(), strut[i].cpsi]) while strut[i].rpsi[0][0] &…

我一直在基于this的pygame平台游戏。我是在Ubuntu机器上编写的,它似乎无法在其他操作系统上运行。生成代码是这样的:levelFile = tkFileDialog.askopenfile(mode='r', defaultextension='.lvl', filetypes=[('Level F…

我试图修改一列的值(如果它们介于以下时间之间(17:00到23:00)),否则,它们必须保持相同的值。这是我的代码:lclstd['Response KWH/hh (per half hour) ']=lclstd['KWH/hh (per half hour) '].astype(float) 从日期时间列中提取时间…

我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…

赞(0) 打赏
部分文章转自网络,侵权联系删除b2bchain区块链学习技术社区 » 退出暂停屏幕后如何解决时钟显示不正确的问题? – python程序员分享
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

b2b链

联系我们联系我们