问题描述
您好,感谢您花时间阅读本文。
这与我正在做的项目有关。这是一个反应测试游戏。基本上,带有 LED 的 Arcade 按钮会亮起,玩家需要按下它们才能得分。打地鼠风格。
游戏计时,30 秒。但我没有使用数字计时器,而是使用在屏幕上移动的进度条来指示剩余时间。 下图: game screenshot
我在代码中将其添加为图像 blit,但它没有正确刷新。您只能在游戏开始时以及玩家按下按钮时看到它。
它需要在屏幕上不断闪烁。
也许我只是遗漏了一些东西,或者我的缩进有误? 非常感谢您对此的任何意见。
主要游戏循环代码如下:
# MAIN GAME SEQUENCE CODE ---------------------------------------------------------------------------------------------
# Setup Pygame refresh rate to 120 fps
clock.tick(60)
while game_running:
# Idle Screen
idle_scrn()
# Instructions
inst_seq()
# GAME PLAY SECTION --------
score = 0
time_Out = 0
leds.off()
start_Time = pygame.time.Clock()
start = int(time.time())
time_move = -500
random_num = random.randint(0,11)
leds.on(random_num)
print(random_num)
while time_Out != 30:
screen.blit(Timebar,(time_move,1000))
time_move += 50
pygame.display.update()
for event in pygame.event.get():
print("For Event started,Game screen started")
screen.fill((255,255,255))
screen.blit(Game_screen[6],(0,0))
score_textback = score_fontback.render("00",3,(199,199,199))
score_text = score_font.render(str(score),(255,37,24))
ctr = 1110
if score >= 10:
ctr -= 155
center_pos = (ctr,580)
score_rect = score_text.get_rect(center = center_pos)
screen.blit(score_textback,(645,390))
screen.blit(score_text,score_rect)
if event.type == pygame.JOYBUTTONDOWN:
print("If for event JOYBUTTONDOWN")
if event.button == random_num:
B = event.button
print(B," button pressed,CORRECT")
leds.off()
butt_Sound.play()
random_num = random.randint(0,11)
leds.on(random_num)
score += 1
pygame.display.update()
current_Time = int(time.time())
time_Out = current_Time - start
#pygame.display.update()
#print("TIMER: ",time_Out)
#print(type(start_Time))
#print(current_Time)
#print(type(current_Time))
#pygame.display.update()
# FINAL score ------------------------
final_score()
exit()
图像是时间条。在代码中,我们在每次刷新时在屏幕上移动 50 个像素。
提前致谢。
解决方法
这是一个最小的例子,也许你会发现它很有用:
import pygame
pygame.init()
width,height = 640,480
screen = pygame.display.set_mode((width,height))
fps = 60
clock = pygame.time.Clock()
progress_width = 0 # initialse progress tracker
total_time = 0
target_time = 10_000 # ten seconds in milliseconds
finished = False
while not finished:
# Handle Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
elif event.type == pygame.KEYDOWN:
progress_width = 0 # reset progress
total_time = 0
# Update Game State
dt = clock.tick(fps) # limit FPS and return time since last call
total_time += dt
progress_width += width * dt / target_time # scale bar width
progress_rect = pygame.Rect(0,height-20,int(progress_width),20)
# Draw Background
screen.fill(pygame.Color("black"))
# Draw Sprites
pygame.draw.rect(screen,pygame.Color("red"),progress_rect)
# Update Display
pygame.display.flip()
# Display the elapsed time in the title bar
pygame.display.set_caption(f"Simple Progress {total_time:,d} ms")
pygame.quit()
它计算经过的时间并更新进度条宽度。填充屏幕宽度需要 10 秒钟,按一个键会重置进度。
您的主循环应该类似于:
- 处理事件
- 更新游戏状态
- 绘制精灵
- 更新屏幕
如果您尝试在多个位置更新屏幕或处理事件,事情很快就会变得混乱。