当我尝试弄平瓷砖时,它说“列表索引超出范围”。我不知道该怎么办,因为这是我的新手。
错误消息:
window.blit(tilemap.textures [tilemap.tilemap [row] [column]],(column tilemap.tilesize,row tilemap.tilesize)) IndexError:列表索引超出范围
我试图更改mapwidth
和mapheight
的值,但这并没有解决问题。我有2个脚本。主图和图块映射。因此可能存在错误。注意(我已经在完整代码中初始化了pygame,所以这不是问题)
main.py
import pygame as pg
# Importing files
import constants
import classes
import tilemap
# Functions
def draw_game():
""" This function draws everything on the screen """
global window, clock
# The background
window.blit(constants.img_background, (0, 0))
# Tiles
for row in range(tilemap.mapheight):
for column in range(tilemap.mapwidth):
window.blit(tilemap.textures[tilemap.tilemap[row][column]], (column*tilemap.tilesize, row*tilemap.tilesize))
# Updating
clock.tick(60)
pg.display.update()
tilemap.py
import pygame as pg
import constants
GRASS = 0
WATER = 1
textures = {
GRASS : pg.image.load("image\\grass.png"),
WATER : pg.image.load("image\\water.png")
}
tilemap = [
[GRASS, GRASS, GRASS, WATER],
[GRASS, GRASS, WATER, GRASS],
[GRASS, WATER, GRASS, GRASS],
[WATER, GRASS, GRASS, GRASS]
]
tilesize = 40
mapwidth = 2
mapheight = 5
答案 0 :(得分:1)
tilemap
是一个列表。该列表包含4个元素,列表的每个元素也是一个包含4个元素的列表。
tilemap = [ [GRASS, GRASS, GRASS, WATER], [GRASS, GRASS, WATER, GRASS], [GRASS, WATER, GRASS, GRASS], [WATER, GRASS, GRASS, GRASS] ]
因此图块地图的“宽度”和“高度”为4:
mapwidth = 4
mapheight = 4
但是您根本不需要该变量,因为您可以通过len()
获得列表的长度:
for row in range( len(tilemap.tilemap) ):
for column in range( len(tilemap.tilemap[row]) ):
window.blit(tilemap.textures[tilemap.tilemap[row][column]],
(column*tilemap.tilesize, row*tilemap.tilesize))
如果您想在地图上放置更多图块,则只需向tilemap:
添加更多图块即可。
例如
tilemap = [
[WATER, WATER, WATER, WATER, WATER, WATER],
[WATER, GRASS, GRASS, GRASS, WATER, WATER],
[WATER, GRASS, GRASS, WATER, GRASS, WATER],
[WATER, GRASS, WATER, GRASS, GRASS, WATER],
[WATER, WATER, GRASS, GRASS, GRASS, WATER],
[WATER, WATER, WATER, WATER, WATER, WATER]
]
mapwidth = len(tilemap.tilemap)
mapheight = len(tilemap.tilemap[0])