TypeError: object of type 'int' has no len() - Python/Pygame

家住魔仙堡 提交于 2021-01-27 18:24:24

问题


I am creating a cookie clicker game, where there is a surface that displays how many cookies I have.

Here is my code for drawing text.

 def draw_text(self, text, font_name, size, color, x, y, align="nw"):
            font = pg.font.Font(font_name, size)
            text_surface = font.render(text, True, color)
            text_rect = text_surface.get_rect()
            self.screen.blit(text_surface, text_rect)

Then in the new function of my game loop (for when a new game starts), I created a variable:

def new(self):
        self.cookie_count = 0

And then finally, I have my drawing function.

def draw(self):
    self.draw_text('Cookies: {}'.format(len(self.cookie_count)), self.cookie_font, 105, SKYBLUE, 325, HEIGHT * 3/4, align="nw")
    pg.display.update()

Yet, when I run the program, I get:

TypeError: object of type 'int' has no len()

I am new to creating a "score counter" you could call it. But why does

self.draw_text('Cookies: {}'.format(len(self.cookie_count))

give me an error? How come the length of self.cookie_count is not printed?


回答1:


If you just want the value of self.cookie_count, you can just use

self.draw_text('Cookies: {}'.format(self.cookie_count)

The len() function returns the number of items in an object such as an array and does not work on an int object.




回答2:


You can try removing the len() function as your self.cookie_count is already an int.

So your answer should be:

self.draw_text('Cookies: {}'.format(self.cookie_count))



回答3:


If you set self.cookie_count = 0 then its type is integer. len() works on lists, tuples and strings but not on integers.




回答4:


This is what you're looking for. len() is a container function, so len(int) gives an error. Use len(str(self.cookie_count)). Hope that helps!

EDIT: This will get you the number of digits in the integer, including a negative sign. For floats this will also count the decimal point. For small numbers (less than 10^16), it's faster to use

import math
digits = math.log10(n) + 1

but this is less readable. With large numbers, rounding imprecisions give an incorrect answer, and the simplicity of the string method far outweighs its lack of speed.



来源:https://stackoverflow.com/questions/45490922/typeerror-object-of-type-int-has-no-len-python-pygame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!