‘text must be a unicode or bytes’

I am making a 2d platforming game in python and have managed to get everything to work apart from displaying vital attributes such as player health.

I have successfully extracted the player’s health, however when I try to display it, I am getting the error in the title.

This is the code I am using to display it:

localplayerhealth=player.gethealth()

healthmessage=('HEALTH: ',localplayerhealth,'%')

messagedisplay(healthmessage,BLACK,500,600, 30, 30, 'mediumfont')

localplayerhealth is a integer data type. I have tried many ways to get this to work, but for some reason they do not work.

Full traceback:

loop(gameclass,s,ishost,received)
  File "C:UsersLukeDesktopYear13CABase.py", line 579, in loop
    player.updateposition(True,False)
  File "C:UsersLukeDesktopYear13CAPlayerClasses.py", line 249, in updateposition
    playerhealth=messagedisplay(self.health,BLACK,500,500, 30, 30, 'smallfont')
  File "C:UsersLukeDesktopYear13CAShared.py", line 22, in messagedisplay
    surface, rectangle = textobject(message,colour,font)  #assigns both the variables of surface and rectangle to the output of the subroutine called with the imported parameters.
  File "C:UsersLukeDesktopYear13CAShared.py", line 10, in textobject
    textSurface = smallfont.render(text, True, colour)
TypeError: text must be a unicode or bytes

Answer

If you want to construct a string to be displayed you have to provide proper formatting. Right now you are creating a tuple:

>>> localplayerhealth=1
>>> 'HEALTH: ',localplayerhealth,'%'
('HEALTH: ', 1, '%')

I guess that you need a string:

>>> to_display = "HEALTH: {}%".format(localplayerhealth)
>>> to_display
'HEALTH: 1%'

Leave a Reply

Your email address will not be published. Required fields are marked *