You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame Powerbar衰减脚本问题:显示不更新且循环异常

Fixing Pygame Powerbar Decay Display Issue

Hey there! Let's sort out that powerbar decay problem you're having. The main issues with your current code are likely that your decay loop is blocking the main Pygame event loop (so no screen updates happen) and you're not properly handling the redraw process during decay. Here's how to fix it:

Key Fixes Explained:

  • Integrate decay into the main loop: Instead of running a separate loop for decay, handle it within Pygame's main event loop so events and screen updates keep working.
  • Track decay state: Use a boolean variable to know when to start decreasing the bar width.
  • Consistent frame rate: Use pygame.time.Clock() to ensure decay speed is smooth and consistent across different systems.
  • Redraw every frame: Always clear the screen and redraw the bar each iteration of the loop, then update the display to show changes.

Revised Full Code:

import pygame

# Initialize Pygame
pygame.init()

# Screen setup
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Powerbar Demo")

# Colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)

# Powerbar variables
bar_start_width = 0
bar_height = 50
bar_x = (screen_width // 2) - 200  # Center the bar horizontally
bar_y = screen_height - 100
max_bar_width = 400
decay_speed = 2  # How much to decrease the bar width per frame
is_decaying = False

# Clock for frame rate control
clock = pygame.time.Clock()
fps = 60

running = True
while running:
    # Handle all Pygame events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
                # Stop decay when a key is pressed
                is_decaying = False
        elif event.type == pygame.KEYUP:
            if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
                # Start decay when key is released
                is_decaying = True

    # Update bar width based on input or decay state
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] or keys[pygame.K_RIGHT]:
        bar_start_width += 1
        # Terminate if bar exceeds max width
        if bar_start_width > max_bar_width:
            running = False
    elif is_decaying and bar_start_width > 0:
        bar_start_width -= decay_speed
        # Prevent bar width from going negative
        if bar_start_width < 0:
            bar_start_width = 0

    # Redraw all elements every frame
    screen.fill(BLACK)
    # Draw the powerbar
    pygame.draw.rect(screen, GREEN, (bar_x, bar_y, bar_start_width, bar_height))
    # Optional: Draw a border around the max bar size
    pygame.draw.rect(screen, WHITE, (bar_x, bar_y, max_bar_width, bar_height), 2)

    # Update the display to show changes
    pygame.display.flip()

    # Cap the frame rate to ensure consistent speed
    clock.tick(fps)

# Quit Pygame cleanly
pygame.quit()

What Changed:

  1. Main Loop Integration: The decay logic is now part of the main loop, so we never block event processing or screen updates.
  2. Decay State Tracking: The is_decaying boolean triggers when a key is released, and stops immediately when a key is pressed again.
  3. Continuous Redraw: Every frame, we fill the screen with the background color, draw the updated bar, and flip the display to reflect changes in real-time.
  4. Frame Rate Control: The clock ensures the loop runs at 60 FPS, making the decay speed predictable regardless of system performance.
  5. Proper Event Handling: We handle QUIT events to exit cleanly, and KEYUP/KEYDOWN events to toggle between bar growth and decay.

This should make your powerbar decay smoothly and update the display correctly when you release the keys. Let me know if you need further tweaks!

内容的提问来源于stack exchange,提问作者Martin Schultz Kristensen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:20:30