Reputation: 33
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?
Upvotes: 2
Views: 13095
Reputation: 71
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.
Upvotes: 0
Reputation: 932
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))
Upvotes: 1
Reputation: 11
If you set self.cookie_count = 0
then its type is integer. len()
works on lists, tuples and strings but not on integers.
Upvotes: 0
Reputation: 713
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.
Upvotes: 2