8000 Fix UnboundLocalError in on_pushButton_clicked when no last arena found · Issue #18 · turkishviking/Python-Robocode · GitHub
[go: up one dir, main page]

Skip to content

Fix UnboundLocalError in on_pushButton_clicked when no last arena found #18

@jackbelmore

Description

@jackbelmore

Description

There's an UnboundLocalError in GUI/window.py when trying to start the last battle without a previously saved arena.

Error

UnboundLocalError: cannot access local variable 'dico' where it is not associated with a value

Root Cause

In the on_pushButton_clicked method (lines 50-64), the code tries to use the dico variable outside the if block where it's defined. When the /.datas/lastArena file doesn't exist, dico is never created, but the code still tries to access dico["botList"] on line 63.

Current Code (Problematic)

if os.path.exists(os.getcwd() + "/.datas/lastArena"):
    with open(os.getcwd() + "/.datas/lastArena",  'rb') as file:
        unpickler = pickle.Unpickler(file)
        dico = unpickler.load()
    file.close()
else:
    print("No last arena found.")

# This line fails when dico doesn't exist
botList = [self.reimport_class(bot) for bot in dico["botList"]]

Proposed Fix

Move the battle setup code inside the if block so it only executes when the arena file exists:

arena_path = os.path.join(os.getcwd(), ".datas", "lastArena")
if os.path.exists(arena_path):
    with open(arena_path, 'rb') as file:
        unpickler = pickle.Unpickler(file)
        dico = unpickler.load()
    botList = [self.reimport_class(bot) for bot in dico["botList"]]
    self.setUpBattle(dico["width"], dico["height"], botList)
else:
    print("No last arena found.")

Additional Improvements

  • Use os.path.join() instead of string concatenation for better cross-platform path handling
  • Remove redundant file.close() call (the with statement handles it automatically)
  • Store the path in a variable to reduce duplication

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0