Pygame list errors, object in an objectHow do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?Getting the last element of a list in PythonHow to make a flat list out of list of listsHow do I concatenate two lists in Python?Determine the type of an object?How to clone or copy a list?How do I list all files of a directory?How to read a file line-by-line into a list?

How do I prevent employees from either switching to competitors or opening their own business?

How to hide an urban landmark?

How come the nude protesters were not arrested?

How to trick the reader into thinking they're following a redshirt instead of the protagonist?

How to draw a Technology Radar?

Soft question: Examples where lack of mathematical rigour cause security breaches?

How is John Wick 3 a 15 certificate?

Non-disclosure agreement in a small business

Union with anonymous struct with flexible array member

What ways have you found to get edits from non-LaTeX users?

What's up with this leaf?

Check if three arrays contains the same element

Is it possible to have the age of the universe be unknown?

Meaning of 'lose their grip on the groins of their followers'

Giant Steps - Coltrane and Slonimsky

Which languages would be most useful in Europe at the end of the 19th century?

With Ubuntu 18.04, how can I have a hot corner that locks the computer?

Any way to create a link to a custom setting's "manage" page?

Wooden cooking layout

Thread Pool C++ Implementation

What is the purpose of the goat for Azazel, as opposed to conventional offerings?

Why didn't Voldemort recognize that Dumbledore was affected by his curse?

What makes Ada the language of choice for the ISS's safety-critical systems?

Importance of Building Credit Score?



Pygame list errors, object in an object


How do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?Getting the last element of a list in PythonHow to make a flat list out of list of listsHow do I concatenate two lists in Python?Determine the type of an object?How to clone or copy a list?How do I list all files of a directory?How to read a file line-by-line into a list?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am running pygame and trying to familiarise my self with the module. Whenever I run this code, it always comes up with this problem:




levelObj = levels[levelNum] 


IndexError: list index out of range




the code I have entered shows the only instances levelNum comes up



def runLevel(levels, levelNum):
global currentImage
levelObj = levels[levelNum]
mapObj = decorateMap(levelObj['mapObj'], levelObj['startState']['player'])
gameStateObj = copy.deepcopy(levelObj['startState'])
mapNeedsRedraw = True
levelSurf = BASICFONT.render('Level %s of %s' % (levelNum + 1, len(levels)), 1, TEXTCOLOR)
levelRect = levelSurf.get_rect()
levelRect.bottomleft = (20, WINHEIGHT - 35)
mapWidth = len(mapObj) * TILEWIDTH
mapHeight = (len(mapObj[0]) - 1) * TILEFLOORHEIGHT + TILEHEIGHT
MAX_CAM_X_PAN = abs(HALF_WINHEIGHT - int(mapHeight / 2)) + TILEWIDTH
MAX_CAM_Y_PAN = abs(HALF_WINWIDTH - int(mapWidth / 2)) + TILEHEIGHT


and then when all the rest of the code comes together



def readLevelsFile(filename):
assert os.path.exists(filename), 'Cannot find the level file: %s' % (filename)

mapFile = open(filename, 'r')
content = mapFile.readlines() + ['rn']
mapFile.close()

levels= []
levelNum = 0
mapTextLines = []
mapObj = []
for lineNum in range (len(content)):
line = content[lineNum].rstrip('rn')

if ';' in line:
line = line[:line.find(';')]

if line != ' ':
mapTextLines.append(line)

elif line == ' ' and len(mapTextLines) > 0:
maxWidth = -1
for i in range (len(mapTextLines)):
if len(mapTextLines[i]) > maxWidth:
maxWidth = len(mapTextLines[i])


for i in range (len(mapTextLines)):
mapTextLines[i] += ' ' * (maxWidth - len(mapTextLines[i]))

for x in range (len(mapTextLines[0])):
mapObj.append([])
for y in range (len(mapTextLines)):
for x in range (maxWidth):
mapObj[x].append(mapTextLines[y][x])

startx = None
starty = None
goals = []
stars = []
for x in range (maxWidth):
for y in range (len(mapObj[x])):
if mapObj[x][y] in ('@', '+'):
startx = x
starty= y

if mapObj[x][y] in ('.', '+', '*'):
goals.append(( x, y))

if mapObj[x][y] in ('$', '*'):
stars.append(( x, y))

assert startx != None and starty != None, 'Level %s (around line %s) in %s is missing a '@' or '+' to mark the start pont.' % (levelNum + 1, lineNum, filename)

assert len(goals) > 0, 'Level %s (around line &s) in %s must have at least one goal. ' % (levelNum+1, lineNum, filename)

assert len(stars) >= len(goals), 'Level %s (around line %s) in %s is impossible to solve. It has %s goals but only %s stars.' % (levelNum+1, lineNum, filename, len(goals), len(stars))


gameStateObj = 'player': (startx, starty),
'stepCounter': 0,
'stars': stars

levelObj = 'width': maxWidth,
'height': len(mapObj),
'mapObj': mapObj,
'goals': goals,
'startState': gameStateObj

levels.append(levelObj)

mapTextLines = []
mapObj = []
gameStateObj =
levelNum += 1
return levels









share|improve this question






























    0















    I am running pygame and trying to familiarise my self with the module. Whenever I run this code, it always comes up with this problem:




    levelObj = levels[levelNum] 


    IndexError: list index out of range




    the code I have entered shows the only instances levelNum comes up



    def runLevel(levels, levelNum):
    global currentImage
    levelObj = levels[levelNum]
    mapObj = decorateMap(levelObj['mapObj'], levelObj['startState']['player'])
    gameStateObj = copy.deepcopy(levelObj['startState'])
    mapNeedsRedraw = True
    levelSurf = BASICFONT.render('Level %s of %s' % (levelNum + 1, len(levels)), 1, TEXTCOLOR)
    levelRect = levelSurf.get_rect()
    levelRect.bottomleft = (20, WINHEIGHT - 35)
    mapWidth = len(mapObj) * TILEWIDTH
    mapHeight = (len(mapObj[0]) - 1) * TILEFLOORHEIGHT + TILEHEIGHT
    MAX_CAM_X_PAN = abs(HALF_WINHEIGHT - int(mapHeight / 2)) + TILEWIDTH
    MAX_CAM_Y_PAN = abs(HALF_WINWIDTH - int(mapWidth / 2)) + TILEHEIGHT


    and then when all the rest of the code comes together



    def readLevelsFile(filename):
    assert os.path.exists(filename), 'Cannot find the level file: %s' % (filename)

    mapFile = open(filename, 'r')
    content = mapFile.readlines() + ['rn']
    mapFile.close()

    levels= []
    levelNum = 0
    mapTextLines = []
    mapObj = []
    for lineNum in range (len(content)):
    line = content[lineNum].rstrip('rn')

    if ';' in line:
    line = line[:line.find(';')]

    if line != ' ':
    mapTextLines.append(line)

    elif line == ' ' and len(mapTextLines) > 0:
    maxWidth = -1
    for i in range (len(mapTextLines)):
    if len(mapTextLines[i]) > maxWidth:
    maxWidth = len(mapTextLines[i])


    for i in range (len(mapTextLines)):
    mapTextLines[i] += ' ' * (maxWidth - len(mapTextLines[i]))

    for x in range (len(mapTextLines[0])):
    mapObj.append([])
    for y in range (len(mapTextLines)):
    for x in range (maxWidth):
    mapObj[x].append(mapTextLines[y][x])

    startx = None
    starty = None
    goals = []
    stars = []
    for x in range (maxWidth):
    for y in range (len(mapObj[x])):
    if mapObj[x][y] in ('@', '+'):
    startx = x
    starty= y

    if mapObj[x][y] in ('.', '+', '*'):
    goals.append(( x, y))

    if mapObj[x][y] in ('$', '*'):
    stars.append(( x, y))

    assert startx != None and starty != None, 'Level %s (around line %s) in %s is missing a '@' or '+' to mark the start pont.' % (levelNum + 1, lineNum, filename)

    assert len(goals) > 0, 'Level %s (around line &s) in %s must have at least one goal. ' % (levelNum+1, lineNum, filename)

    assert len(stars) >= len(goals), 'Level %s (around line %s) in %s is impossible to solve. It has %s goals but only %s stars.' % (levelNum+1, lineNum, filename, len(goals), len(stars))


    gameStateObj = 'player': (startx, starty),
    'stepCounter': 0,
    'stars': stars

    levelObj = 'width': maxWidth,
    'height': len(mapObj),
    'mapObj': mapObj,
    'goals': goals,
    'startState': gameStateObj

    levels.append(levelObj)

    mapTextLines = []
    mapObj = []
    gameStateObj =
    levelNum += 1
    return levels









    share|improve this question


























      0












      0








      0








      I am running pygame and trying to familiarise my self with the module. Whenever I run this code, it always comes up with this problem:




      levelObj = levels[levelNum] 


      IndexError: list index out of range




      the code I have entered shows the only instances levelNum comes up



      def runLevel(levels, levelNum):
      global currentImage
      levelObj = levels[levelNum]
      mapObj = decorateMap(levelObj['mapObj'], levelObj['startState']['player'])
      gameStateObj = copy.deepcopy(levelObj['startState'])
      mapNeedsRedraw = True
      levelSurf = BASICFONT.render('Level %s of %s' % (levelNum + 1, len(levels)), 1, TEXTCOLOR)
      levelRect = levelSurf.get_rect()
      levelRect.bottomleft = (20, WINHEIGHT - 35)
      mapWidth = len(mapObj) * TILEWIDTH
      mapHeight = (len(mapObj[0]) - 1) * TILEFLOORHEIGHT + TILEHEIGHT
      MAX_CAM_X_PAN = abs(HALF_WINHEIGHT - int(mapHeight / 2)) + TILEWIDTH
      MAX_CAM_Y_PAN = abs(HALF_WINWIDTH - int(mapWidth / 2)) + TILEHEIGHT


      and then when all the rest of the code comes together



      def readLevelsFile(filename):
      assert os.path.exists(filename), 'Cannot find the level file: %s' % (filename)

      mapFile = open(filename, 'r')
      content = mapFile.readlines() + ['rn']
      mapFile.close()

      levels= []
      levelNum = 0
      mapTextLines = []
      mapObj = []
      for lineNum in range (len(content)):
      line = content[lineNum].rstrip('rn')

      if ';' in line:
      line = line[:line.find(';')]

      if line != ' ':
      mapTextLines.append(line)

      elif line == ' ' and len(mapTextLines) > 0:
      maxWidth = -1
      for i in range (len(mapTextLines)):
      if len(mapTextLines[i]) > maxWidth:
      maxWidth = len(mapTextLines[i])


      for i in range (len(mapTextLines)):
      mapTextLines[i] += ' ' * (maxWidth - len(mapTextLines[i]))

      for x in range (len(mapTextLines[0])):
      mapObj.append([])
      for y in range (len(mapTextLines)):
      for x in range (maxWidth):
      mapObj[x].append(mapTextLines[y][x])

      startx = None
      starty = None
      goals = []
      stars = []
      for x in range (maxWidth):
      for y in range (len(mapObj[x])):
      if mapObj[x][y] in ('@', '+'):
      startx = x
      starty= y

      if mapObj[x][y] in ('.', '+', '*'):
      goals.append(( x, y))

      if mapObj[x][y] in ('$', '*'):
      stars.append(( x, y))

      assert startx != None and starty != None, 'Level %s (around line %s) in %s is missing a '@' or '+' to mark the start pont.' % (levelNum + 1, lineNum, filename)

      assert len(goals) > 0, 'Level %s (around line &s) in %s must have at least one goal. ' % (levelNum+1, lineNum, filename)

      assert len(stars) >= len(goals), 'Level %s (around line %s) in %s is impossible to solve. It has %s goals but only %s stars.' % (levelNum+1, lineNum, filename, len(goals), len(stars))


      gameStateObj = 'player': (startx, starty),
      'stepCounter': 0,
      'stars': stars

      levelObj = 'width': maxWidth,
      'height': len(mapObj),
      'mapObj': mapObj,
      'goals': goals,
      'startState': gameStateObj

      levels.append(levelObj)

      mapTextLines = []
      mapObj = []
      gameStateObj =
      levelNum += 1
      return levels









      share|improve this question
















      I am running pygame and trying to familiarise my self with the module. Whenever I run this code, it always comes up with this problem:




      levelObj = levels[levelNum] 


      IndexError: list index out of range




      the code I have entered shows the only instances levelNum comes up



      def runLevel(levels, levelNum):
      global currentImage
      levelObj = levels[levelNum]
      mapObj = decorateMap(levelObj['mapObj'], levelObj['startState']['player'])
      gameStateObj = copy.deepcopy(levelObj['startState'])
      mapNeedsRedraw = True
      levelSurf = BASICFONT.render('Level %s of %s' % (levelNum + 1, len(levels)), 1, TEXTCOLOR)
      levelRect = levelSurf.get_rect()
      levelRect.bottomleft = (20, WINHEIGHT - 35)
      mapWidth = len(mapObj) * TILEWIDTH
      mapHeight = (len(mapObj[0]) - 1) * TILEFLOORHEIGHT + TILEHEIGHT
      MAX_CAM_X_PAN = abs(HALF_WINHEIGHT - int(mapHeight / 2)) + TILEWIDTH
      MAX_CAM_Y_PAN = abs(HALF_WINWIDTH - int(mapWidth / 2)) + TILEHEIGHT


      and then when all the rest of the code comes together



      def readLevelsFile(filename):
      assert os.path.exists(filename), 'Cannot find the level file: %s' % (filename)

      mapFile = open(filename, 'r')
      content = mapFile.readlines() + ['rn']
      mapFile.close()

      levels= []
      levelNum = 0
      mapTextLines = []
      mapObj = []
      for lineNum in range (len(content)):
      line = content[lineNum].rstrip('rn')

      if ';' in line:
      line = line[:line.find(';')]

      if line != ' ':
      mapTextLines.append(line)

      elif line == ' ' and len(mapTextLines) > 0:
      maxWidth = -1
      for i in range (len(mapTextLines)):
      if len(mapTextLines[i]) > maxWidth:
      maxWidth = len(mapTextLines[i])


      for i in range (len(mapTextLines)):
      mapTextLines[i] += ' ' * (maxWidth - len(mapTextLines[i]))

      for x in range (len(mapTextLines[0])):
      mapObj.append([])
      for y in range (len(mapTextLines)):
      for x in range (maxWidth):
      mapObj[x].append(mapTextLines[y][x])

      startx = None
      starty = None
      goals = []
      stars = []
      for x in range (maxWidth):
      for y in range (len(mapObj[x])):
      if mapObj[x][y] in ('@', '+'):
      startx = x
      starty= y

      if mapObj[x][y] in ('.', '+', '*'):
      goals.append(( x, y))

      if mapObj[x][y] in ('$', '*'):
      stars.append(( x, y))

      assert startx != None and starty != None, 'Level %s (around line %s) in %s is missing a '@' or '+' to mark the start pont.' % (levelNum + 1, lineNum, filename)

      assert len(goals) > 0, 'Level %s (around line &s) in %s must have at least one goal. ' % (levelNum+1, lineNum, filename)

      assert len(stars) >= len(goals), 'Level %s (around line %s) in %s is impossible to solve. It has %s goals but only %s stars.' % (levelNum+1, lineNum, filename, len(goals), len(stars))


      gameStateObj = 'player': (startx, starty),
      'stepCounter': 0,
      'stars': stars

      levelObj = 'width': maxWidth,
      'height': len(mapObj),
      'mapObj': mapObj,
      'goals': goals,
      'startState': gameStateObj

      levels.append(levelObj)

      mapTextLines = []
      mapObj = []
      gameStateObj =
      levelNum += 1
      return levels






      python pygame






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 at 18:21









      Rabbid76

      49.5k123658




      49.5k123658










      asked Mar 24 at 18:15









      chris fchris f

      11




      11






















          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55326964%2fpygame-list-errors-object-in-an-object%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55326964%2fpygame-list-errors-object-in-an-object%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Obelisk of Theodosius Contents History Description Notes Bibliography Further reading External links Navigation menuAge of spirituality : late antique and early Christian art, third to seventh centuryOver 60 picturesObelisks of the World41°00′21.24″N 28°58′31.43″E / 41.0059000°N 28.9753972°E / 41.0059000; 28.97539727724550-7235741376235741376

          밀양 대씨 역사 각주 함께 보기 둘러보기 메뉴밀양 대씨

          1973년 목차 사건 문화 탄생 사망 노벨상 달력 둘러보기 메뉴