`generateBase()` taking super long to run

Question:
The generateBase() function in my game’s code is taking super long to run. Here’s what I ran in the console:

generateBase("lunar threat", "lunar menace", "lunar fighter", 10)

It was taking a while to run so I checked Replit Ask and when I came back, it was still running. What’s happening?

Here is the code for the generateBase function so you can debug:

def generateBase(alien1, alien2, alien3, alien_max):
  # Difficulties:
  #  - <33
  #   * 45% alien 1
  #   * 30% alien 2
  #   * 25% alien 3
  #  - 33-67
  #   * 40% alien 2
  #   * 35% alien 1
  #   * 25% alien 3
  #  - 67+
  #   * 35% alien 3
  #   * 35% alien 2
  #   * 30% alien 1

  aliens = randint(1, alien_max)
  diff = randint(1, 100)
  retVal = []
  i = 0
  while i < aliens:
    alien_chance = randint(1, 100)
    if diff <= 33:
      if alien_chance < 45:
        retVal.append(alien1)
      elif alien_chance >= 45 and alien_chance < 75:
        retVal.append(alien2)
      else:
        retVal.append(alien3)
    elif diff > 33 and diff <= 67:
      if alien_chance < 40:
        retVal.append(alien2)
      elif alien_chance >= 40 and alien_chance < 75:
        retVal.append(alien1)
      else:
        retVal.append(alien3)
    else:
      if alien_chance < 35:
        retVal.append(alien3)
      elif alien_chance <= 35 and alien_chance < 70:
        retVal.append(alien2)
      else:
        retVal.append(alien1)
  return retVal

Repl link:
https://replit.com/@element1010/Expedition#main.py

You forgot to increment the i variable so the loop runs forever.
In python, it is much better to use:

for i in range(aliens):
  print('hi')

instead of:

i = 0
while i < aliens:
  print('hi')
  i += 1
5 Likes

You can further simplify your code by realizing that you don’t need to check if a number x is greater than chance c in your elif condition because the previous clause if x <= c guarantees it.

1 Like

Thank you.

Yes, I don’t like that for some reason though. Maybe is just because I started coding with JavaScript and that’s the style I like better.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.