forked from juvester/mari-o-fceux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
neatevolve.lua
2049 lines (1634 loc) · 47.8 KB
/
neatevolve.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- MarI/O by SethBling
-- Feel free to use this code, but please do not redistribute it.
-- Port to FCEUX.
-- Tested on FCEUX 2.2.2 (Ubuntu 16.04).
-- #############################################################################
-- ### Instructions ############################################################
-- #############################################################################
-- 1. Save this script somewhere on your computer.
-- 2. Open Super Mario Bros. in FCEUX.
-- 3. Go to some level and make a saveste at the beginning of the level. Use
-- savestate slot 1 or edit the settings below.
-- 4. Load the script in FCEUX (File -> Load Lua Script)
-- 5. Enjoy!'
-- There's no GUI like in Bizhawk but you can edit the following settings
-- manually.
-- #############################################################################
-- ### SETTINGS ################################################################
-- #############################################################################
-- File name for a previously saved MarI/O pool. Use nil to start a new pool.
-- Backups for every generation will be saved in a folder called "backups".
LOAD_FROM_FILE = nil
--LOAD_FROM_FILE = "backups/backup.5.SMB1-1.state.pool"
-- HUD options. Use "false" to hide elements (might improve performance).
SHOW_NETWORK = true
SHOW_MUTATION_RATES = true
-- Load the level from FCEUX savestate slot
SAVESTATE_SLOT = 1
-- #############################################################################
-- #############################################################################
-- #############################################################################
SAVE_LOAD_FILE = "SMB1-1.state.pool"
RECORD_LOAD_FILE = "SMB1-1.rec"
os.execute("mkdir backups")
SavestateObj = savestate.object(SAVESTATE_SLOT)
ButtonNames = {
"A",
"B",
"up",
"down",
"left",
"right",
}
BoxRadius = 6
InputSize = (BoxRadius*2+1)*(BoxRadius*2+1)
Inputs = InputSize+1
Outputs = #ButtonNames
Population = 300
DeltaDisjoint = 2.0
DeltaWeights = 0.4
DeltaThreshold = 1.0
StaleSpecies = 15
MutateConnectionsChance = 0.25
PerturbChance = 0.90
CrossoverChance = 0.75
LinkMutationChance = 2.0
NodeMutationChance = 0.50
BiasMutationChance = 0.40
StepSize = 0.1
DisableMutationChance = 0.4
EnableMutationChance = 0.2
TimeoutConstant = 20
MaxNodes = 1000000
-- recording
SaveGenerationRecords = false -- save unique replays for each generation to disk
MaxPlayedRecords = 1024 -- max simultaneously displaying records
SynchronizedPlayback = false -- should all records play simultaneously
PauseAfterDeath = true -- should game pause for some time, so collision with enemy will not end recording abruptly
DrawRecordAsSprite = true -- draw record using character sprite during playback
DrawRecordAsBox = false -- draw record using simple colored box during playback
DrawRecordTrail = false -- draw record trajectory trail during playback
RecordColors = { "red", "green", "blue", "cyan", "magenta", "yellow", "purple", "white", "orange" } -- colors used to display boxes and trails
RecordTrailFrameCount = 30 -- trail length in frames
DissolveAnimationFrames = 15 -- fade out animation duration in frames
PlayerCloseFadeDistance = 32 -- objects will start to fade at this distance to player, so player can be visible in very crowded environment. 0 to disable
PlayerCloseMaxFade = 0.1 -- maximum fade amount, so record still can be visible, even if its on same spot as player
CrossFadeOnRestart = false
GenerationRecordsList = {}
PlayingRecordsList = {}
CurrentRecord = {}
ScriptQueueSchedule = {}
LastFrameScreenshot = nil
LastFrameScreenshotVisibility = 0
CheckboxOnSprite = nil
CheckboxOffSprite = nil
SettingsButtonSprite = nil
ReplayCharacterSprites = {} -- table which hold every loaded sprite
ReplayCharacterSpriteCount = 160 -- amount of characters in sprites folder
ReplayCharacterFrameNames = {
"idle", -- 1
"walk1", -- 2
"walk2", -- 3
"walk3", -- 4
"jump", -- 5
"skid", -- 6
"climb1", -- 7
"climb2", -- 8
"swim1", -- 9
"swim2", -- 10
"swim3", -- 11
"swim4", -- 12
"swim5", -- 13
"swim6" -- 14
}
IsMousePressed = false
IsMouseReleased = false
IsMouseClicked = false
IsGUIVisible = true
IsSettingsOpened = false
GUIVisibility = 1.0
GUIOffset = 0
FocusedControlId = -1
CurrentControlId = 0
MouseX = 0
MouseY = 0
-- Sprite management functions
function loadGUISprites()
CheckboxOnSprite = loadSprite("checkbox_on")
CheckboxOffSprite = loadSprite("checkbox_off")
SettingsButtonSprite = loadSprite("settings_button")
end
function loadCharacterSprites()
for c = 1, ReplayCharacterSpriteCount do
for i, name in pairs(ReplayCharacterFrameNames) do
loadCharacterSprite(i, false, c)
loadCharacterSprite(i, true, c)
end
end
end
function getCharacterSprite(animFrame, mirrored, character)
local index = getCharacterSpriteIndex(animFrame, mirrored, character)
return ReplayCharacterSprites[index]
end
function getCharacterSpriteName(animFrame, mirrored, character)
local side = "_r_"
if mirrored then
side = "_l_"
end
return ReplayCharacterFrameNames[animFrame] .. side.. character
end
function getCharacterSpriteIndex(animFrame, mirrored, character)
return getCharacterSpriteName(animFrame, mirrored, character)
end
function loadCharacterSprite(animFrame, mirrored, character)
local name = getCharacterSpriteName(animFrame, mirrored, character)
local index = getCharacterSpriteIndex(animFrame, mirrored, character)
ReplayCharacterSprites[index] = loadSprite(name)
end
function loadSprite(name)
local f = io.open("sprites/" .. name .. ".gd", "rb")
local img = f:read("*all")
f:close()
return img
end
-- Game data parsing
function getLevelLayout()
return memory.readbyte(0x00e7)
end
function isPlayerLoaded()
return memory.readbyte(0x06C9) == 0xff and memory.readbyte(0x0490) ~= 0x00 -- TODO: check if this is a proper way to detect that player is loaded into level
end
function readCharacterAnimationDirection()
return memory.readbyte(0x0033) == 2
end
function readCharacterAnimationSprite()
local anim = memory.readbyte(0x06d5)
local swimLegs = 0
if AND(memory.readbyte(0x0009), 0x04) == 0x04 then
swimLegs = 1
end
if anim == 0x68 or anim == 0x00 then return 2 end -- walk1
if anim == 0x70 or anim == 0x10 then return 3 end -- walk2
if anim == 0x60 or anim == 0x08 then return 4 end -- walk3
if anim == 0x80 or anim == 0x20 then return 5 end -- jump
if anim == 0x78 or anim == 0x18 then return 6 end -- skid
if anim == 0xa0 or anim == 0x40 then return 7 end -- climb2
if anim == 0xa8 or anim == 0x48 then return 8 end -- climb2
if anim == 0x88 or anim == 0x28 then return 9 + swimLegs end -- swim1 or swim2
if anim == 0x90 or anim == 0x30 then return 11 + swimLegs end -- swim3 or swim4
if anim == 0x98 or anim == 0x38 then return 13 + swimLegs end -- swim5 or swim6
-- if anim == 0x50 ... crouch
-- if anim == 0x58 ... fire
-- if anim == 0xe0 ... dead
return 1
end
-- Record management functions
function newFrame(xPosition, yPosition, animation, direction, level, isVisible)
local frame = {}
frame.x = xPosition
frame.y = yPosition
frame.animation = animation
frame.direction = direction
frame.level = level
frame.isVisible = isVisible
return frame
end
function newRecording()
local recording = {}
recording.generation = 0
recording.species = 0
recording.genome = 0
recording.fitness = 0
recording.hash = 0
recording.frames = {}
recording.skin = getRecordSkin()
recording.color = getRecordColor()
return recording;
end
function getRecordSkin()
return math.random(1, ReplayCharacterSpriteCount)
end
function getRecordColor()
return RecordColors[math.random(1, #RecordColors)]
end
function recordCurrentFrame(record)
record.frames[#record.frames + 1] = newFrame(marioX, marioY,
readCharacterAnimationSprite(),
readCharacterAnimationDirection(),
getLevelLayout(),
isPlayerLoaded());
record.hash = record.hash + marioX * marioY
end
function saveGenerationRecord(record, generation, species, genome, fitness)
record.generation = generation
record.species = species
record.genome = genome
record.fitness = fitness
for i, record in pairs(GenerationRecordsList) do
if isRecordsSame(record, CurrentRecord) then return end
end
table.insert(GenerationRecordsList, record)
emu.print("New unique record #" .. record.hash .. " added to generation record list, " .. #GenerationRecordsList .. " total" )
end
function clearGenerationRecords()
GenerationRecordsList = {}
collectgarbage()
end
-- Record playback functions
function addRecordToPlayback(record)
for i, playback in ipairs(PlayingRecordsList) do
if isRecordsSame(playback.record, record) then return end -- record is not unique
end
local playback = {}
playback.record = record
playback.currentFrame = 1
playback.totalFrames = #record.frames
playback.frameSprites = {}
for i, frame in ipairs(record.frames) do
table.insert(playback.frameSprites, getCharacterSprite(frame.animation, frame.direction, record.skin))
end
table.insert(PlayingRecordsList, playback)
if #PlayingRecordsList > MaxPlayedRecords then
table.remove(PlayingRecordsList, 1)
end
end
function resetPlaybackFrames()
for i, playback in ipairs(PlayingRecordsList) do
playback.currentFrame = 1
end
end
function updatePlaybackFrame(currentFrame)
for i, playback in ipairs(PlayingRecordsList) do
if SynchronizedPlayback then
playback.currentFrame = currentFrame
else
local respawnDelay = DissolveAnimationFrames
if DrawRecordTrail then
respawnDelay = math.max(DissolveAnimationFrames, RecordTrailFrameCount)
end
playback.currentFrame = playback.currentFrame + 1
if playback.totalFrames + respawnDelay < playback.currentFrame then
playback.currentFrame = 1
end
end
end
end
function clearPlayingRecords()
PlayingRecordsList = {}
end
-- GUI Drawing functions
function updateGUIInput()
local i = input.get()
local pressed = i.click == 1
IsMouseClicked = pressed and pressed ~= IsMousePressed
IsMouseReleased = not pressed and pressed ~= IsMousePressed
IsMousePressed = pressed
MouseX = i.xmouse
MouseY = i.ymouse
if IsMouseReleased then
FocusedControlId = -1
end
CurrentControlId = 0
end
function drawButton(x, y, w, text, color)
gui.box(x, y, x + w, y + 8, color, color)
gui.text(x + 1, y + 1, text, "white", "clear")
if IsGUIVisible then
return checkButton(x, y, w, 8)
end
return false
end
function drawSlider(x, y, w, value, minValue, maxValue, text)
if not text then text = "" end
gui.box(x, y, x + w, y + 8, { 0, 0, 0, 128 }, "white")
local offset = 1 + ((value - minValue) / (maxValue - minValue)) * (w - 2)
local t = 0
if checkButton(x, y, w, 8, true) then
t = (MouseX - x - 1) / (w - 2)
if t < 0 then t = 0 end
if t > 1 then t = 1 end
value = math.floor(minValue + (maxValue - minValue) * t)
end
gui.text(x + 4, y + 1, value .. " " .. text, "#4CFF00aa", "clear")
if offset < 1 then offset = 1 end
if offset > w - 1 then offset = w - 1 end
gui.line(x + offset, y + 1, x + offset, y + 7, "#4CFF00")
return value
end
function drawCheckbox(x, y, w, isChecked, text)
if checkButton(x, y, w, 7) then
isChecked = not isChecked
end
if isChecked then
gui.image(x, y, CheckboxOnSprite)
else
gui.image(x, y, CheckboxOffSprite)
end
drawShadedText(x + 10, y, text)
return isChecked
end
function drawShadedText(x, y, text, color)
if not color then color = white end
gui.text(x + 1, y + 1, text, { 0, 0, 0, 128 }, "clear")
gui.text(x, y, text, color, "clear")
end
function checkButton(x, y, w, h, continous)
local isClicked = IsMouseClicked
CurrentControlId = CurrentControlId + 1
if continous then
if FocusedControlId == CurrentControlId then
return true
end
end
if isClicked and MouseX >= x and MouseX < x + w and MouseY >= y and MouseY < y + h then
IsMouseClicked = false
FocusedControlId = CurrentControlId
return true
end
return false
end
function updateGUIParams()
if IsGUIVisible then
if GUIVisibility < 1 then
GUIVisibility = GUIVisibility + 0.05
end
else
if GUIVisibility > 0 then
GUIVisibility = GUIVisibility - 0.05
end
end
local targetOffset = 0
if IsSettingsOpened then targetOffset = -133 end
GUIOffset = GUIOffset + (targetOffset - GUIOffset) * 0.15
end
function startScreenCrossFade()
LastFrameScreenshot = gui.gdscreenshot()
LastFrameScreenshotVisibility = 1
end
function updateScreenCrossFade()
if LastFrameScreenshotVisibility > 0 then
LastFrameScreenshotVisibility = LastFrameScreenshotVisibility - 0.05
if LastFrameScreenshotVisibility < 0 then LastFrameScreenshotVisibility = 0 end
end
end
function formatFitness(fitness, appendSign)
local sign = "+"
if appendSign then
sign = getNumberSign(fitness)
else
sign = " "
end
return sign .. string.format("%04d", math.abs(math.floor(fitness)))
end
function getNumberSign(number)
if number < 0 then return "-" else return "+" end
end
function drawGUI()
if SHOW_NETWORK then
gui.opacity(1)
displayGenome(getCurrentGenome())
end
updateGUIParams()
updateGUIInput()
if GUIVisibility > 0 then
gui.opacity(0.3 * GUIVisibility)
gui.box(-1, 211 + GUIOffset, 256, 256, "black", "clear")
gui.opacity(GUIVisibility)
drawShadedText(8, 215 + GUIOffset, "Gen: " .. pool.generation ..
" Species: " .. pool.currentSpecies ..
" Genome: " .. pool.currentGenome ..
" (" .. getGenerationPercentage() .. "%)")
local fitness = getTotalFitness()
drawShadedText(8, 223 + GUIOffset, "Fitness: " .. formatFitness(fitness, false) ..
" / " .. formatFitness(pool.maxFitness, true))
drawShadedText(49, 223 + GUIOffset, getNumberSign(fitness)) -- this is to prevent situation, when rapidly changing +- shakes whole text
drawShadedText(136, 223 + GUIOffset, "Records: " .. math.min(#PlayingRecordsList, MaxPlayedRecords))
gui.image(232, 214 + GUIOffset, SettingsButtonSprite)
if IsGUIVisible and checkButton(232, 214 + GUIOffset, 16, 16) then IsSettingsOpened = not IsSettingsOpened end
if GUIOffset < -0.1 then
local bottomOffset = 232 + GUIOffset
gui.opacity(GUIVisibility * 0.3)
gui.box(0, bottomOffset, 255, bottomOffset - GUIOffset - 1, "black", "clear")
gui.opacity(GUIVisibility)
drawShadedText(8, 4 + bottomOffset, "Record display options", "red")
gui.line(8, 12 + bottomOffset, 112, 12 + bottomOffset, "red")
DrawRecordAsSprite = drawCheckbox(8, 16 + bottomOffset, 64, DrawRecordAsSprite, "Draw sprite")
DrawRecordAsBox = drawCheckbox(96, 16 + bottomOffset, 64, DrawRecordAsBox, "Draw box")
DrawRecordTrail = drawCheckbox(184, 16 + bottomOffset , 64, DrawRecordTrail, "Draw trail")
drawShadedText(8, 26 + bottomOffset, "Trail length: ")
RecordTrailFrameCount = drawSlider(96, 26 + bottomOffset, 150, RecordTrailFrameCount, 0, 120, "frames")
drawShadedText(8, 36 + bottomOffset, "Death fade: ")
DissolveAnimationFrames = drawSlider(96, 36 + bottomOffset, 150, DissolveAnimationFrames, 0, 60, "frames")
drawShadedText(8, 46 + bottomOffset, "Fade distance: ")
PlayerCloseFadeDistance = drawSlider(96, 46 + bottomOffset, 150, PlayerCloseFadeDistance, 0, 120, "pixels")
drawShadedText(8, 58 + bottomOffset, "Record playback options", "red")
gui.line(8, 66 + bottomOffset, 120, 66 + bottomOffset, "red")
SynchronizedPlayback = drawCheckbox(8, 70 + bottomOffset, 64, SynchronizedPlayback, "Synchronous")
drawShadedText(8, 80 + bottomOffset, "Maximum: ")
MaxPlayedRecords = drawSlider(52, 80 + bottomOffset, 194, MaxPlayedRecords, 0, 2048, "records")
drawShadedText(8, 92 + bottomOffset, "Misc", "red")
gui.line(8, 100 + bottomOffset, 27, 100 + bottomOffset, "red")
SaveGenerationRecords = drawCheckbox(8, 104 + bottomOffset, 96, SaveGenerationRecords, "Save records")
PauseAfterDeath = drawCheckbox(8, 112 + bottomOffset, 96, PauseAfterDeath, "Pause after death")
CrossFadeOnRestart = drawCheckbox(8, 120 + bottomOffset, 96, CrossFadeOnRestart, "Cross fade on restart")
if drawButton(170, 120 + bottomOffset, 40, "Play Top", { 0, 255, 0, 128 }) then
IsSettingsOpened = false
schedule(playTop)
end
if drawButton(212, 120 + bottomOffset, 34, "Restart", { 255, 0, 0, 128 }) then
IsSettingsOpened = false
schedule(restart)
end
end
end
-- This check order is intentional, so panel will block clicks
if checkButton(0, 212 + GUIOffset, 256, 256) and not IsSettingsOpened then IsGUIVisible = not IsGUIVisible end
if checkButton(0, 26, 256, 76) then SHOW_NETWORK = not SHOW_NETWORK end
if checkButton(0, 103, 256, 128) then SHOW_MUTATION_RATES = not SHOW_MUTATION_RATES end
end
-- Record drawing functions
function forEachPlayingRecord(func)
local xScreenOffset = marioX - screenX
local yScreenOffset = 0
for i, playback in ipairs(PlayingRecordsList) do
if i > MaxPlayedRecords then return end
local currentFrame = playback.currentFrame
local lastFrame = currentFrame
local firstFrame = currentFrame - RecordTrailFrameCount
local frameCount = playback.totalFrames
if lastFrame > frameCount then lastFrame = frameCount end
func(playback, lastFrame, currentFrame, xScreenOffset, yScreenOffset)
end
end
function calculateProximityOpacity(frameData)
local opacityScale = 1
if PlayerCloseFadeDistance > 0 then
opacityScale = getProximity(frameData.x, frameData.y, marioX, marioY) / PlayerCloseFadeDistance
if opacityScale > 1 then opacityScale = 1 end
if opacityScale < PlayerCloseMaxFade then opacityScale = PlayerCloseMaxFade end
end
return opacityScale
end
function drawRecordTrail(playback, lastFrame, currentFrame, xScreenOffset, yScreenOffset)
local record = playback.record
local firstFrame = currentFrame - RecordTrailFrameCount
if firstFrame > lastFrame then firstFrame = lastFrame end
if firstFrame < 1 then firstFrame = 1 end
local currentLayout = getLevelLayout()
local prevXPosition
local prevYPosition
for frame = firstFrame, lastFrame do
local frameData = record.frames[frame]
if frameData.level == currentLayout and frameData.isVisible then
local xPosition = frameData.x - xScreenOffset + 8
local yPosition = frameData.y - yScreenOffset + 24
if prevXPosition and (xPosition ~= prevXPosition or yPosition ~= prevYPosition) and isInScreenBounds(xPosition, yPosition, 4) then
local proximityScale = calculateProximityOpacity(frameData)
local colorScale = (frame - firstFrame + 1) / RecordTrailFrameCount
gui.opacity(colorScale * proximityScale)
gui.line(prevXPosition, prevYPosition, xPosition, yPosition, record.color, false)
end
prevXPosition = xPosition
prevYPosition = yPosition
else
prevXPosition = nil
prevYPosition = nil
end
end
end
function drawRecordBox(playback, lastFrame, currentFrame, xScreenOffset, yScreenOffset)
local record = playback.record
local frameData = record.frames[lastFrame]
local currentLayout = getLevelLayout()
if not frameData.isVisible or frameData.level ~= currentLayout then return end
local xPosition = frameData.x - xScreenOffset + 8
local yPosition = frameData.y - yScreenOffset + 24
local frameCount = playback.totalFrames
if isInScreenBounds(xPosition, yPosition, 12) and (frameCount + DissolveAnimationFrames) > currentFrame then
local size = 1
local proximityScale = calculateProximityOpacity(frameData)
if frameCount > currentFrame then
gui.opacity(proximityScale)
else
local t = (currentFrame - frameCount) / DissolveAnimationFrames
gui.opacity((1 - t) * proximityScale)
size = 1 + 10 * t
end
gui.box(xPosition - size, yPosition - size, xPosition + size, yPosition + size, record.color, { 0, 0, 0, 128 })
end
end
function drawRecordCharacter(playback, lastFrame, currentFrame, xScreenOffset, yScreenOffset)
local record = playback.record
local frameData = record.frames[lastFrame]
local currentLayout = getLevelLayout()
if not frameData.isVisible or frameData.level ~= currentLayout then return end
local xPosition = frameData.x - xScreenOffset - 4
local yPosition = frameData.y - yScreenOffset + 9
local animImage = playback.frameSprites[lastFrame]
local frameCount = playback.totalFrames
local proximityScale = calculateProximityOpacity(frameData)
if isInScreenBounds(xPosition, yPosition, 24) and (frameCount + DissolveAnimationFrames) > currentFrame and animImage then
if frameCount > currentFrame then
gui.opacity(proximityScale)
else
local t = (currentFrame - frameCount) / DissolveAnimationFrames
gui.opacity((1 - t) * proximityScale)
end
gui.image(xPosition, yPosition, animImage)
end
end
function drawPlayingRecords()
if not isPlayerLoaded() then
return -- if player is not loaded, then probably it is a blank screen, so dont display replays here
end
if DrawRecordTrail then
forEachPlayingRecord(drawRecordTrail)
end
if DrawRecordAsSprite then
forEachPlayingRecord(drawRecordCharacter)
end
if DrawRecordAsBox then
forEachPlayingRecord(drawRecordBox)
end
end
function drawScreenCrossFade()
if LastFrameScreenshot and LastFrameScreenshotVisibility ~= 0 then
gui.opacity(LastFrameScreenshotVisibility)
gui.image(0, 0, LastFrameScreenshot)
drawShadedText(108, 108, "RESTARTING...")
end
end
-- Saving, Loading
function writeRecordsBackupFile()
writeRecordsFile("backups/backup." .. pool.generation .. "." .. RECORD_LOAD_FILE, GenerationRecordsList)
end
function writeGenerationBackupFile()
writeFile("backups/backup." .. pool.generation .. "." .. SAVE_LOAD_FILE)
end
function writeRecordsFile(filename, recordList)
local file = io.open(filename, "w")
file:write("2\n") -- format version
file:write(#recordList .. "\n")
for i, record in ipairs(recordList) do
local r, g, b, a = gui.parsecolor(record.color)
file:write("--- record [" .. i .. "] ---\n")
file:write(record.hash .. "\n")
file:write(record.fitness .. "\n")
file:write(#record.frames .. "\n")
file:write(record.generation .. "\n")
file:write(record.species .. "\n")
file:write(record.genome .. "\n")
file:write(record.skin .. "\n")
file:write(r .. ", " .. g .. ", " .. b .. ", " .. a .. "\n")
for j, frame in ipairs(record.frames) do
local anim = -1
if frame.isVisible then
anim = frame.animation
if frame.direction then
anim = anim + 0x20
end
end
file:write(frame.x .. " " .. frame.y .. " " .. anim .. " " .. frame.level .. "\n")
end
end
file:close()
end
-- Utility functions
function schedule(func)
table.insert(ScriptQueueSchedule, func)
end
function getProximity(x1, y1, x2, y2)
return math.max(math.abs(x1 - x2), math.abs(y1 - y2))
end
function isInScreenBounds(x, y, radius)
return x > -radius and x < 256 + radius and y > -radius and y < 256 + radius
end
function isRecordsSame(record1, record2)
return record1.hash == record2.hash and record1.fitness == record2.fitness and #record1.frames == #record2.frames
end
function runScheduledFunctions()
if #ScriptQueueSchedule ~= 0 then
for i, f in ipairs(ScriptQueueSchedule) do
f()
end
ScriptQueueSchedule = {}
end
end
-- Original algorithm
function toRGBA(ARGB)
return bit.lshift(ARGB, 8) + bit.rshift(ARGB, 24)
end
function isDead()
local playerState = memory.readbyte(0x000E)
return playerState == 0x0B or -- Dying
playerState == 0x06 or -- Dead
memory.readbyte(0x00B5) > 1 -- Below viewport (in pit)
end
function getPositions()
marioX = memory.readbyte(0x6D) * 0x100 + memory.readbyte(0x86)
marioY = memory.readbyte(0x03B8) + (memory.readbyte(0xB5) - 1) * 0xFF
screenX = memory.readbyte(0x03AD)
end
function getTile(dx, dy)
local x = marioX + dx + 8
local y = marioY + dy
local page = math.floor(x/256)%2
local subx = math.floor((x%256)/16)
local suby = math.floor((y - 32)/16)
local addr = 0x500 + page*13*16+suby*16+subx
if suby >= 13 or suby < 0 then
return 0
end
if memory.readbyte(addr) ~= 0 then
return 1
else
return 0
end
end
function getSprites()
local sprites = {}
for slot=0,4 do
local enemy = memory.readbyte(0xF+slot)
if enemy ~= 0 then
local ex = memory.readbyte(0x6E + slot)*0x100 + memory.readbyte(0x87+slot)
local ey = memory.readbyte(0xCF + slot)+24
sprites[#sprites+1] = {["x"]=ex,["y"]=ey}
end
end
return sprites
end
function getInputs()
getPositions()
local sprites = getSprites()
local inputs = {}
for dy=-BoxRadius*16,BoxRadius*16,16 do
for dx=-BoxRadius*16,BoxRadius*16,16 do
inputs[#inputs+1] = 0
tile = getTile(dx, dy)
if tile == 1 and marioY+dy + 16 < 0x1B0 then
inputs[#inputs] = 1
end
for i = 1,#sprites do
distx = math.abs(sprites[i]["x"] - (marioX+dx))
disty = math.abs(sprites[i]["y"] - (marioY+dy + 16))
if distx <= 8 and disty <= 8 then
inputs[#inputs] = -1
end
end
end
end
--mariovx = memory.read_s8(0x7B)
--mariovy = memory.read_s8(0x7D)
return inputs
end
function sigmoid(x)
return 2/(1+math.exp(-4.9*x))-1
end
function newInnovation()
pool.innovation = pool.innovation + 1
return pool.innovation
end
function newPool()
local pool = {}
pool.species = {}
pool.generation = 0
pool.innovation = Outputs
pool.currentSpecies = 1
pool.currentGenome = 1
pool.currentFrame = 1
pool.maxFitness = 0
return pool
end
function newSpecies()
local species = {}
species.topFitness = 0
species.staleness = 0
species.genomes = {}
species.averageFitness = 0
return species
end
function newGenome()
local genome = {}
genome.genes = {}
genome.fitness = 0
genome.adjustedFitness = 0
genome.network = {}
genome.maxneuron = 0
genome.globalRank = 0
genome.mutationRates = {}
genome.mutationRates["connections"] = MutateConnectionsChance
genome.mutationRates["link"] = LinkMutationChance
genome.mutationRates["bias"] = BiasMutationChance
genome.mutationRates["node"] = NodeMutationChance
genome.mutationRates["enable"] = EnableMutationChance
genome.mutationRates["disable"] = DisableMutationChance
genome.mutationRates["step"] = StepSize
return genome
end
function copyGenome(genome)
local genome2 = newGenome()
for g=1,#genome.genes do
table.insert(genome2.genes, copyGene(genome.genes[g]))
end
genome2.maxneuron = genome.maxneuron
genome2.mutationRates["connections"] = genome.mutationRates["connections"]
genome2.mutationRates["link"] = genome.mutationRates["link"]
genome2.mutationRates["bias"] = genome.mutationRates["bias"]
genome2.mutationRates["node"] = genome.mutationRates["node"]
genome2.mutationRates["enable"] = genome.mutationRates["enable"]
genome2.mutationRates["disable"] = genome.mutationRates["disable"]
return genome2
end
function basicGenome()
local genome = newGenome()
local innovation = 1
genome.maxneuron = Inputs
mutate(genome)
return genome
end
function newGene()
local gene = {}
gene.into = 0
gene.out = 0
gene.weight = 0.0
gene.enabled = true
gene.innovation = 0
return gene
end
function copyGene(gene)
local gene2 = newGene()