Crash while running dialog box from recipe

Started by zo3xiaJonWeinberg

zo3xiaJonWeinberg Lv 1

I'm editing a recipe to try to make the cancel and X button work even after clicking More Options and going back to Main settings. I think I finally got it to work as I can't reproduce the bug but when I finally fixed the code, I clicked More then Return then X or Cancel and Foldit crashed on Aflatoxin 1902. I'll copy the log and my recipe:

log:
args passed:
'/Applications/Foldit.app/Contents/MacOS/Foldit'
args used:
'/Applications/Foldit.app/Contents/MacOS/Foldit'
'-resources'
'cmp-resources-214153bebec0533121c44416c1fa1d1b/resources'
'-database'
'cmp-database-428fc0948d0f404d685c4e477f984796/database'
'-interactive_game'
'novice'
'-boinc_url'
'https://fold.it'
'-interactive:interactive_residue_types'
'-ignore_unrecognized_res'
'-out:level'
'200'
'-out:no_color'
'-load_PDB_components'
'false'
We're loading in the hotkeys
We loaded in the hotkeys
starting the init thread!..
boinc base url: https://fold.it
checking updates…
binary
local: '6528c4834803a83cdb017d9b405e109c'
remote: '6528c4834803a83cdb017d9b405e109c'
database
local: '428fc0948d0f404d685c4e477f984796'
remote: '428fc0948d0f404d685c4e477f984796'
resources
local: '214153bebec0533121c44416c1fa1d1b'
remote: '214153bebec0533121c44416c1fa1d1b'
cleaning up old components:
binary 6528c4834803a83cdb017d9b405e109c
database 428fc0948d0f404d685c4e477f984796
resources 214153bebec0533121c44416c1fa1d1b
binary 00000000000000000000000000000000
resources 00000000000000000000000000000000
REPORTING CRASH: 769520
SoundTheme::load: cmp-resources-214153bebec0533121c44416c1fa1d1b/resources/sounds/organic_01
loading: cmp-resources-214153bebec0533121c44416c1fa1d1b/resources/sounds/organic_01/rotamer_land_00.ogg
loading: cmp-resources-214153bebec0533121c44416c1fa1d1b/resources/sounds/organic_01/rotamer_land_01.ogg
loading: cmp-resources-214153bebec0533121c44416c1fa1d1b/resources/sounds/organic_01/rotamer_land_02.ogg
loading: cmp-resources-214153bebec0533121c44416c1fa1d1b/resources/sounds/organic_01/rotamer_land_03.ogg
loading: cmp-resources-214153bebec0533121c44416c1fa1d1b/resources/sounds/organic_01/rotamer_land_04.ogg
loading: cmp-resources-214153bebec0533121c44416c1fa1d1b/resources/sounds/organic_01/rotamer_land_05.ogg
(@init_machine_log)intro_level_version_ is 0
SVM classifier successfully loaded
Feature list successfully loaded
Valid classifier feature list
buildid: 20200921-459a3ae845-macos_x64
Duplicate hotkey action UNDO_UNDO (, Undo)
Duplicate hotkey action UNDO_REDO (, Redo)
Duplicate hotkey action UNDO_RESTORE_BEST (, Restore Very Best)
about to create view_options_button_
setting side chain mode to: 2 Show All (Slow)
Found remote enable option: 0
Show splash!
Playing: sounds/organic_01/splashscreen.ogg
Converting any old-style quicksaves and autosaves…
Sending SOPs:

Sending SOPs:

About to show the puzzle screen…
Trying to get the puzzle list…
Loading cache…
Parsing puzzle URL…
Parsing contests…
Parsing macros…
Saving the cache…
JM level version = 0
Using file: cmp-resources-214153bebec0533121c44416c1fa1d1b/resources/levels/endless_puzzles.intros
Using file: cmp-resources-214153bebec0533121c44416c1fa1d1b/resources/levels/puzzles_branching_ordered.intros
Parsing level completion…
Sending SOPs:

Initting the list…
Got the puzzles…
Sending SOPs:

Finished show_puzzle_screen…
Sending SOPs:

has key .owts
has key .opdb
core.conformation.Conformation: [ WARNING ] missing heavyatom: OXT on residue ARG:CtermProteinFull 178
has key .opuzzle_setup
has key .ocnstr
starting score : 55.3207
puzzle loaded
Autosave puzzles/0002010541/0000769520/default/autosave.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-best.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-recentbest.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-creditbest.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave2.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave3.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave5.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave6.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave91.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave98.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-best-improver.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-recentbest-improver.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-creditbest-improver.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave-improver.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave2-improver.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave3-improver.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave4-improver.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave5-improver.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave6-improver.ir_solution loaded.
Quicksave puzzles/0002010541/0000769520/default/quicksave98-improver.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-best-improver.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-recentbest-improver.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-creditbest-improver.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-best-improver.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-recentbest-improver.ir_solution loaded.
Autosave puzzles/0002010541/0000769520/default/autosave-creditbest-improver.ir_solution loaded.
building library…done.
ScorePanel new session
clear density…
GROUP CHAT CHANNEL: GoScience
BOINC says connect to: irc.fold.it:6667
Using nick: zo3xiaJonWeinberg
SRVR_THRD getting notifications…
Initting IRC mappings…
Error: not connected to IRC when init happened.
Ended Initialization of GameApplication
Entering IRC::run
Sending SOPs:

Notice : This nickname is registered and protected. If it is your Notice : nick, type /msg NickServ IDENTIFY password. Otherwise, Notice : please choose a different nick. Notice : Password accepted - you are now recognized. IDENTIFIED Sending message to FolditIRCBot: infoplz #global Sending message to FolditIRCBot: infoplz #veteran Initting IRC mappings... Sending SOPs:

Sending SOPs:

Sending SOPs:

Sending SOPs:

Sending SOPs:

Sending SOPs:

SRVR_THRD getting notifications…
Sending message to FolditIRCBot: afk

recipe:

function printTimeAndScore(startTime, scoreGain, currentStateString)
local ss = (os.time() - startTime) % 60
local mm = (((os.time() - startTime - ss) % 3600) / 60)
local hh = (os.time() - startTime - mm*60 - ss) / 3600
print("Time: " .. string.format("%02d", hh) .. ":" .. string.format("%02d", mm) .. ":" .. string.format("%02d", ss) .. ". " .. currentStateString .. " Score: " .. current.GetEnergyScore() .. ", Total: +" .. scoreGain)
end

function initializeActions()
performAction = {}
actionDescription = {}

performAction[0] = function()
    structure.WiggleAll(1) --jon reduced
end
actionDescription[0] = "Wiggle(1)"

performAction[1] = function()
    local ss=math.random(1,structure.GetCount()-3)
    selection.SelectRange(ss,ss+3)
    structure.MutateSidechainsSelected(1) --All(1)
end
actionDescription[1] = "Mutate(1)"

performAction[2] = function()
    local startSegmentNumber = math.random(1, structure.GetCount() - 9)
    local endSegmentNumber = math.random(startSegmentNumber + 8, structure.GetCount())
    band.AddBetweenSegments(startSegmentNumber, endSegmentNumber)
    band.SetStrength(1, 10)
    band.SetGoalLength(1, structure.GetDistance(startSegmentNumber, endSegmentNumber) * 0.9)
end
actionDescription[2] = "Add random band"

performAction[3] = function()
    band.DeleteAll()
end
actionDescription[3] = "Delete all bands"

performAction[4] = function()
    recentbest.Restore()
end
actionDescription[4] = "Restore recent best"

performAction[5] = function()
    local startSegmentNumber = math.random(1,structure.GetCount() - 3)
    selection.DeselectAll()
    selection.SelectRange(startSegmentNumber, startSegmentNumber + 3)
    structure.RebuildSelected(1) --jon halved for fairness with fast actions
    selection.DeselectAll()
end
actionDescription[5] = "Rebuild random segment"

performAction[6] = function()
    behavior.SetClashImportance(1)
end
actionDescription[6] = "Set clash importance to 1"

performAction[7] = function()
    behavior.SetClashImportance(0.5)
end
actionDescription[7] = "Set clash importance to 0.5"

performAction[8] = function()
    behavior.SetClashImportance(0.02)
end
actionDescription[8] = "Set clash importance to 0.02"

performAction[9] = function()
    local startSegmentNumber = math.random(1, structure.GetCount() - 3)
    selection.DeselectAll()
    selection.SelectRange(startSegmentNumber, startSegmentNumber + 3)
    structure.IdealizeSelected()
    selection.DeselectAll()
end
actionDescription[9] = "Idealize random segment"

performAction[10] = function()
    local lengthOfSegment = math.random(1, 3)
    local segmentInformation = {}
    local workSegmentNumber = math.random(1, 3)
    local function sortSegments(segmentInformation)
        for i = 1, #segmentInformation - 1 do
            for j = i + 1, #segmentInformation do
                if segmentInformation[i][3] > segmentInformation[j][3] then
                    segmentInformation[i], segmentInformation[j] = segmentInformation[j], segmentInformation[i]
                end
            end
        end
        return segmentInformation
    end

    for i = 1, structure.GetCount() - lengthOfSegment + 1 do
        segmentInformation[i] = {i, i + lengthOfSegment - 1, current.GetSegmentEnergyScore(i) }
        for j = 2, lengthOfSegment do
            segmentInformation[i][3] = segmentInformation[i][3] + current.GetSegmentEnergyScore(i + j - 1)
        end
    end
    segmentInformation = sortSegments(segmentInformation)

    selection.DeselectAll()
    selection.SelectRange(math.max(segmentInformation[workSegmentNumber][1] - 1, 1), math.min(segmentInformation[workSegmentNumber][2] + 1, structure.GetCount()))
    structure.RebuildSelected(1) --jon halved
    selection.DeselectAll()
end
actionDescription[10] = "Rebuild worst segment"

performAction[11]=function()
    behavior.SetFiltersDisabled(true)
end
actionDescription[11]="disable filters"

performAction[12]=function()
    behavior.SetFiltersDisabled(false)
end
actionDescription[12]="enable filters"

performAction[13]=function()
    --Bands in Space
    local s1=math.random(structure.GetCount())
    local str=math.random(0.1,1)
        local len=math.random(20)
        local theta = math.acos(math.random()) --jon: arccosine
        local phi = 2 * math.pi * math.random()
        local segmentXAxis=0
        local segmentYAxis=0
        while true do --all 3 must be different
            segmentXAxis = math.random(structure.GetCount())--segCnt) --jon
            segmentYAxis = math.random(structure.GetCount())--segCnt) --jon
            if segmentXAxis~=s1 and segmentYAxis~=s1 and segmentXAxis~=segmentYAxis then break end
        end
        --{segmentOrigin, segmentXAxis, segmentYAxis, rho, theta, phi}
        band.Add(s1, segmentXAxis, segmentYAxis, len, theta, phi, str)
       --bands.AddBand(b)
     --puzzle.StartOver()
    
end
actionDescription[13]="band in space"

performAction[14]=function()
    selection.SelectAll()
    structure.SetSecondaryStructureSelected("a") --auto
    selection.DeselectAll()
end
actionDescription[14]="auto secondary structure. won't affect score in this script, just human readability and maybe info for other scripts"

performAction[15]=function()
    --    Set segments secondary structure. Valid values are e=sheet, h=helix, l=loop, m=molecule, a=auto. 
    local struct={[1]="e",[2]="h",[3]="l",[4]="m"}
    structure.SetSecondaryStructure(math.random(1,structure.GetCount()), struct[math.random(1,#struct)])
end
actionDescription[15]="random secondary structure. won't affect score, etc. but Ai doesn't know that."

local foo={}
table.insert(foo,"fortune")
print("foo[1] "..foo[1])
print("debugging: at this code step #performAction is currently "..#performAction)
performAction[#performAction+1]=function() -- +1]=function()
    puzzle.StartOver()
end
actionDescription[#actionDescription+1]="reset puzzle. may be necessary for multi-start puzzles. doesn't exit evolver mode like manual reset does. "

--insert new actions above this line before counting them --jon

NumberOfActions=#performAction+1 --jon
print("NumberOfActions is now "..NumberOfActions) end

function addHashToAlgorithm(algorithm)
algorithm.Hash = ""
for i = 1, #algorithm do
if algorithm[i] >= 10 then
algorithm.Hash = algorithm.Hash .. string.char(HashStartCharacterCode + algorithm[i] + HashShift)
else
algorithm.Hash = algorithm.Hash .. string.char(HashStartCharacterCode + algorithm[i])
end
end
end

function addAlgorithmBasedOnHash(algorithm)
for i = 1, string.len(algorithm.Hash) do
algorithm[i] = string.byte(algorithm.Hash, i) - HashStartCharacterCode
if algorithm[i] > 10 then – NumberOfActions then –jon 10 -> Num ?
algorithm[i] = algorithm[i] - HashShift
end
end
end

function createRandomAlgorithm(algorithm)
initializeAlgorithm(algorithm)
for i = 1, NumberOfAlgorithmSteps do
algorithm[i] = math.random(0, NumberOfActions - 1)
end
optimizeAlgorithm(algorithm)
end

function testAlgorithm(algorithm)
print("algorithm.Hash: ")
print(algorithm.Hash)
–resetPuzzle() –jon
peak=recentbest.GetEnergyScore()
algorithm.Score[0] = current.GetEnergyScore()
algorithm.GainScore[0] = 999999
local iteration = 1

--while algorithm.GainScore[iteration - 1] >= IterationScoreThreshold do

    local iterationStartScore = current.GetEnergyScore()
    print("Iteration: "..string.format(iteration)..". Start. ") --zw

    for i = 1, #algorithm do
        performAction[algorithm[i]]()
        --print("Step: " ..i..". Action: "..algorithm[i]..". Score: "..current.GetEnergyScore())
    end

    --recentbest.Restore() --jon
    algorithm.Score[iteration] = current.GetEnergyScore() --jon
    algorithm.GainScore[iteration] = algorithm.Score[iteration] - iterationStartScore
    print("Iteration: "..iteration..". End. Score: "..algorithm.Score[iteration]) --jon uncomm
    printTimeAndScore(startTime, algorithm.Score[iteration] - algorithm.Score[0], algorithm.CurrentStateString .. " Iteration " .. string.format("%02d", iteration) .. ".")

    iteration = iteration + 1

--end --zwJon

algorithm.Score[iteration]=recentbest.GetEnergyScore()-peak --jon 

updateBestPosition() end

function initializeAlgorithm(algorithm)
algorithm.Score = {}
algorithm.GainScore = {}
algorithm.Hash = ""
algorithm.CurrentStateString = ""
end

function copyAlgorithm(algorithm)
local newAlgorithm = {}
initializeAlgorithm(newAlgorithm)
for i = 1, #algorithm do
newAlgorithm[i] = algorithm[i]
end
newAlgorithm.Hash = algorithm.Hash
return newAlgorithm
end

function mutateAlgorithm(algorithm)
for i = 1, #algorithm do
if math.random(0, 1) <= MutateRate then
algorithm[i] = math.random(0, NumberOfActions - 1)
end
end
optimizeAlgorithm(algorithm)
end

function createCrossAlgorithm(algorithmFirst, algorithmSecond)
local algorithmFirstHash = algorithmFirst.Hash
for i = 1, #algorithmFirst do
if math.random(0, 1) <= 0.5 then
algorithmFirst[i] = algorithmSecond[i]
end
end
optimizeAlgorithm(algorithmFirst)
if algorithmFirstHash == algorithmFirst.Hash or algorithmFirst.Hash == algorithmSecond.Hash then
print("Crossing " .. algorithmFirst.Hash .. " changed to Mutation")
mutateAlgorithm(algorithmFirst)
end
end

function sortPopulation(population)
for i = 1, #population - 1 do
for j = i + 1, #population do
if population[i].Score[#population[i].Score] < population[j].Score[#population[j].Score] then
population[i], population[j] = population[j], population[i]
end
end
end
end

function printPopulation(population)
for i = 1, #population do
print(string.format("%4s", i) .. ", " .. population[i].Hash .. ", score: " .. population[i].Score[#population[i].Score]..", gain: ".. population[i].GainScore[#population[i].GainScore]) –jon
if i == PopulationSize then
print("————————————————–")
end
end
end

function truncate(algorithm) –zo3xia reorganized
for i = NumberOfAlgorithmSteps + 1, #algorithm do
algorithm[i] = nil
end
end

function optimizeAlgorithm(algorithm)
for i = #algorithm + 1, NumberOfAlgorithmSteps do
algorithm[i] = math.random(0, NumberOfActions - 1)
end
truncate(algorithm)
local actionNumber = 1
while actionNumber <= #algorithm do
if actionNumber == 1 and algorithm[actionNumber] == 4 then – Delete first if recentbest.Restore()
deleteAction(algorithm, actionNumber)
elseif actionNumber > 1 and algorithm[actionNumber] == algorithm[actionNumber - 1] and algorithm[actionNumber] == 1 then – Delete if second in a row structure.ShakeSidechainsAll(1)
deleteAction(algorithm, actionNumber)
elseif actionNumber > 1 and algorithm[actionNumber] == algorithm[actionNumber - 1] and algorithm[actionNumber] == 3 then – Delete if second in a row band.DeleteAll()
deleteAction(algorithm, actionNumber)
elseif actionNumber > 1 and algorithm[actionNumber] == algorithm[actionNumber - 1] and algorithm[actionNumber] == 4 then – Delete if second in a row recentbest.Restore()
deleteAction(algorithm, actionNumber)
elseif actionNumber > 1 and algorithm[actionNumber] == 3 and algorithm[actionNumber - 1] == 2 then – Delete if second in a row recentbest.Restore()
deleteAction(algorithm, actionNumber)
elseif actionNumber == #algorithm and algorithm[actionNumber] == 4 then – Delete last if recentbest.Restore()
deleteAction(algorithm, actionNumber)
elseif actionNumber == #algorithm and algorithm[actionNumber] == 2 then – Delete last if it is add band.
deleteAction(algorithm, actionNumber)
elseif actionNumber == #algorithm and algorithm[actionNumber] == 6 then – Delete last if change of clashing importance
deleteAction(algorithm, actionNumber)
elseif actionNumber == #algorithm and algorithm[actionNumber] == 7 then – Delete last if change of clashing importance
deleteAction(algorithm, actionNumber)
elseif actionNumber == #algorithm and algorithm[actionNumber] == 8 then – Delete last if change of clashing importance
deleteAction(algorithm, actionNumber)
elseif actionNumber > 1 and algorithm[actionNumber] == 6 and (algorithm[actionNumber - 1] == 7 or algorithm[actionNumber - 1] == 8) then – Delete if second in a row change of clashing importance
deleteAction(algorithm, actionNumber)
elseif actionNumber > 1 and algorithm[actionNumber] == 7 and (algorithm[actionNumber - 1] == 6 or algorithm[actionNumber - 1] == 8) then – Delete if second in a row change of clashing importance
deleteAction(algorithm, actionNumber)
elseif actionNumber > 1 and algorithm[actionNumber] == 8 and (algorithm[actionNumber - 1] == 6 or algorithm[actionNumber - 1] == 7) then – Delete if second in a row change of clashing importance
deleteAction(algorithm, actionNumber)
else actionNumber = actionNumber + 1
end
end
addHashToAlgorithm(algorithm)
end

function deleteAction(algorithm, actionNumber)
for i = actionNumber, #algorithm - 1 do
algorithm[i] = algorithm[i + 1]
end
algorithm[#algorithm] = math.random(0, NumberOfActions - 1)
end

function updateBestPosition()
if current.GetEnergyScore() > bestScore then
bestScore = current.GetEnergyScore()
save.Quicksave(2)
end
end

function resetPuzzle()
save.Quickload(1)
recentbest.Save()
behavior.SetClashImportance(1)
end

function printMainInformation()
print("PopulationSize: " .. PopulationSize)
print("MutationSize: " .. MutationSize)
print("AliensSize: " .. AliensSize)
print("CrossSize: " .. CrossSize)
print("NumberOfAlgorithmSteps: " .. NumberOfAlgorithmSteps)
print("IterationScoreThreshold: " .. IterationScoreThreshold)
print("ResetWorldGeneration: " .. ResetWorldGeneration)
print("MutateRate: " .. MutateRate)
print("StartScore: " .. current.GetEnergyScore())
print("———————————-")
print("Actions used:")
for i = 0, #performAction do
if i >= 10 then
print(string.char(HashStartCharacterCode + i + HashShift) .. ": " .. actionDescription[i])
else
print(string.char(HashStartCharacterCode + i) .. ": " .. actionDescription[i])
end
end
print("———————————-")
end

function cleanAlgorithmHash(algorithmHash)
local cleanedAlgorithmHash = ""
for i = 1, string.len(algorithmHash) do
if string.byte(algorithmHash, i) >= HashStartCharacterCode and string.byte(algorithmHash, i) <= HashStartCharacterCode + 10 then – 10 then –jon
cleanedAlgorithmHash = cleanedAlgorithmHash .. string.sub(algorithmHash, i, i)
end
–code 48 = 0
–HashStartCharcterCode=48
–HashStartCharacterCode+17=65
–code 65 is A
–jon
if string.byte(algorithmHash, i) >= HashStartCharacterCode + 17 and string.byte(algorithmHash, i) <= HashStartCharacterCode + 17 + NumberOfActions-10-1 then –jon –1 because Action 0 included
cleanedAlgorithmHash = cleanedAlgorithmHash .. string.sub(algorithmHash, i, i)
end
end
return cleanedAlgorithmHash
end

function showMoreDialog()
local moreDialog = dialog.CreateDialog("Additional options.")
moreDialog.Label = dialog.AddLabel("Include pre-defined algorithms:")
moreDialog.AddAlgorithm1 = dialog.AddCheckbox("51042031048016049104", true)
moreDialog.AddAlgorithm2 = dialog.AddCheckbox("91042031047016045104", true)
moreDialog.LabelCustomAlgorithm = dialog.AddLabel("Include custom algorithm:")
moreDialog.CustomHash = dialog.AddTextbox("", "")
moreDialog.OK = dialog.AddButton("Return", 1)

local moreDialogResult = dialog.Show(moreDialog)
if (moreDialogResult == 1) then
    InitialAlgorithm[1] = moreDialog.AddAlgorithm1.value
    InitialAlgorithm[2] = moreDialog.AddAlgorithm2.value
    if string.len(moreDialog.CustomHash.value) > 0 then
        CustomAlgorithmHash = cleanAlgorithmHash(moreDialog.CustomHash.value)
        print("custom: "..CustomAlgorithmHash)
        if string.len(CustomAlgorithmHash) > 0 then
            InitialAlgorithm[3] = true
        end
    end
    showMainDialog()
end end --jon reoranized to avoid recursion with 2 functions calling each other

– table dialog.AddSlider(string label, number value, number minimum, number maximum, number precision by tenths)
function showMainDialog()
local mainDialog = dialog.CreateDialog("AI Learns to play FoldIt.")
repeat –GAB loop for GUI copied by jon
mainDialog.PopulationSize = dialog.AddSlider("Population Size:", PopulationSize, 3, 200, 0)
mainDialog.MutationSize = dialog.AddSlider("Mutation Size:", MutationSize, 0, 200, 0)
mainDialog.AliensSize = dialog.AddSlider("Aliens Size:", AliensSize, 0, 200, 0)
mainDialog.CrossSize = dialog.AddSlider("Cross Size:", CrossSize, 0, 200, 0)
mainDialog.LabelNumberOfAlgorithmSteps = dialog.AddLabel("Number Of Algorithm Steps:")
mainDialog.NumberOfAlgorithmSteps = dialog.AddSlider("", NumberOfAlgorithmSteps, 5, 200, 0)
mainDialog.LabelIterationScoreThreshold = dialog.AddLabel("Iteration Score Threshold:")
mainDialog.IterationScoreThreshold = dialog.AddSlider("", IterationScoreThreshold, 0.1, 100, 1)
mainDialog.LabelResetWorldGeneration = dialog.AddLabel("Reset World to best solution Every x Generations:")
mainDialog.ResetWorldGeneration = dialog.AddSlider("", ResetWorldGeneration, 1, 200, 0)
mainDialog.MutateRate = dialog.AddSlider("Mutate Rate:", MutateRate, 0.1, 1, 1)
mainDialog.LimitActions = dialog.AddSlider("Limit actions:", 17-3, 1, #performAction, 0)
mainDialog.l1 = dialog.AddLabel("(some are known by humans not to score)")

    mainDialog.OK = dialog.AddButton("OK", 1)
    mainDialog.More = dialog.AddButton("More", 2)
    mainDialog.Cancel = dialog.AddButton("Cancel", 0)

    mainDialogResult = dialog.Show(mainDialog) --jon changed local to global in style of GAB

    if (mainDialogResult > 0) then --jon changed if to while and >= to > to satisfy todo
        PopulationSize = mainDialog.PopulationSize.value
        MutationSize = mainDialog.MutationSize.value
        AliensSize = mainDialog.AliensSize.value
        CrossSize = mainDialog.CrossSize.value
        NumberOfAlgorithmSteps = mainDialog.NumberOfAlgorithmSteps.value
        IterationScoreThreshold = mainDialog.IterationScoreThreshold.value
        ResetWorldGeneration = mainDialog.ResetWorldGeneration.value
        MutateRate = mainDialog.MutateRate.value
        LimitActions=mainDialog.LimitActions.value --jon
        NumberOfActions=LimitActions --overwriting

        -- TODO: Fix windows management. Currently if you go back to Main and click Cancel it is still start script
        if (mainDialogResult == 2) then
            showMoreDialog()
        end
        -- return true --jon deleted in style of GAB
    end
until mainDialogResult<2
return mainDialogResult>0 end

function getCurrentStateString(generation, stateType, typeNumber)
return "Generation " .. string.format("%03d", generation) .. ". " .. string.format("%8s", stateType) .. " Num " .. string.format("%03d", typeNumber) .. ": "
end

function runMainProgram()
local population = {}
local algorithm = {}
–initializeActions() –jon moved
printMainInformation()

-- Create initial population

-- Add own algorithms

--print("does this indentation work") --zw
if InitialAlgorithm[3] then
	algorithm = {}
	algorithm.Hash = CustomAlgorithmHash
	addAlgorithmBasedOnHash(algorithm)
	initializeAlgorithm(algorithm)
	--optimizeAlgorithm(algorithm)
	truncate(algorithm) 
	addHashToAlgorithm(algorithm) --zo3xia
	algorithm.CurrentStateString = getCurrentStateString(0, "Initial", #population + 1) .. algorithm.Hash .. "."
	testAlgorithm(algorithm)
	table.insert(population, algorithm)
end
if InitialAlgorithm[1] then
    algorithm = {5,1,0,4,2,0,3,1,0,4,8,0,1,6,0,4,9,1,0,4}
    initializeAlgorithm(algorithm)
    --optimizeAlgorithm(algorithm)
truncate(algorithm)        
addHashToAlgorithm(algorithm)
    algorithm.CurrentStateString = getCurrentStateString(0, "Initial", #population + 1) .. algorithm.Hash .. "."
    testAlgorithm(algorithm)
    table.insert(population, algorithm)
end

if InitialAlgorithm[2] then
    algorithm = {9,1,0,4,2,0,3,1,0,4,7,0,1,6,0,4,5,1,0,4}
    initializeAlgorithm(algorithm)
    --optimizeAlgorithm(algorithm)
truncate(algorithm)
    addHashToAlgorithm(algorithm)
    algorithm.CurrentStateString = getCurrentStateString(0, "Initial", #population + 1) .. algorithm.Hash .. "."
    testAlgorithm(algorithm)
    table.insert(population, algorithm)
end

-- Add random algorithms

for i = #population + 1, PopulationSize do
    local algorithm = {}
    createRandomAlgorithm(algorithm)
    algorithm.CurrentStateString = getCurrentStateString(0, "Initial", i) .. algorithm.Hash .. "."
    print("algorithm.CurrentStateString is ", algorithm.CurrentStateString) --zw
    testAlgorithm(algorithm)
    table.insert(population, algorithm)
end

sortPopulation(population)
printPopulation(population)

-- Grow of new generations

local generation = 1
while generation <= MaxGenerationSize do

    -- Reset world to best solution in case of Generations limit
    if generation % ResetWorldGeneration == 0 then
        print("World resetting to best solution!")
        print("--------------------------------------------------")
        save.Quickload(2)
        save.Quicksave(1)
        recentbest.Save()

        -- Replace old algorithms score with new for new world.
        for i = 1, #population do
            local newAlgorithm = copyAlgorithm(population[1])
            table.remove(population,1)
            newAlgorithm.CurrentStateString = getCurrentStateString(generation, "Recheck", i) .. newAlgorithm.Hash .. "."
            testAlgorithm(newAlgorithm)
            table.insert(population, newAlgorithm)
        end
    end

    -- Mutation
    for i = 1, math.min(#population, MutationSize) do
        local newAlgorithm = copyAlgorithm(population[i])
        mutateAlgorithm(newAlgorithm)
        newAlgorithm.CurrentStateString = getCurrentStateString(generation, "Mutation", i) .. population[i].Hash .. " to " .. newAlgorithm.Hash .. "."
        testAlgorithm(newAlgorithm)
        table.insert(population, newAlgorithm)
    end

    -- Crossing
    local crossDistance = 1
    local generatedCrossings = 0
    while crossDistance <= PopulationSize - 1 do
        local i = 1
        while i <= PopulationSize - crossDistance and generatedCrossings < CrossSize do
            local newAlgorithm = copyAlgorithm(population[i])
            local newAlgorithmSecond = copyAlgorithm(population[i + crossDistance])
            createCrossAlgorithm(newAlgorithm,newAlgorithmSecond)
            generatedCrossings = generatedCrossings + 1
            newAlgorithm.CurrentStateString = getCurrentStateString(generation, "Crossing", generatedCrossings) .. population[i].Hash .. " + " .. population[i + crossDistance].Hash .. " to " .. newAlgorithm.Hash .. "."
            testAlgorithm(newAlgorithm)
            table.insert(population, newAlgorithm)
            i = i + 1
        end
        crossDistance = crossDistance + 1
    end

    -- Aliens
    for i = 1, AliensSize do
        local newAlgorithm = {}
        createRandomAlgorithm(newAlgorithm)
        newAlgorithm.CurrentStateString = getCurrentStateString(generation, "Alien", i) .. newAlgorithm.Hash .. "."
        testAlgorithm(newAlgorithm)
        table.insert(population, newAlgorithm)
    end

    -- Remove worst from population

    sortPopulation(population)
    print("Top " .. PopulationSize .. " will survive:")
    printPopulation(population)
    while #population > PopulationSize do
        table.remove(population)
    end

    generation = generation + 1
end end

——————— MAIN PROGRAM ——————-
—————————————————————
print("more verbose, default fewer algorithm steps to get to the genetic algorithm mutations part.") –zw
NumberOfAlgorithmSteps = 5 —– 20 –
–NumberOfActions = 11 –jon
initializeActions() –jon
IterationScoreThreshold = 1
ResetWorldGeneration = 100 –jon x10
MutateRate = 0.2
InitialAlgorithm = {true, true, false}
CustomAlgorithmHash = ""

PopulationSize = 5
MutationSize = 4
AliensSize = 0 —5
CrossSize = 1 —5

MaxGenerationSize = 1000
HashStartCharacterCode = 48 –0 –jon
HashShift = 7

save.Quicksave(1)
recentbest.Save()
bestScore = current.GetEnergyScore()
startTime = os.time()
math.randomseed(startTime)

if showMainDialog() then
runMainProgram()
else print("Execution cancelled by user.")
end