Hexagon Extractor

This is an excerpt of the Python code which is capable of extracting hexagon levels. Currently, I am revising this code for easier readability.

```
   """The three different lists we will use for this program."""
   _hexa = []
   _tstorm = []
   _allhexa = []

```

```
   """Use the extracted json file in txt format to
   create a list-based datastructure. It is through this
   method where all the datastructures will be filled.

```

```
   Hexagon represents an instance of a hexagon level in the raw
   text file, to be processed."""
   def extract_hexagon(data: str) -> None:
       ini = data.find('{')
       fin = data.find('}')
       hexagon = None
       while(fin >= 0):
           hexagon = data[ini:fin + 1]
           categorize(hexagon)
           #Proceed to next level.
           data = data[fin + 1:]
           ini = data.find('{')
           fin = data.find('}')

```

```
   """Inspect each hexagon, and place each into the corresponding
   array, along with the total list of all hexagons and
   thunderstorms."""
   def categorize(hexagon: str) -> None:
       ep = get_episode(hexagon)
       lvl = get_level(hexagon)
       ts = get_hardness(hexagon)
       total = getTotalLevel(ep, lvl)
       tup = (total, ep, ts)
       if (ts == 1):
           _hexa.append(tup)
       if (ts == 2):
           _tstorm.append(tup)
       _allhexa.append(tup)

```

```
   """Get the corresponding episode number of this hexagon level."""
   def get_episode(hexagon: str) -> int:
       ini = hexagon.find(':')
       fin = hexagon.find(',')
       return int(hexagon[ini + 1:fin])

```

```
   """Get the corresponding level number of this hexagon level."""
   def get_level(hexagon: str) -> int:
       hexagon = hexagon[hexagon.find(',') + 1:]
       ini = hexagon.find(':')
       fin = hexagon.find(',')
       return int(hexagon[ini + 1:fin])

```

```
   """Determine if the hexagon is simply a hexagon or a t-storm."""
   def get_hardness(hexagon: str) -> int:
       hexagon = hexagon[hexagon.find("difficulty"):]
       ini = hexagon.find(':')
       fin = hexagon.find('}')
       return int(hexagon[ini + 1:fin])

```

```
   """Obtain the total level given that you provided an episode
   and a level number."""
   def getTotalLevel(ep: int, lvl: int) -> int:
       if ep < 1:
           return -1
       if ep == 1 or ep == 2:
           return 10*(ep - 1) + lvl
       else:
           return 20 + 15*(ep - 3) + lvl

```

```
   """Save the extracted hexagon datastructure into a simple txt format."""
   def save_hexagonReport(yourSessionKey = sessionKey) -> bool:
       #Provide your session key, or the preset one. Return an error and
       #a False result if the session key expired.

```

```
       print("Session Key:", sessionKey)
       try:
           extract_hexagon(_get_url_hexagon(yourSessionKey))
       except urllib.error.HTTPError:
           print("Sorry, this list is either outdated or nonexistant!")
           return False
       s = ""

       for k in range(len(_allhexa)):
           hexa = _allhexa[k]
           if (hexa[2] == 1):
               s += (" L%d\tE%d\n" %(hexa[0],hexa[1]))
           else:
               s += (" L%d\tE%d\tT-Storm\n" %(hexa[0],hexa[1]))
           if (k < len(_allhexa) - 1 and _allhexa[k + 1][1] > _allhexa[k][1]):
               s += (" /\n")
       #Save the extracted data into a txt file, with s as the string variable.
       f = open("hexagon_report.txt", 'w')
       f.write(s)
       f.close
       return True

```

```
   """Simple implementation of converting the data into a Lua code."""
   def lua_code() -> str:
       elapsed = time.time()

       LL = 2660
       episode = 1
       lastHexIndex = 0

```

```
       """Keeping track of the index holding the previous hexagon level,
       determine if this level is a hexagon.

```

```
       It uses lastHexIndex to determine starting point; this is
       determined by the parent method."""
       def determine_result(k) -> str:
           #This algorithm finds out the next hexagon from the sorted list
           #of hexagons. The hexagon level with index lastHexIndex
           #is never greater than your current level.
           for index in range(lastHexIndex, len(_allhexa) - 1):
               hexa = _allhexa[index]
               #If the next hexagon matches the level, than output
               #the corresponding hexagon type.
                       return "Hexagon"
                   elif (hexa[2] == 2):
                       return "Super Hard"
               #If the next hexagon exceeds the level, then this level
               #is not a hexagon, and you haven't reached it yet.
               if (hexa[0] > k):

                   return ""
           return ""

```

```
       """Lua code generation runs here."""
       s = "return {\n"
       for k in range(1,2660):
           #Determine result in advance to know when to advance lastHexIndex
           result = determine_result(k)
           #Generate comments to start new episode
           if (k == 1 or k == 11):
               s += "\t--Episode " + str(episode) + "\n"
               episode += 1
           elif (k > 19 and (k + 10 - 1) % 15 == 0):
               s += "\n\t--Episode " + str(episode) + "\n"
               episode += 1
           #Generate Lua lookup references
           s += "\t[" + str(k) + "] = "
           s += "\'" + result + "\',\n"
           #If the result is a hexagon, increment lastHexIndex
           if (result != ""):
               lastHexIndex += 1
       s += "}"

```

```
       f = open("hexagon_lua.txt", 'w')
       f.write(s)
       f.close
       print("Lua code extracted in " + str(time.time() - elapsed) + "s.")
       return s

```

```
   """Hexagon extraction and creating output file executes here."""
   print(save_hexagonReport())
   lua_code()

```