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

如何在PyGame中更新文本?分数变量变化但显示不更新

解决Pygame分数不动态更新的问题

问题根源

你的分数文本无法更新,核心原因是分数图像只在程序初始化时渲染了一次。后续score变量和text字符串虽随碰撞更新,但存储渲染后图像的img变量没有重新生成,屏幕始终显示最初的静态分数图像。

修改方案

将分数文本的渲染逻辑移到游戏主循环内部,确保每次循环都基于最新的score值重新生成图像。同时可以优化代码里的eval调用,用对象字典替代,提升代码安全性和可读性。

修改后的完整代码

import pygame, sys
from pygame.locals import *
import random

pygame.init()
 
FPS = 60
FramePerSec = pygame.time.Clock()

BLACK = (0, 0, 0)
WHITE = (255, 255, 255) 
GRAY = (200, 200, 200)

SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600

running = True
display = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Game")


class Arrow(pygame.sprite.Sprite):
    def __init__(self, img_path):
        super().__init__() 
        self.image = pygame.image.load(img_path)
        self.rect = self.image.get_rect()   
        self.rect.center = (random.randint(30, SCREEN_WIDTH-30), 0) 
        self._layer = self.rect.bottom 
 
    def move(self):
        self.rect.move_ip(0, 10)
        if self.rect.bottom > SCREEN_HEIGHT:
            self.rect.top = 0
            self.rect.center = (random.randint(30, SCREEN_WIDTH-30), 0)
 
    def draw(self, surface):
        surface.blit(self.image, self.rect) 

# 用字典存储箭头对象,替代eval调用
arrows = {
    1: Arrow("up.png"),
    2: Arrow("down.png"),
    3: Arrow("left.png"),
    4: Arrow("right.png")
}

rt, score = 2, 0
font = pygame.font.SysFont(None, 48)

def change(val):
    global rt
    rt = val

def getpoint():
    global score
    score += 1

class Player(pygame.sprite.Sprite):
    def __init__(self): 
        super().__init__() 
        self.image = pygame.image.load("Player.png")
        self.rect = self.image.get_rect()
        self.rect.center = (160, 520)
    
    def update(self):
        pressed_keys = pygame.key.get_pressed()
        if self.rect.left > 0 and pressed_keys[K_LEFT]:
            self.rect.move_ip(-10, 0)
        if self.rect.right < SCREEN_WIDTH and pressed_keys[K_RIGHT]:
            self.rect.move_ip(10, 0)
        
        current_arrow = arrows[rt]
        if self.rect.colliderect(current_arrow.rect):
            change(random.randint(1, 4))
            getpoint()
 
    def draw(self, surface):
        surface.blit(self.image, self.rect)     
 
         
P1 = Player()

while running:   
    for event in pygame.event.get():              
        if event.type == QUIT:
            running = False
    
    P1.update()
    arrows[rt].move()

    # 每次循环都重新渲染分数文本
    text = f"Score: {score}"
    score_img = font.render(text, True, BLACK)
    score_rect = score_img.get_rect(topleft=(20, 20))

    display.fill(WHITE)
    display.blit(score_img, score_rect)
    P1.draw(display)
    arrows[rt].draw(display) 
    pygame.display.update()
    FramePerSec.tick(FPS)

pygame.quit()

额外优化说明

  1. 将重复的箭头类合并为一个Arrow基类,通过传入不同图片路径创建不同箭头,减少代码冗余
  2. 用字典存储箭头对象,彻底移除eval调用,避免安全风险同时提升代码可读性
  3. 简化玩家移动的条件判断逻辑,让代码更简洁

内容的提问来源于stack exchange,提问作者Gorzan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:47:21