在pygame中,我正在尝试创建一个简单的程序,该程序可以为我正在开发的游戏随机生成2d地图,并使用具有不同稀有度的不同材质。但是直到我决定将稀有性部分添加到程序中之前,它都运行良好。
在尝试实现此功能后,它给了我这个错误 :
Traceback (most recent call last):
File "/home/pi/pygame/2D game.py", line 63, in <module>
tilemap[rw][cl] = tile
IndexError: list index out of range
这是我的代码:
import pygame, sys, random
from pygame.locals import *
#List variables/constants
DIRT = 0
GRASS = 1
WATER = 2
COAL = 3
BLACK = (0, 0, 0)
BROWN = (153, 76, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
#Useful dimensions
TILESIZE = 40
MAPWIDTH = 30
MAPHEIGHT = 20
#A dictionary linking recources to textures
textures = {
DIRT : pygame.image.load("dirt.png"),
GRASS : pygame.image.load("grass.png"),
WATER : pygame.image.load("water.png"),
COAL : pygame.image.load("coal.png"),
}
#A list of resources
resources = [DIRT, GRASS, WATER, COAL]
#Using list comprehension to create a tilemap
tilemap = [ [DIRT for w in range(MAPWIDTH)] for h in range(MAPHEIGHT)]
#Initialise pygame module
pygame.init()
#Creating a new draw surface
DISPLAYSURF = pygame.display.set_mode((MAPWIDTH * TILESIZE, MAPHEIGHT * TILESIZE))
#Naming the window
pygame.display.set_caption("2D game")
#Loop through each row
for rw in range(MAPWIDTH):
#Loop through each column
for cl in range(MAPHEIGHT):
randomNumber = random.randint(0, 30)
#If a 0,the tile = coal
if randomNumber == 0:
tile = COAL
#If 1 or 2, tile = water
elif randomNumber == 1 or randomNumber == 2:
tile = WATER
#If 3 - 7, tile = grass
elif randomNumber >= 3 and randomNumber <= 7:
tile = DIRT
#if anything else, tile = dirt
else:
tile = GRASS
#Set the position on the tilemap to the randomly chosen tile
tilemap[rw][cl] = tile
#Loop forever
while True:
#Collects all the user events
for event in pygame.event.get():
#if the user wants to quit
if event.type == QUIT:
pygame.quit()
sys.exit()
#Loop through each row
for row in range(MAPHEIGHT):
#Loop through each column
for column in range(MAPWIDTH):
#Draw an image of resource at the correct position on the tilemap, using the correct texture
DISPLAYSURF.blit(textures[tilemap[row][column]], (column * TILESIZE, row * TILESIZE))
#Update the display
pygame.display.update()
答案 0 :(得分:1)
此矩阵的存储方式是第一个索引表示高度,第二个索引表示宽度。因此,您必须使用tilemap[x-direction][y-direction]
而不是tilemap[y-direction][x-direction]
。因此,在您的情况下tilemap[cl][rw] = tile
在PIL之类的程序包中也可以看到这种行为。