Python 简单PyGame中的错误

Python 简单PyGame中的错误,python,pygame,Python,Pygame,我试图用Python制作一个游戏,代码如下: # 1 - Import library import pygame from pygame.locals import * # 2 - Initialize the game pygame.init() width, height = 640, 480 screen=pygame.display.set_mode((width, height)) # 3 - Load images player = pygame.image.load("res

我试图用Python制作一个游戏,代码如下:

# 1 - Import library
import pygame
from pygame.locals import *

# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))

# 3 - Load images
player = pygame.image.load("resources/images/dude.png")
grass = pygame.image.load("resources/images/grass.png")
castle = pygame.image.load("resources/images/castle.png") 

# 4 - keep looping through
while 1:
    # 5 - clear the screen before drawing it again
    screen.fill(0)
    # 6 - draw the screen elements
    for x in range(width/grass.get_width()+1):
        for y in range(height/grass.get_height()+1):
          screen.blit(grass,(x*100,y*100))
       screen.blit(castle,(0,30))
       screen.blit(castle,(0,135))
       screen.blit(castle,(0,240))
       screen.blit(castle,(0,345 ))
       screen.blit(player, (100,100))
       # 7 - update the screen
       pygame.display.flip()
       # 8 - loop through the events
       for event in pygame.event.get():
       # check if the event is the X button 
        if event.type==pygame.QUIT:
         # if it is quit the game
         pygame.quit() 
          exit(0)
这是我遇到的错误,但我不知道如何解决它:

Traceback (most recent call last):
  File "C:/Python32/Game 1/game.py", line 19, in <module>
    for x in range(width/grass.get_width()+1):
TypeError: 'float' object cannot be interpreted as an integer
回溯(最近一次呼叫最后一次):
文件“C:/Python32/Game 1/Game.py”,第19行,在
对于范围内的x(宽度/草。获取_宽度()+1):
TypeError:“float”对象不能解释为整数

范围函数需要整数而不是浮点数或字符串,可以使用
int()
函数将浮点数转换为整数

因此,不是:

for x in range(width/grass.get_width()+1):
使用:

例如:


width/grass.getwidth()似乎正在返回一个浮点值。尝试将其强制转换为int,看看这是否可以缓解您的问题。对于范围内的x(round(width/grass.get_width()+1)):显然,您应该根据您的需要向上或向下取整。
range()
需要一个
int
参数,而在您的情况下,会得到由
width/grass.get_width()+1
生成的
float
。想想看,round()似乎会返回一个float。使用int()来查看您是否获得了所需的行为。并且修复了缩进,似乎所有的while代码都在第一个循环中。谢谢,使用int()是有效的。
for x in range(int(width/grass.get_width()+1)):
print int(5.145)
>>> 5