I’m trying to code a ‘High Scores program’, which simply accesses values from a separate file and then displays them on the screen. Here’s my code:
#high scores program #imports score values from a seperate file an prints them on the screen import pygame,sys,random from pygame import * pygame.init() WINWIDTH=640 #width of the window in pixels WINHEIGHT=420 #height of the window in pixels FPS=30 #frames per second # r g b RED= (255, 0, 0) BLACK=( 0, 0, 0) def get_text(pos,text,size,color): """Returns a text surface and a rect object based on the parameters given to be displayed on the screen. """ BASICFONT=pygame.font.Font('freesansbold.ttf',size) textSurf=BASICFONT.render(text,True,RED) rectObj=textSurf.get_rect() retcObj.center=(size) return textSurf,rectObj def displayScores(): """Displays the high scores on the screen. """ #keep track of how many scores have been displayed on the screen index=0 #add each line of the high scores file into a list scores=[] for line in scoresFile: scores.append(line) #a list containing all of the score surfaces and rect objects scoresList=[] while True: DISPLAYSURF.fill(BLACK) for event in pygame.event.get(): #event loop if event.type==QUIT: pygame.quit() sys.exit() for i in scores: index+=1 scoreSurf,scoreObj=get_text((WINWIDTH/2,(index*10)),'%s.:%s'%(index,i),15,RED) scoresList.append([scoreSurf,scoreObj]) DISPLAYSURF.blit(scoresList[0][0],scoresList[0][1]) pygame.display.update() FPSCLOCK.tick(FPS) while True: #main loop global DISPLAYSURF,FPSCLOCK DISPLAYSURF=pygame.display.set_mode((WINWIDTH,WINHEIGHT)) pygame.display.set_caption('High Scores!') FPSCLOCK=pygame.time.Clock() #randomly select a number between 1 and 100 to be added to the high scores randomScore=random.randint(0,100) #open the high scores file in read/ append mode scoresFile=open('highScores.txt','a+') displayScores() scoresFile.close() Everytime I run the program I get an IndexError saying that when the line ‘DISPLAYSURF.blit(scoresList[0][0],scoresList[0][1])’ runs, the list index is out of range. Can anyone help me? I’m using Python 3.2.3.