В 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()