From ad6cf68969c0564d2f984cea24ceb1e1dbc90c00 Mon Sep 17 00:00:00 2001 From: magical Date: Sun, 4 Feb 2024 10:21:28 -0800 Subject: [PATCH] close files properly after patching --- Randomizer.py | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/Randomizer.py b/Randomizer.py index 9bddd3c..ba5c1ef 100644 --- a/Randomizer.py +++ b/Randomizer.py @@ -2616,20 +2616,22 @@ def patch_game(): os.system('.\\armips\\armips.exe "Metroid Fusion Open Randomizer.asm" -root ".\\data\\asm" -sym ".\\temp.sym"') os.replace('.\\data\\MFOR.gba', '.\\seeds\\{}.gba'.format(FileName)) else: - source = open(BaseGame, 'rb') - target = open(os.path.join('.', 'seeds', '{}.gba'.format(FileName)), 'wb') - patch = open(os.path.join('.', 'data', 'MFOR.bps'), 'rb') - try: - apply_to_files(patch, source, target) - except: - target.close() - os.unlink(os.path.join('.', 'seeds', '{}.gba'.format(FileName))) - print('Error: failed to patch game with base patch!') - sys.exit(1) - + error = False + with open(BaseGame, 'rb') as source: + with open(os.path.join('.', 'seeds', '{}.gba'.format(FileName)), 'wb') as target: + with open(os.path.join('.', 'data', 'MFOR.bps'), 'rb') as patch: + try: + apply_to_files(patch, source, target) + except Exception: + error = True + if error: + os.remove(os.path.join('.', 'seeds', '{}.gba'.format(FileName))) + print('Error: failed to patch game with base patch!') + sys.exit(1) + checksum = fileHash(os.path.join('.', 'seeds', '{}.gba'.format(FileName))) if checksum != 2455114263: - os.unlink(os.path.join('.', 'seeds', '{}.gba'.format(FileName))) + os.remove(os.path.join('.', 'seeds', '{}.gba'.format(FileName))) print('Error: Base patch file has been modified. Please go to https://metroidconstruction.com/ and re-download MFOR.') sys.exit(1) @@ -2864,14 +2866,14 @@ def patch_game(): sourcedata = source.read() with open(os.path.join('.', 'seeds', '{}.gba'.format(FileName)), 'rb') as target: targetdata = target.read() - - patch = open(os.path.join('.', 'seeds', '{}.bps'.format(FileName)), 'wb') - + blocksize = (len(sourcedata) + len(targetdata)) // 1000000 + 1 print("Using blocks of {0} bytes".format(blocksize)) iterable = diff_bytearrays(blocksize, sourcedata, targetdata) - write_bps(bps_progress(iterable), patch) + with open(os.path.join('.', 'seeds', '{}.bps'.format(FileName)), 'wb') as patch: + write_bps(bps_progress(iterable), patch) + print('') ItemNames = [ @@ -3074,7 +3076,7 @@ def start_randomizer(rom, settings): print('Debug generation enabled') if loop > 0: SeedValue = str(random.randrange(sys.maxsize)) - + Difficulty = SeedSettings['Difficulty'] DamageRuns = SeedSettings['DamageRuns'] random.seed(SeedValue + str(SeedSettings))