Skip to main content
 首页 » 编程设计

python之打印乐谱之Pygame

2025年05月04日16tintown

有谁知道我怎样才能让分数显示在我的游戏屏幕上?

到目前为止我有这段代码:

for bullet in bullet_list: 
 
        block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True) 
 
        for block in block_hit_list: 
        explosion.play() 
        bullet_list.remove(bullet) 
        all_sprites_list.remove(bullet) 
        score += 10 
        font = pygame.font.Font(None, 36) 
        text = font.render(score, 1, (WHITE)) 
        textpos = text.get_rect(centerx=background.get_width()/2) 
        background.blit(text, textpos) 
 
    if bullet.rect.y < -10: 
        bullet_list.remove(bullet) 
        all_sprites_list.remove(bullet) 

但是,一旦我启动游戏并发射子弹,我就会收到此错误:

"text = font.render(score, 1, (WHITE))

TypeError: text must be a unicode or bytes"

有谁知道我该如何解决这个问题?

谢谢

请您参考如下方法:

好的,所以首先您问的是如何正确绘制站点,这就像之前的答案一样,但是您将其 blit 到屏幕的方式是错误的。

您目前每次通过 for 循环时都会将分数 blit 到屏幕,这会导致它产生您正在体验的效果。这应该就在 for 循环之后。 示例:

for bullet in bullet_list:  
    block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)  
    for block in block_hit_list: 
        explosion.play() 
        bullet_list.remove(bullet) 
        all_sprites_list.remove(bullet)  
        score += 10 
        #removed this line!!!! ~ font = pygame.font.Font(None, 36)  
        #removed this line to!!!! ~ text = font.render(score, 1, (WHITE))  
        #remove this line also!!! ~ textpos = text.get_rect(centerx=background.get_width()/2)  
        #finally remove this line!!!! ~ background.blit(text, textpos)  
    if bullet.rect.y < -10: 
        bullet_list.remove(bullet)  
        all_sprites_list.remove(bullet) 
#add in those removed lines after your for loop. 
font = pygame.font.Font(None, 36) 
text = font.render(score, 1, (WHITE)) 
textpos = text.get_rect(centerx=background.get_width()/2) 
background.blit(text, textpos) 

这应该有效。如果您需要任何进一步的帮助,请告诉我。