打印分数 - Pygame
有没有人知道我怎么才能把分数显示在我游戏的屏幕上?
到目前为止,我有这段代码:
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 必须是 Unicode 或字节"
有没有人知道我该怎么解决这个问题?
谢谢!
2 个回答
2
你需要把分数转换成一个字符串。
text = font.render(str(score), 1, (WHITE))
4
好的,首先你问的是如何正确地绘制网站,这其实和之前的回答差不多。但你在把内容显示到屏幕上的方式上有点问题。
现在你是在每次循环的时候都把分数显示到屏幕上,这样就会导致你遇到的问题。其实应该在循环结束后再显示分数。
举个例子:
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)
这样应该就能正常工作了。如果你还需要其他帮助,请告诉我。