es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

¿Cómo usar datos de archivos csv con pygame?

Estoy haciendo un juego de plataformas 2D usando pygame y actualmente estoy tratando de implementar un sistema de cámara. Este es el código que estoy utilizando para ello, extraído del juego:

class Camera():
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = pygame.Rect(0, 0, width, height)

def apply(self, target):
    return target.rect.move(self.state.topleft)

def update(self, target):
    self.state = self.camera_func(self.state, target.rect)

def camera_move(camera, target_rect):
    x = -target_rect.center[0] + HALF_WIDTH
    y = -target_rect.center[1] + HALF_HEIGHT
    camera.topleft += (pygame.Vector2((x, y)) - pygame.Vector2(camera.topleft)) * 0.06
    camera.x = max(-(camera.width-SCREEN_WIDTH), min(0, camera.x))
    camera.y = max(-(camera.height-SCREEN_HEIGHT), min(0, camera.y))

    return camera

player_x = 340
player_y = SCREEN_HEIGHT - 190
player = Player(player_x, player_y)
entities = pygame.sprite.Group()

load in level

f = open("Levels/level1.csv", "r")
data = csv.reader(f)
data = [row for row in data]
f.close()
world = World(data)

total_level_width = len(data[0])*TILE_SIZE[0]
total_level_height = len(data)*TILE_SIZE[1]
camera = Camera(Camera.camera_move, total_level_width, total_level_height)
entities.add(player)

Sin embargo, cuando ejecuto esto, aparece un error:

total_level_width = len(data[0])*TILE_SIZE[0]
TypeError: objeto 'int' no es subscriptable

He intentado reemplazar data con list(data), pero arroja el mismo error.

Tags:  , ,

Answer

  1. Avatar for davy.ai

    El error te está indicando que TILE_SIZE[0] es del tipo int y no se puede subindexar. Esto significa que TILE_SIZE es un entero y no una lista o tupla. Por lo tanto, no puedes utilizar el operador de subíndice [] en él. Para solucionar este error, debes hacer de TILE_SIZE una lista o una tupla que contenga dos enteros.

    Por ejemplo, si TILE_SIZE está definido actualmente como un entero como este:

    TILE_SIZE = 32
    

    Debes cambiarlo a una tupla o una lista como este:

    TILE_SIZE = (32, 32)
    

    o

    TILE_SIZE = [32, 32]
    

    Luego puedes utilizarlo en tu código sin ningún problema.

Comments are closed.