Skip to content

Sourcery refactored main branch#1

Open
sourcery-ai[bot] wants to merge 1 commit intomainfrom
sourcery/main
Open

Sourcery refactored main branch#1
sourcery-ai[bot] wants to merge 1 commit intomainfrom
sourcery/main

Conversation

@sourcery-ai
Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot commented Mar 5, 2023

Branch main refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

See our documentation here.

Run Sourcery locally

Reduce the feedback loop during development by using the Sourcery editor plugin:

Review changes via command line

To manually merge these changes, make sure you're on the main branch, then run:

git fetch origin sourcery/main
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai sourcery-ai Bot requested a review from Killklli March 5, 2023 22:31
Copy link
Copy Markdown
Author

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery timed out performing refactorings.

Due to GitHub API limits, only the first 60 comments can be shown.

Comment thread version.py
@@ -1,4 +1,5 @@
"""Holds the version for DK64 Rando."""

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 15-26 refactored with the following changes:

return codecs.encode(pickle.dumps(spoiler), "base64").decode()
except Exception as e:
print("error: " + traceback.format_exc())
print(f"error: {traceback.format_exc()}")
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function generate_playthrough refactored with the following changes:

Comment thread randomizer/Fill.py
eventAdded = True
# Continue doing searches until nothing new is found
while len(newLocations) > 0 or eventAdded:
while newLocations or eventAdded:
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GetAccessibleLocations refactored with the following changes:

Comment thread randomizer/Fill.py
Comment on lines -312 to +315
allCBsFound = True
for level_index in range(7):
if sum(LogicVariables.ColoredBananas[level_index]) != 500:
# missingCBs = []
# for region_collectible_list in Logic.CollectibleRegions.values():
# for collectible in region_collectible_list:
# if collectible.enabled and not collectible.added:
# missingCBs.append(collectible)
allCBsFound = False
allCBsFound = all(
sum(LogicVariables.ColoredBananas[level_index]) == 500
for level_index in range(7)
)
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function VerifyWorld refactored with the following changes:

This removes the following comments ( why? ):

#     for collectible in region_collectible_list:
# missingCBs = []
#         if collectible.enabled and not collectible.added:
#             missingCBs.append(collectible)
# for region_collectible_list in Logic.CollectibleRegions.values():

Comment thread randomizer/Fill.py
Comment on lines -344 to +339
coinsNeeded = [maxCoins[kong] - coinsSpent[kong] for kong in range(0, 5)]
coinsNeeded = [maxCoins[kong] - coinsSpent[kong] for kong in range(5)]
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function VerifyWorldWithWorstCoinUsage refactored with the following changes:

Comment on lines -235 to +231
if logic is None:
self.logic = lambda l: True
else:
self.logic = logic
self.logic = (lambda l: True) if logic is None else logic
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Balloon.__init__ refactored with the following changes:

Comment on lines -255 to +248
return [int(spawnX), int(spawnY), int(spawnZ)]
return [spawnX, spawnY, spawnZ]
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Balloon.setSpawnPoint refactored with the following changes:

Comment thread randomizer/Prices.py
Comment on lines -105 to +116
prices = {}
parameters = GetPriceWeights(weight)
shopLocations = [location_id for location_id, location in LocationList.items() if location.type == Types.Shop]
for location in shopLocations:
prices[location] = GenerateRandomPrice(weight, parameters[0], parameters[1], parameters[2])
prices = {
location: GenerateRandomPrice(
weight, parameters[0], parameters[1], parameters[2]
)
for location in shopLocations
}
# Progressive items get their own price pool
for item in ProgressiveMoves.keys():
prices[item] = []
for i in range(ProgressiveMoves[item]):
for _ in range(ProgressiveMoves[item]):
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function RandomizePrices refactored with the following changes:

Comment thread randomizer/Prices.py
Comment on lines -120 to +127
lowerLimit = 1
if weight == RandomPrices.free:
newPrice = 0
else:
newPrice = round(random.normalvariate(avg, stddev))
lowerLimit = 1
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GenerateRandomPrice refactored with the following changes:

Comment thread randomizer/Prices.py
Comment on lines -241 to +248
if slamLevel in [1, 2]:
return settings.prices[item][slamLevel - 1]
else:
# If already have max slam, there's move to buy
return 0
return settings.prices[item][slamLevel - 1] if slamLevel in [1, 2] else 0
elif item == Items.ProgressiveAmmoBelt:
if ammoBelts in [0, 1]:
return settings.prices[item][ammoBelts]
else:
# If already have max ammo belt, there's move to buy
return 0
return settings.prices[item][ammoBelts] if ammoBelts in [0, 1] else 0
elif item == Items.ProgressiveInstrumentUpgrade:
if instUpgrades in [0, 1, 2]:
return settings.prices[item][instUpgrades]
else:
# If already have max instrument upgrade, there's move to buy
return 0
# Vanilla prices are by item, not by location
return settings.prices[item][instUpgrades] if instUpgrades in [0, 1, 2] else 0
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GetPriceAtLocation refactored with the following changes:

  • Split conditional into multiple branches (split-or-ifs)
  • Simplify conditional into switch-like form (switch)
  • Replace if statement with if expression [×3] (assign-if-exp)

This removes the following comments ( why? ):

# If already have max instrument upgrade, there's move to buy
# If already have max ammo belt, there's move to buy
# Vanilla prices are by item, not by location
# If already have max slam, there's move to buy

Comment thread randomizer/Prices.py
Comment on lines -274 to +264
if price is not None:
# print("KongCanBuy checking item: " + str(LocationList[location].item))
# print("for kong: " + kong.name + " with " + str(coins[kong]) + " coins")
# print("has price: " + str(price))
return logic.GetCoins(kong) >= price
else:
return False
return logic.GetCoins(kong) >= price if price is not None else False
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function KongCanBuy refactored with the following changes:

This removes the following comments ( why? ):

# print("for kong: " + kong.name + " with " + str(coins[kong]) + " coins")
# print("has price: " + str(price))
# print("KongCanBuy checking item: " + str(LocationList[location].item))

Comment on lines -81 to +88
for key in dict_data:
value = dict_data[key]
for key, value in dict_data.items():
# At this time, all strings represent ints, so just convert.
if type(value) == str:
value = int(value)
key_enum = SettingsStringEnum[key]
key_data_type = SettingsStringTypeMap[key_enum]
# Encode the key.
key_size = max([member.value for member in SettingsStringEnum]).bit_length()
key_size = max(member.value for member in SettingsStringEnum).bit_length()
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function encrypt_settings_string_enum refactored with the following changes:

This removes the following comments ( why? ):

# letters.
# Split the bitstring into 6-bit chunks and look up the corresponding

Comment on lines -156 to +152
key_size = max([member.value for member in SettingsStringEnum]).bit_length()
key_size = max(member.value for member in SettingsStringEnum).bit_length()
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function decrypt_settings_string_enum refactored with the following changes:

Comment thread randomizer/Settings.py
self.seed = str(self.seed) + self.__hash + str(json.dumps(form_data))
self.set_seed()
self.seed_hash = [random.randint(0, 9) for i in range(5)]
self.seed_hash = [random.randint(0, 9) for _ in range(5)]
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Settings.__init__ refactored with the following changes:

Comment thread randomizer/Settings.py
Comment on lines -183 to +188
randomlist = []
for min_percentage in self.troff_min:
randomlist.append(random.randint(round(self.troff_max * min_percentage), self.troff_max))
randomlist = [
random.randint(
round(self.troff_max * min_percentage), self.troff_max
)
for min_percentage in self.troff_min
]
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Settings.update_progression_totals refactored with the following changes:

Comment on lines -135 to +133
while len(backpool) > 0:
while backpool:
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ShuffleExitsInPool refactored with the following changes:

Comment on lines -235 to +237
js.postMessage("Entrance placement failed. Retrying. Tries: " + str(retries))
js.postMessage(f"Entrance placement failed. Retrying. Tries: {retries}")
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ExitShuffle refactored with the following changes:

Comment on lines -348 to +359
if settings.starting_kong == Kongs.tiny and settings.random_prices != RandomPrices.free:
japesOptions = list(levelIndexChoices.intersection({2, 3}))
else:
japesOptions = list(levelIndexChoices.intersection({1, 3}))
japesOptions = (
list(levelIndexChoices.intersection({2, 3}))
if settings.starting_kong == Kongs.tiny
and settings.random_prices != RandomPrices.free
else list(levelIndexChoices.intersection({1, 3}))
)
elif settings.starting_kong == Kongs.tiny and settings.random_prices != RandomPrices.free:
japesOptions = list(levelIndexChoices.intersection({2, 3, 4, 5}))
else:
# Tiny has no coins and no T&S access in Japes so it can't be first for her unless prices are free
if settings.starting_kong == Kongs.tiny and settings.random_prices != RandomPrices.free:
japesOptions = list(levelIndexChoices.intersection({2, 3, 4, 5}))
else:
japesOptions = list(levelIndexChoices.intersection({1, 2, 3, 4, 5}))
japesOptions = list(levelIndexChoices.intersection({1, 2, 3, 4, 5}))
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ShuffleLevelOrderForOneStartingKong refactored with the following changes:

This removes the following comments ( why? ):

# If Aztec is level 2 and start with chunky, one of Japes/Factory needs to be level 1-3 and other in level 3-5
# If Aztec is level 3, one of Japes/Factory needs to be in level 1-2 and other in level 1-5
# Tiny has no coins and no T&S access in Japes so it can't be first for her unless prices are free
# If Aztec is level 1 or 2, one of Japes/Factory needs to be in level 1-4 and other in level 1-5
# If Aztec is level 2 and don't start with diddy or chunky, one of Japes/Factory needs to be level 1 and other in level 3-5

Comment on lines -443 to +472
if kongsOwned == settings.starting_kongs_count:
# If reached Aztec without freeing anyone yet, specific combinations of kongs are needed to open those cages (if they have any occupants)
if newLevelOrder[level] == Levels.AngryAztec and (Locations.TinyKong in settings.kong_locations or Locations.LankyKong in settings.kong_locations):
# Assume we can free any locked kongs here
tinyAccessible = Locations.TinyKong in settings.kong_locations
lankyAccessible = Locations.LankyKong in settings.kong_locations
if (
kongsOwned == settings.starting_kongs_count
and newLevelOrder[level] == Levels.AngryAztec
and (
Locations.TinyKong in settings.kong_locations
or Locations.LankyKong in settings.kong_locations
)
):
# Assume we can free any locked kongs here
tinyAccessible = Locations.TinyKong in settings.kong_locations
lankyAccessible = Locations.LankyKong in settings.kong_locations
# If a kong is in Tiny Temple, either Diddy or Chunky can free them
if tinyAccessible:
if Kongs.diddy not in settings.starting_kong_list and Kongs.chunky not in settings.starting_kong_list:
tinyAccessible = False
# If a kong is in Llama temple, need to be able to get past the guitar door and one of Donkey, Lanky, or Tiny to open the Llama temple
if lankyAccessible:
guitarDoorAccess = (
Kongs.diddy in settings.starting_kong_list
or settings.open_levels
or (Kongs.donkey in settings.starting_kong_list and settings.activate_all_bananaports == ActivateAllBananaports.all)
)
if not guitarDoorAccess or (
Kongs.donkey not in settings.starting_kong_list and Kongs.lanky not in settings.starting_kong_list and Kongs.tiny not in settings.starting_kong_list
):
lankyAccessible = False
# If we can unlock one kong then we can unlock both, so if we can't reach either then we can't assume we can unlock any kong from here
if not tinyAccessible and not lankyAccessible:
break
if (
tinyAccessible
and Kongs.diddy not in settings.starting_kong_list
and Kongs.chunky not in settings.starting_kong_list
):
tinyAccessible = False
# If a kong is in Llama temple, need to be able to get past the guitar door and one of Donkey, Lanky, or Tiny to open the Llama temple
if lankyAccessible:
guitarDoorAccess = (
Kongs.diddy in settings.starting_kong_list
or settings.open_levels
or (Kongs.donkey in settings.starting_kong_list and settings.activate_all_bananaports == ActivateAllBananaports.all)
)
if not guitarDoorAccess or (
Kongs.donkey not in settings.starting_kong_list and Kongs.lanky not in settings.starting_kong_list and Kongs.tiny not in settings.starting_kong_list
):
lankyAccessible = False
# If we can unlock one kong then we can unlock both, so if we can't reach either then we can't assume we can unlock any kong from here
if not tinyAccessible and not lankyAccessible:
break
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ShuffleLevelOrderForMultipleStartingKongs refactored with the following changes:

This removes the following comments ( why? ):

# If reached Aztec without freeing anyone yet, specific combinations of kongs are needed to open those cages (if they have any occupants)

Comment on lines -40 to +62
level_to_enum = {
Levels.DKIsles: randomizer.LogicFiles.DKIsles.LogicRegions,
Levels.JungleJapes: randomizer.LogicFiles.JungleJapes.LogicRegions,
Levels.AngryAztec: randomizer.LogicFiles.AngryAztec.LogicRegions,
Levels.FranticFactory: randomizer.LogicFiles.FranticFactory.LogicRegions,
Levels.GloomyGalleon: randomizer.LogicFiles.GloomyGalleon.LogicRegions,
Levels.FungiForest: randomizer.LogicFiles.FungiForest.LogicRegions,
Levels.CrystalCaves: randomizer.LogicFiles.CrystalCaves.LogicRegions,
Levels.CreepyCastle: randomizer.LogicFiles.CreepyCastle.LogicRegions,
Levels.HideoutHelm: randomizer.LogicFiles.HideoutHelm.LogicRegions,
}
level_to_name = {
Levels.DKIsles: "Isles",
Levels.JungleJapes: "Japes",
Levels.AngryAztec: "Aztec",
Levels.FranticFactory: "Factory",
Levels.GloomyGalleon: "Galleon",
Levels.FungiForest: "Forest",
Levels.CrystalCaves: "Caves",
Levels.CreepyCastle: "Castle",
Levels.HideoutHelm: "Helm",
}
if spoiler.settings.random_fairies:
level_to_enum = {
Levels.DKIsles: randomizer.LogicFiles.DKIsles.LogicRegions,
Levels.JungleJapes: randomizer.LogicFiles.JungleJapes.LogicRegions,
Levels.AngryAztec: randomizer.LogicFiles.AngryAztec.LogicRegions,
Levels.FranticFactory: randomizer.LogicFiles.FranticFactory.LogicRegions,
Levels.GloomyGalleon: randomizer.LogicFiles.GloomyGalleon.LogicRegions,
Levels.FungiForest: randomizer.LogicFiles.FungiForest.LogicRegions,
Levels.CrystalCaves: randomizer.LogicFiles.CrystalCaves.LogicRegions,
Levels.CreepyCastle: randomizer.LogicFiles.CreepyCastle.LogicRegions,
Levels.HideoutHelm: randomizer.LogicFiles.HideoutHelm.LogicRegions,
}
level_to_name = {
Levels.DKIsles: "Isles",
Levels.JungleJapes: "Japes",
Levels.AngryAztec: "Aztec",
Levels.FranticFactory: "Factory",
Levels.GloomyGalleon: "Galleon",
Levels.FungiForest: "Forest",
Levels.CrystalCaves: "Caves",
Levels.CreepyCastle: "Castle",
Levels.HideoutHelm: "Helm",
}
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ShuffleFairyLocations refactored with the following changes:

  • Move assignments closer to their usage [×2] (move-assign)
  • Swap if/else branches of if expression to remove negation [×2] (swap-if-expression)

# Other levels are 0-6 but Helm is 7, DK Isles is 8, and I'm too scared to change it so it's accounted for here
if levelOffset > 7:
levelOffset = 7
levelOffset = min(levelOffset, 7)
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GetBlueprintItemForKongAndLevel refactored with the following changes:

Comment on lines -93 to +92
if levelOffset > 7:
levelOffset = 7
levelOffset = min(levelOffset, 7)
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GetBlueprintLocationForKongAndLevel refactored with the following changes:

Comment on lines -114 to +116
available_for_kong = []
# Pick a random unselected kasplat from available ones for this kong
for kasplat in kasplats:
if not kasplat.selected and kong in kasplat.kong_lst:
available_for_kong.append(kasplat.name)
available_for_kong = [
kasplat.name
for kasplat in kasplats
if not kasplat.selected and kong in kasplat.kong_lst
]
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ShuffleKasplatsAndLocations refactored with the following changes:

This removes the following comments ( why? ):

# Pick a random unselected kasplat from available ones for this kong

Comment on lines -184 to +183
# Make sure only 1 of each kasplat per level, set up array to track that
level_kongs = []
kongs = GetKongs()
# Add a list of kongs for each level
# Excludes Shops level, but will include a useless Helm level
for i in range(len(Levels) - 1):
level_kongs.append(kongs.copy())
level_kongs = [kongs.copy() for _ in range(len(Levels) - 1)]
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ShuffleKasplats refactored with the following changes:

This removes the following comments ( why? ):

# Add a list of kongs for each level
# Excludes Shops level, but will include a useless Helm level
# Make sure only 1 of each kasplat per level, set up array to track that

Comment on lines -224 to +242
if spoiler.settings.kasplat_rando:
retries = 0
while True:
try:
# Shuffle kasplats
if spoiler.settings.kasplat_location_rando:
ShuffleKasplatsAndLocations(spoiler, LogicVariables)
else:
ShuffleKasplatsInVanillaLocations(spoiler, LogicVariables)
# Verify world by assuring all locations are still reachable
Fill.Reset()
if not Fill.VerifyWorld(spoiler.settings):
raise Ex.KasplatPlacementException
return
except Ex.KasplatPlacementException:
if retries == 10:
# This is the first VerifyWorld check, and serves as the canary in the coal mine
# If we get to this point in the code, the world itself is likely unstable from some combination of settings or bugs
js.postMessage("Settings combination is likely unstable.")
raise Ex.KasplatAttemptCountExceeded
retries += 1
js.postMessage("Kasplat placement failed. Retrying. Tries: " + str(retries))
# We've added logic in kasplat location rando, now we need to remove it
if spoiler.settings.kasplat_location_rando:
ResetShuffledKasplatLocations()
if not spoiler.settings.kasplat_rando:
return
retries = 0
while True:
try:
# Shuffle kasplats
if spoiler.settings.kasplat_location_rando:
ShuffleKasplatsAndLocations(spoiler, LogicVariables)
else:
ShuffleKasplatsInVanillaLocations(spoiler, LogicVariables)
# Verify world by assuring all locations are still reachable
Fill.Reset()
if not Fill.VerifyWorld(spoiler.settings):
raise Ex.KasplatPlacementException
return
except Ex.KasplatPlacementException:
if retries == 10:
# This is the first VerifyWorld check, and serves as the canary in the coal mine
# If we get to this point in the code, the world itself is likely unstable from some combination of settings or bugs
js.postMessage("Settings combination is likely unstable.")
raise Ex.KasplatAttemptCountExceeded
retries += 1
js.postMessage(f"Kasplat placement failed. Retrying. Tries: {retries}")
# We've added logic in kasplat location rando, now we need to remove it
if spoiler.settings.kasplat_location_rando:
ResetShuffledKasplatLocations()
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function KasplatShuffle refactored with the following changes:

self.logic = lambda l: True
else:
self.logic = logic
self.logic = (lambda l: True) if logic is None else logic
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BananaCoinGroup.__init__ refactored with the following changes:

self.logic = lambda l: True
else:
self.logic = logic
self.logic = (lambda l: True) if logic is None else logic
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CrownLocation.__init__ refactored with the following changes:

self.logic = lambda l: True
else:
self.logic = logic
self.logic = (lambda l: True) if logic is None else logic
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DoorData.__init__ refactored with the following changes:

Comment on lines -195 to +199
EnemySelector = []
for enemyEnum, enemy in EnemyMetaData.items():
if enemy.selector_enabled:
EnemySelector.append({"name": enemy.name, "value": enemyEnum.name, "tooltip": ""})
EnemySelector = [
{"name": enemy.name, "value": enemyEnum.name, "tooltip": ""}
for enemyEnum, enemy in EnemyMetaData.items()
if enemy.selector_enabled
]
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 195-198 refactored with the following changes:

Comment thread randomizer/Lists/Item.py
Items.BananaHoard: Item("Banana Hoard", True, Types.Constant, Kongs.any),
}

HHItemSelector = []
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 253-272 refactored with the following changes:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants