Thilo G
Thilo G

Reputation: 93

IndexError: string index out of range, when iterating over dict of lists

I'm sorry if this should be considered a duplicate, I went over several other questions and couldn't locate the mistake because it is probably to special to my case...

I know the problem is somewhere here, I'm using this to draw each char in a dictionary:

Edit: Alright, this was to abstract for a concrete example, I don't know where it's going wrong, so I'll post the whole code:

import pygame, random, time, sys, string, itertools

check_errors = pygame.init()

################### Main Variables ######################

PSwith = 460
PSheight = 460
playSurface = pygame.display.set_mode((PSwith, PSheight))

rowsCount = int(PSwith/10 - 1)
columnsCount = int(PSheight/10 - 1)

print('rows: ', rowsCount)
print('columns: ', columnsCount)

alphabet = list(string.ascii_letters + string.punctuation + string.digits)

red = pygame.Color(255,0,0)
blue = pygame.Color(0,0,255)
green = pygame.Color(0,255,0)
white = pygame.Color(255,255,255)
black = pygame.Color(0,0,0)

defaultColor = green
activeColor = white

fpsController = pygame.time.Clock()

################### Important Functions ######################

def drawChar(char, x, y, color):
    CharFont = pygame.font.SysFont('hermit', 15)
    CharSurf = CharFont.render(char, True, color)
    CharRect = CharSurf.get_rect()
    CharRect.midtop = (x, y)
    playSurface.blit(CharSurf, CharRect)

CharPosMatrix = []
CharLibrary = []

def setCharPos(row):
    for column in range(1, int(PSwith/10)):
        CharPosMatrix.append((column*10, row*10))

for row in range(1, int(PSheight/10)):
    setCharPos(row)

print('CharPosMatrix: ', CharPosMatrix)
print('len CharPosMatrix:', len(CharPosMatrix))


### assembling char library, with default color ###
for i in range(rowsCount * columnsCount):
        CharLibrary.append([random.choice(alphabet), defaultColor])

print('CharLibrary: ', CharLibrary)
print('len CharLibrary:', len(CharLibrary))

#MatrixDict = dict(zip(CharLibrary, CharPosMatrix))
MatrixDict = dict(zip(CharPosMatrix,CharLibrary)) #zipping each character with a x,y coord
print('MatrixDict: ', MatrixDict)
print('len MatrixDict: ', len(MatrixDict))

################### Main Loop ######################

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    playSurface.fill(black)

    holderlist = []
    indexCounter = 0


    for key, value in MatrixDict.items():
        drawChar(value[0], key[0], key[1], value[1])
        print(key)
        print(value)

    ### start changing random elements ###

    n = 0
    for i in range(random.randint(1, 200)):
        MatrixDict[random.choice(CharPosMatrix)]= random.choice(alphabet)
        n += 1
    print('randomly changed characters: ', n)

    randColumn = 0
    for i in range(10):
        MatrixDict[(10, 10)] = 'X'

    pygame.display.flip()

    fpsController.tick(60) 

the part where I actually know, the error spawns is:

        for key, value in MatrixDict.items():
            drawChar(value[0], key[0], key[1], value[1])
            print(key)
            print(value) 

if I change value[1] to the variable green i.e., the code runs...

Upvotes: 1

Views: 405

Answers (1)

JuhaniTakkunen
JuhaniTakkunen

Reputation: 176

You have set up MatrixDict correctly in the beginning, and everything works correctly the first time main while-loop is iterated. In the end of the while-loop however there are two lines where you modify MatrixDict, which breaks the code for future iterations:

88: MatrixDict[random.choice(CharPosMatrix)] = random.choice(alphabet)
94: MatrixDict[(10, 10)] = 'X'

In both cases, you need to specify color as well as character, eg:

88: MatrixDict[random.choice(CharPosMatrix)] = random.choice(alphabet), defaultColor
94: MatrixDict[(10, 10)] = 'X', defaultColor

Upvotes: 1

Related Questions