-
Notifications
You must be signed in to change notification settings - Fork 2
/
RYUNATOR.lua
1710 lines (1458 loc) · 41 KB
/
RYUNATOR.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
local mem = manager:machine().devices[":maincpu"].spaces["program"]
local gui = manager:machine().screens[":screen"]
local Json = require("json")
local path = "src/RYUNATOR/pools/"
local players_amount = 2
-- Memory address offset to differentiate p1 and p2
local player_offset = 0x0300
-- Memory address offset for projectile slots
local projectile_offset = -0xC0
-- Combines ports IN1 and IN2
local pool
local controllers
local max_health = {}
local time_cornered, time_blocking, time_air, time_close = {}, {}, {}, 0
local win_streak = 0
local punches = {
" Jab Punch",
" Strong Punch",
" Fierce Punch",
}
local kicks = {
" Short Kick",
" Forward Kick",
" Roundhouse Kick",
}
local special_attacks = {
" special 1",
" special 2",
" special 3",
}
--------------------
--- NEAT variables--
--------------------
local output_buttons = {
" Up",
" Right",
" Left",
" Down",
" Jab Punch",
" Strong Punch",
" Fierce Punch",
" Short Kick",
" Forward Kick",
" Roundhouse Kick",
" special 1",
" special 2",
" special 3",
}
gui_element = 6
Inputs = 45
Outputs = #output_buttons
Population = 300
DeltaDisjoint = 2.0
DeltaWeights = 0.4
DeltaThreshold = 1.0
StaleSpecies = 25
MutateConnectionsChance = 0.35
PerturbChance = 0.90
CrossoverChance = 0.75
LinkMutationChance = 2.0
NodeMutationChance = 0.60
BiasMutationChance = 0.40
StepSize = 0.1
DisableMutationChance = 0.4
EnableMutationChance = 0.2
MaxNodes = 1000000
-- Used to determine if we need to continue input for a special move accross several frames.
-- counts the frame of the current special move.
local special_move_frame = { ["P1"] = 0, ["P2"] = 0 }
-- 0: no special move
-- 1: Quarter Circle Forward
-- 2: Quarter Circle Back
-- 3: Z-Move
local curr_special_move = { ["P1"] = 0, ["P2"] = 0 }
----------------------
-- CONTROLLER INPUT --
----------------------
local function set_input(key)
--[[ print("key is " .. key)
for kp, p in pairs(controllers) do
print("Values for table " .. kp)
for k, b in pairs(p) do
print(k .. " : " .. b.state)
end
end]]
for name, button in pairs(controllers[key]) do
button.field:set_value(button.state)
end
end
local function clear_input(controller_to_update)
local key = controller_to_update == 0 and "P1" or "P2"
for button in pairs(controllers[key]) do
controllers[key][button].state = 0
end
end
local function map_input()
controllers = {}
controllers["P1"] = {}
controllers["P2"] = {}
-- Table with the arcade's ports
local ports = manager:machine():ioport().ports
-- Get input port for sticks and punches
local IN1 = ports[":IN1"]
-- Get input port for kicks
local IN2 = ports[":IN2"]
-- Iterate over fields (button names) and create button objects
for field_name, field in pairs(IN1.fields) do
local button = {}
button.port = IN1
button.field = field
button.state = 0
controllers[string.sub(field_name, 1, 2)][field_name] = button
end
-- Iterate over fields (button names) and create button objects
for field_name, field in pairs(IN2.fields) do
local button = {}
button.port = IN2
button.field = field
button.state = 0
controllers[string.sub(field_name, 1, 2)][field_name] = button
end
set_input("P1")
set_input("P2")
end
--------------------------
-- END CONTROLLER INPUT --
--------------------------
----------------
-- MEM ACCESS --
----------------
-- The parameter represents which player's info you want, indexed from 0.
-- Player, what byte to start reading from in the 24 byte sequence, how many bytes to read (1, 2, 4)
function get_animation_byte(player_num, byte, to_read)
local anim_pointer = mem:read_u32(0xFF83D8 + (player_offset * player_num))
if to_read == 1 then
return mem:read_u8(anim_pointer + byte)
elseif to_read == 2 then
return mem:read_u16(anim_pointer + byte)
else
return mem:read_u32(anim_pointer + byte)
end
end
function get_hitbox_attack_byte(player_num, byte)
local hitbox_info = get_hitbox_info(player_num)
-- Offset for atk hitboxes
local attack_hitbox_offset = mem:read_u16(hitbox_info + 0x08)
local attack_hitbox_list = hitbox_info + attack_hitbox_offset
-- Offset defined in animation data
local attack_hitbox_list_offset = get_animation_byte(player_num, 0x0C, 1)
-- multiply by the size of atk hitboxes (12 bytes)
local curr_attack_hitbox = attack_hitbox_list + (attack_hitbox_list_offset * 12)
-- Get the requested byte (atk hitboxes are defined by 12 bytes)
return mem:read_u8(curr_attack_hitbox + byte)
end
function get_hitbox_info(player_num)
local hitbox_info_pointer = mem:read_u32(0xFF83F2 + (player_offset * player_num))
return hitbox_info_pointer
end
function get_health(player_num)
local health = mem:read_u16(0xFF83EA + (player_offset * player_num)) > 1000 and 144 or mem:read_u16(0xFF83EA + (player_offset * player_num))
return health
end
function has_control(player_num)
return mem:read_u16(0xFF83EE + (player_offset * player_num)) == 1
end
function get_timer()
return tonumber(string.format("%x", mem:read_u8(0xFF8ABE)))
end
function is_round_finished()
return mem:read_u16(0xFF8AC0) == 1
end
-- Default 0, 1 -> P1, 2 -> P2, 255 -> Draw
function get_round_winner()
return mem:read_u8(0xFF8AC2)
end
--[[
State?
20 (00010100) - thrown / grounded
14 (00001110) - hitstun OR blockstun
12 (00001100) - special move
10 (00001010) - attacking OR throwing
8 (00001000) - blocking (not hit yet)
6 (00000110) - ?
4 (00000100) - jumping
2 (00000010) - crouching
0 (00000000) - standing
]] --
function get_player_state(player_num)
return mem:read_u8(0xFF83C1 + (player_offset * player_num))
end
-- NN INPUTS --
function get_pos_x(player_num)
return mem:read_u16(0xFF83C4 + (player_offset * player_num))
end
function get_pos_y(player_num)
return mem:read_u16(0xFF83C8 + (player_offset * player_num))
end
function get_x_distance()
return mem:read_u16(0xFF8540)
end
function get_y_distance()
return mem:read_u16(0xFF8542)
end
function is_midair(player_num)
return num(mem:read_u16(0xFF853F + (player_offset * player_num)) > 0)
end
function in_hit_distance()
local dist = get_x_distance()
if dist > 50 then
return 0
else
return (50 - dist) / 50
end
end
function is_thrown(player_num)
return num(get_player_state(player_num) == 20)
end
function is_crouching(player_num)
return num(get_animation_byte(player_num, 0x12, 1) == 1)
end
-- player_num = player blocking
-- animation byte returns 0 = no block, 1 = standing block, -1 = crouching block
-- returns One Hot encoded array with values {no blocking, standing block, crouching block}
function get_blocking(player_num)
local blocking = get_animation_byte(player_num, 0x11, 1)
features = one_hot_encode_features(1,-1,blocking)
return features
end
-- player_num = player attacking
-- 0 = no attack, 1 = should block high, -1 = should block low
-- returns one hot encoded array with values {no attack, should block high, and should block low}
function get_attack_block(player_num)
local attack_ex = get_hitbox_attack_byte(player_num, 0x7)
return one_hot_encode_features(1,-1, attack_ex)
end
function is_in_hitstun(player_num)
return num(get_player_state(player_num) == 14 and get_blocking(player_num)[1] == 1)
end
-- Special move with invincibility OR waking up
function is_invincible(player_num)
return num(get_animation_byte(player_num, 0x08, 1) == 0 and
get_animation_byte(player_num, 0x09, 1) == 0 and
get_animation_byte(player_num, 0x0A, 1) == 0 and
get_animation_byte(player_num, 0x0D, 1) == 1)
end
function is_cornered(player_num)
local pos_player = get_pos_x(player_num)
if get_x_distance() < 90 then
if pos_player > 925 and get_forward(player_num) == " Left" then
return 1
elseif pos_player < 345 and get_forward(player_num) == " Right" then
return 1
end
end
return 0
end
-- 8 projectile slots, indexed from 0
function is_projectile_active(projectile_slot)
return mem:read_u16(0xFF98C7 + (projectile_offset * projectile_slot)) ~= 0
end
function projectile_pos_x(projectile_slot)
return mem:read_u16(0xFF98BC + (projectile_offset * projectile_slot))
end
function projectile_pos_y(projectile_slot)
return mem:read_u16(0xFF98C0 + (projectile_offset * projectile_slot))
end
-- END NN INPUTS --
--------------------
-- END MEM ACCESS --
--------------------
----------------------
-- HELPER FUNCTIONS --
----------------------
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
function flatten(list)
if type(list) ~= "table" then return {list} end
local flat_list = {}
for _, elem in ipairs(list) do
for _, val in ipairs(flatten(elem)) do
flat_list[#flat_list + 1] = val
end
end
return flat_list
end
local function array_has_value(tab, val)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
function num(var)
return var and 1 or 0
end
function get_forward(player)
local p1 = get_pos_x(0)
local p2 = get_pos_x(1)
if player == 0 then
if p1 < p2 then
return " Right"
else
return " Left"
end
else
if p2 < p1 then
return " Right"
else
return " Left"
end
end
end
function get_backward(player)
local p1 = get_pos_x(0)
local p2 = get_pos_x(1)
if player == 0 then
if p1 > p2 then
return " Right"
else
return " Left"
end
else
if p2 > p1 then
return " Right"
else
return " Left"
end
end
end
function one_hot_encode_features(max, min, active_feature)
features = {}
for i = 1, max-min do
table.insert(features, (i == feature) and 1 or 0)
end
return features
end
function start_round()
manager:machine():load("1");
max_health[1] = get_health(0) < 144 and 144 or get_health(0)
max_health[2] = get_health(1) < 144 and 144 or get_health(1)
time_cornered[1] = 0
time_cornered[2] = 0
time_blocking[1] = 0
time_blocking[2] = 0
time_air[1] = 0
time_air[2] = 0
time_close = 0
if win_streak % 50 == 0 and win_streak ~= 0 then
--[[ print("Mixing nets")
local species = pool[1].species[pool[1].current_species]
local g1 = species.genomes[pool[1].current_genome]
local species2 = pool[2].species[pool[2].current_species]
local g2 = species2.genomes[pool[2].current_genome]
local child = {}
if win_streak < 0 then
print("Mixing net 2 into 1")
child = mix_nets(g1, g2, 1)
table.insert(child, breed_child(species, 1))
add_to_species(child, 1)
else
print("Mixing net 1 into 2 ")
child = mix_nets(g1, g2, 2)
table.insert(child, breed_child(species2, 2))
add_to_species(child, 2)
end]]
win_streak = 0
end
for i = 1, players_amount do
next_genome(i)
local species = pool[i].species[pool[i].current_species]
local genome = species.genomes[pool[i].current_genome]
generate_network(genome)
end
end
--------------------------
-- END HELPER FUNCTIONS --
--------------------------
--------------------
-- PLAYER ACTIONS --
--------------------
function quarter_circle_forward(controller_to_update, punch_type)
local key = controller_to_update == 0 and "P1" or "P2"
local forward = get_forward(controller_to_update)
local attack = punches[punch_type]
clear_input(controller_to_update)
-- Determine input based on current frame
if special_move_frame[key] == 0 then
controllers[key][key .. " Down"].state = 1
elseif special_move_frame[key] == 1 then
controllers[key][key .. " Down"].state = 1
controllers[key][key .. forward].state = 1
elseif special_move_frame[key] == 2 then
controllers[key][key .. forward].state = 1
controllers[key][key .. attack].state = 1
elseif special_move_frame[key] == 3 then
special_move_frame[key] = 0
-- Mark the move as finished
curr_special_move[key] = 0
clear_input(key)
end
set_input(key)
if curr_special_move[key] ~= 0 then
special_move_frame[key] = special_move_frame[key] + 1
end
end
function quarter_circle_back(controller_to_update, kick_type)
-- Determine input based on current frame
local attack = kicks[kick_type]
local key = controller_to_update == 0 and "P1" or "P2"
local back = get_backward(controller_to_update)
clear_input(controller_to_update)
-- Determine input based on current frame
if special_move_frame[key] == 0 then
controllers[key][key .. " Down"].state = 1
elseif special_move_frame[key] == 1 then
controllers[key][key .. " Down"].state = 1
controllers[key][key .. back].state = 1
elseif special_move_frame[key] == 2 then
controllers[key][key .. back].state = 1
controllers[key][key .. attack].state = 1
elseif special_move_frame[key] == 3 then
special_move_frame[key] = 0
-- Mark the move as finished
curr_special_move[key] = 0
clear_input(key)
end
set_input(key)
if curr_special_move[key] ~= 0 then
special_move_frame[key] = special_move_frame[key] + 1
end
end
function z_move(controller_to_update, attack_type)
local attack = punches[attack_type]
local key = controller_to_update == 0 and "P1" or "P2"
local forward = get_forward(controller_to_update)
clear_input(controller_to_update)
-- Determine input based on current frame
if special_move_frame[key] == 0 then
controllers[key][key .. forward].state = 1
elseif special_move_frame[key] == 1 then
controllers[key][key .. " Down"].state = 1
elseif special_move_frame[key] == 2 then
controllers[key][key .. forward].state = 1
controllers[key][key .. " Down"].state = 1
controllers[key][key .. attack].state = 1
elseif special_move_frame[key] == 3 then
special_move_frame[key] = 0
-- Mark the move as finished
curr_special_move[key] = 0
clear_input(key)
end
set_input(key)
if curr_special_move[key] ~= 0 then
special_move_frame[key] = special_move_frame[key] + 1
end
end
------------------------
-- END PLAYER ACTIONS --
------------------------
----------
-- NEAT --
----------
-- x - min / max - min
function get_inputs(player_num)
-- Without keys to ensure their order is always maintained
local enemy = player_num == 0 and 1 or 0
local forward = get_forward(player_num) == " Right" and 1 or -1
local input_table = {
-- shared inputs
(get_x_distance()) / (264) * forward,
in_hit_distance() * forward,
-- Own inputs
(get_pos_x(player_num) - 990) / (990 - 420),
(get_pos_y(player_num) - 40) / (120 - 40),
get_health(player_num) / (max_health[(player_num + 1)]),
is_cornered(player_num),
is_midair(player_num),
is_thrown(player_num),
is_in_hitstun(player_num),
is_crouching(player_num),
is_invincible(player_num),
get_blocking(player_num),
get_attack_block(player_num),
-- Enemy inputs
(get_pos_x(enemy) - 990) / (990 - 420),
(get_pos_y(enemy) - 120) / (120 - 40),
get_health(enemy) / (max_health[enemy + 1]),
is_cornered(enemy),
is_midair(enemy),
is_thrown(enemy),
is_in_hitstun(enemy),
is_crouching(enemy),
is_invincible(enemy),
get_blocking(enemy),
get_attack_block(enemy),
}
for i = 0, 7, 1 do
local distance_x, distance_y = 0, 0
if is_projectile_active(i) then
if projectile_pos_x(i) > 0 then
distance_x = math.max(get_pos_x(player_num), projectile_pos_x(i)) - math.min(get_pos_x(player_num), projectile_pos_x(i))
else
distance_x = 0
end
if projectile_pos_y(i) > 0 then
distance_y = math.max(get_pos_y(player_num), projectile_pos_y(i)) - math.min(get_pos_y(player_num), projectile_pos_y(i))
else
distance_y = 0
end
end
table.insert(input_table, (distance_x / 264))
table.insert(input_table, (distance_y / 264))
end
-- print(dump(flatten(input_table)))
return flatten(input_table)
end
function sigmoid(x)
return 2 / (1 + math.exp(-x)) - 1
end
function new_innovation(net_num)
pool[net_num].innovation = pool[net_num].innovation + 1
return pool[net_num].innovation
end
function new_pool()
local pool = {}
pool.species = {}
pool.generation = 0
pool.innovation = Outputs
pool.current_species = 1
pool.current_genome = 1
pool.current_frame = 0
pool.curr = 0
pool.max_fitness = 0
return pool
end
function new_species()
local species = {}
species.top_fitness = 0
species.staleness = 0
species.genomes = {}
species.average_fitness = 0
return species
end
function basic_genome(pool_num)
local genome = new_genome()
local innovation = 1
genome.max_neuron = Inputs
mutate(genome, pool_num)
return genome
end
function new_genome()
local genome = {}
genome.genes = {}
genome.fitness = 0
genome.adjusted_fitness = 0
genome.network = {}
genome.max_neuron = 0
genome.global_rank = 0
genome.mutation_rates = {}
genome.mutation_rates["connections"] = MutateConnectionsChance
genome.mutation_rates["link"] = LinkMutationChance
genome.mutation_rates["bias"] = BiasMutationChance
genome.mutation_rates["node"] = NodeMutationChance
genome.mutation_rates["enable"] = EnableMutationChance
genome.mutation_rates["disable"] = DisableMutationChance
genome.mutation_rates["step"] = StepSize
return genome
end
function copy_gene(gene)
local gene2 = new_gene()
gene2.into = gene.into
gene2.out = gene.out
gene2.weight = gene.weight
gene2.enabled = gene.enabled
gene2.innovation = gene.innovation
return gene2
end
function new_gene()
local gene = {}
gene.into = 0
gene.out = 0
gene.weight = 0.0
gene.enabled = true
gene.innovation = 0
return gene
end
function new_neuron()
local neuron = {}
neuron.incoming = {}
neuron.value = 0.0
return neuron
end
function generate_network(genome)
local network = {}
network.neurons = {}
for i = 1, Inputs do
network.neurons[i] = new_neuron()
end
for o = 1, Outputs do
network.neurons[MaxNodes + o] = new_neuron()
end
table.sort(genome.genes, function(a, b)
return (a.out < b.out)
end)
for i = 1, #genome.genes do
local gene = genome.genes[i]
if gene.enabled then
if network.neurons[gene.out] == nil then
network.neurons[gene.out] = new_neuron()
end
local neuron = network.neurons[gene.out]
table.insert(neuron.incoming, gene)
if network.neurons[gene.into] == nil then
network.neurons[gene.into] = new_neuron()
end
end
end
genome.network = network
end
function evaluate_network(network, inputs, player_num)
local key = player_num == 1 and "P1" or "P2"
table.insert(inputs, 1)
if #inputs ~= Inputs then
print("Incorrect number of neural network inputs")
print(#inputs)
return {}
end
for i = 1, Inputs do
network.neurons[i].value = inputs[i]
end
for _, neuron in pairs(network.neurons) do
local sum = 0
for j = 1, #neuron.incoming do
local incoming = neuron.incoming[j]
local other = network.neurons[incoming.into]
sum = sum + incoming.weight * other.value
end
if #neuron.incoming > 0 then
neuron.value = sigmoid(sum)
end
end
local outputs = {}
for o = 1, Outputs do
local button = key .. output_buttons[o]
if network.neurons[MaxNodes + o].value > 0 then
outputs[button] = true
else
outputs[button] = false
end
end
return outputs
end
function crossover(g1, g2)
-- Make sure g1 is the higher fitness genome
if g2.fitness > g1.fitness then
local tempg = g1
g1 = g2
g2 = tempg
end
local child = new_genome()
local innovations2 = {}
for i = 1, #g2.genes do
local gene = g2.genes[i]
innovations2[gene.innovation] = gene
end
for i = 1, #g1.genes do
local gene1 = g1.genes[i]
local gene2 = innovations2[gene1.innovation]
if gene2 ~= nil and math.random(2) == 1 and gene2.enabled then
table.insert(child.genes, copy_gene(gene2))
else
table.insert(child.genes, copy_gene(gene1))
end
end
child.maxn_euron = math.max(g1.max_neuron, g2.max_neuron)
for mutation, rate in pairs(g1.mutation_rates) do
child.mutation_rates[mutation] = rate
end
return child
end
function random_neuron(genes, nonInput)
local neurons = {}
if not nonInput then
for i = 1, Inputs do
neurons[i] = true
end
end
for o = 1, Outputs do
neurons[MaxNodes + o] = true
end
for i = 1, #genes do
if (not nonInput) or genes[i].into > Inputs then
neurons[genes[i].into] = true
end
if (not nonInput) or genes[i].out > Inputs then
neurons[genes[i].out] = true
end
end
local count = 0
for _, _ in pairs(neurons) do
count = count + 1
end
local n = math.random(1, count)
for k, v in pairs(neurons) do
n = n - 1
if n == 0 then
return k
end
end
return 0
end
function contains_link(genes, link)
for i = 1, #genes do
local gene = genes[i]
if gene.into == link.into and gene.out == link.out then
return true
end
end
end
-------------
-- Mutations--
-------------
-- Randomly modifies the weigt attributed to a local gene
function point_mutate(genome)
local step = genome.mutation_rates["step"]
for i = 1, #genome.genes do
local gene = genome.genes[i]
if math.random() < PerturbChance then
gene.weight = gene.weight + math.random() * step * 2 - step
else
gene.weight = math.random() * 4 - 2
end
end
end
-- Creates new neuron
function link_mutate(genome, force_bias, net_num)
local neuron1 = random_neuron(genome.genes, false)
local neuron2 = random_neuron(genome.genes, true)
local newLink = new_gene()
if neuron1 <= Inputs and neuron2 <= Inputs then
--Both input nodes
return
end
if neuron2 <= Inputs then
-- Swap output and input
local temp = neuron1
neuron1 = neuron2
neuron2 = temp
end
newLink.into = neuron1
newLink.out = neuron2
if force_bias then
newLink.into = Inputs
end
if contains_link(genome.genes, newLink) then
return
end
newLink.innovation = new_innovation(net_num)
newLink.weight = math.random() * 4 - 2
table.insert(genome.genes, newLink)
end
function node_mutate(genome, net_num)
if #genome.genes == 0 then
return
end
genome.max_neuron = genome.max_neuron + 1
local gene = genome.genes[math.random(1, #genome.genes)]
if not gene.enabled then
return
end
gene.enabled = false
local gene1 = copy_gene(gene)
gene1.out = genome.max_neuron
gene1.weight = 1.0
gene1.innovation = new_innovation(net_num)
gene1.enabled = true
table.insert(genome.genes, gene1)
local gene2 = copy_gene(gene)
gene2.into = genome.max_neuron
gene2.innovation = new_innovation(net_num)
gene2.enabled = true
table.insert(genome.genes, gene2)
end
function enable_disable_mutate(genome, enable)
local candidates = {}
for _, gene in pairs(genome.genes) do
if gene.enabled == not enable then
table.insert(candidates, gene)
end
end
if #candidates == 0 then
return
end
local gene = candidates[math.random(1, #candidates)]
gene.enabled = not gene.enabled
end
function mutate(genome, net_num)
for mutation, rate in pairs(genome.mutation_rates) do
if math.random(1, 2) == 1 then
genome.mutation_rates[mutation] = 0.95 * rate
else
genome.mutation_rates[mutation] = 1.05263 * rate
end
end
if math.random() < genome.mutation_rates["connections"] then
point_mutate(genome)
end
local p = genome.mutation_rates["link"]
while p > 0 do
if math.random() < p then
link_mutate(genome, false, net_num)
end
p = p - 1
end
p = genome.mutation_rates["bias"]
while p > 0 do
if math.random() < p then
link_mutate(genome, true, net_num)
end
p = p - 1
end
p = genome.mutation_rates["node"]
while p > 0 do
if math.random() < p then
node_mutate(genome, net_num)
end
p = p - 1
end