-
-
Notifications
You must be signed in to change notification settings - Fork 988
/
ai_helper.lua
2467 lines (2089 loc) · 97.7 KB
/
ai_helper.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 H = wesnoth.require "helper"
local LS = wesnoth.require "location_set"
local F = wesnoth.require "functional"
local M = wesnoth.map
-- This is a collection of Lua functions used for custom AI development.
-- Note that this is still work in progress with significant changes occurring
-- frequently. Backward compatibility cannot be guaranteed at this time in
-- development releases, but it is of course easily possible to copy a function
-- from a previous release directly into an add-on if it is needed there.
--
-- Invisible units ('viewing_side' and 'ignore_visibility' parameters):
-- With their default settings, the ai_helper functions use the vision a player of
-- the respective side would see, that is, they assume no knowledge of invisible
-- units. This can be influenced with the 'viewing_side' and 'ignore_visibility' parameters,
-- which work in the same way as they do in wesnoth.find_reach() and wesnoth.find_path():
-- - If 'viewing_side' is set, vision for that side is used. It must be set to a valid side number.
-- - If 'ignore_visibility' is set to true, all units on the map are seen and shroud is ignored.
-- This overrides 'viewing_side'.
-- - If neither parameter is given and a function takes a parameter linked to a specific side,
-- such as a side number or a unit, as input, vision of that side is used.
-- - For some functions that take no other side-related input, 'viewing_side' is made a required parameter.
--
-- Path finding:
-- All ai_helper functions disregard shroud for path finding (while still ignoring
-- hidden units correctly) as of Wesnoth 1.13.7. This is consistent with default
-- Wesnoth AI behavior and ensures that Lua AIs, including the Micro AIs, can be
-- used for AI sides with shroud=yes. It is accomplished by using
-- ai_helper.find_path_with_shroud() instead of wesnoth.find_path().
local ai_helper = {}
----- Debugging helper functions ------
function ai_helper.show_messages()
-- Returns true or false (hard-coded). To be used to
-- show messages if in debug mode.
-- Just edit the following line (easier than trying to set WML variable)
local show_messages_flag = false
if wesnoth.game_config.debug then return show_messages_flag end
return false
end
function ai_helper.print_exec()
-- Returns true or false (hard-coded). To be used to
-- show which CA is being executed if in debug mode.
-- Just edit the following line (easier than trying to set WML variable)
local print_exec_flag = false
if wesnoth.game_config.debug then return print_exec_flag end
return false
end
function ai_helper.print_eval()
-- Returns true or false (hard-coded). To be used to
-- show which CA is being evaluated if in debug mode.
-- Just edit the following line (easier than trying to set WML variable)
local print_eval_flag = false
if wesnoth.game_config.debug then return print_eval_flag end
return false
end
function ai_helper.done_eval_messages(start_time, ca_name)
ca_name = ca_name or 'unknown'
local dt = wesnoth.get_time_stamp() / 1000. - start_time
if ai_helper.print_eval() then
ai_helper.print_ts_delta(start_time, ' - Done evaluating ' .. ca_name .. ':')
end
end
function ai_helper.clear_labels()
-- Clear all labels on a map
for x, y in wesnoth.current.map:iter(true) do
wesnoth.label { x = x, y = y, text = "" }
end
end
function ai_helper.put_labels(map, cfg)
-- Take @map (location set) and put label containing 'value' onto the map.
-- Print 'nan' if element exists but is not a number.
-- @cfg: table with optional configuration parameters:
-- - show_coords: (boolean) use hex coordinates as labels instead of value
-- - factor=1: (number) if value is a number, multiply by this factor
-- - keys: (array) if the value to be displayed is a subelement of the LS data,
-- use these keys to access it. For example, if we want to display data[3]
-- set keys = { 3 }, if it's data.arg[3], set keys = { 'arg', 3 }
-- - clear=true: (boolean) if set to 'false', do not clear existing labels
-- - color=nil: (string) the color string to be used for the output
cfg = cfg or {}
local factor = cfg.factor or 1
local clear_labels = cfg.clear
if (clear_labels == nil) then clear_labels = true end
if clear_labels then
ai_helper.clear_labels()
end
map:iter(function(x, y, data)
local out
if cfg.show_coords then
out = x .. ',' .. y
else
if cfg.keys then
for _,key in ipairs(cfg.keys) do data = data[key] end
end
if (type(data) == 'string') then
out = data
else
out = tonumber(data) or 'nan'
end
end
if (type(out) == 'number') then out = out * factor end
wesnoth.label { x = x, y = y, text = out, color = cfg.color }
end)
end
function ai_helper.print_ts(...)
-- Print arguments preceded by a time stamp in seconds
-- Also return that time stamp
local ts = wesnoth.get_time_stamp() / 1000.
local arg = { ... }
arg[#arg+1] = string.format('[ t = %.3f ]', ts)
std_print(table.unpack(arg))
return ts
end
function ai_helper.print_ts_delta(start_time, ...)
-- @start_time: time stamp in seconds as returned by wesnoth.get_time_stamp / 1000.
-- Same as ai_helper.print_ts(), but also adds time elapsed since
-- the time given in the first argument (in seconds)
-- Returns time stamp as well as time elapsed
local ts = wesnoth.get_time_stamp() / 1000.
local delta = ts - start_time
local arg = { ... }
arg[#arg+1] = string.format('[ t = %.3f, dt = %.3f ]', ts, delta)
std_print(table.unpack(arg))
return ts, delta
end
----- AI execution helper functions ------
function ai_helper.is_incomplete_move(check)
if (not check.ok) then
-- Legitimately interrupted moves have the following error codes:
-- E_AMBUSHED = 2005
-- E_FAILED_TELEPORT = 2006,
-- E_NOT_REACHED_DESTINATION = 2007
if (check.status == 2005) or (check.status == 2006) or (check.status == 2007) then
return check.status
end
end
return false
end
function ai_helper.is_incomplete_or_empty_move(check)
if (not check.ok) then
-- Empty moves have the following error code:
-- E_EMPTY_MOVE = 2001
if ai_helper.is_incomplete_move(check) or (check.status == 2001) then
return check.status
end
end
return false
end
function ai_helper.dummy_check_action(gamestate_changed, ok, result, status)
return {
gamestate_changed = gamestate_changed or false,
ok = ok or false,
result = result or 'ai_helper::DUMMY_FAILED_ACTION',
status = status or 99999
}
end
function ai_helper.checked_action_error(action, error_code)
if wesnoth.game_config.debug then
error(action .. ' could not be executed. Error code: ' .. error_code, 3)
end
end
function ai_helper.checked_attack(ai, attacker, defender, weapon)
local check = ai.check_attack(attacker, defender, weapon)
if (not check.ok) then
ai.stopunit_attacks(attacker)
ai_helper.checked_action_error('ai.attack from ' .. attacker.x .. ',' .. attacker.y .. ' to ' .. defender.x .. ',' .. defender.y, check.status .. ' (' .. check.result .. ')')
return check
end
return ai.attack(attacker, defender, weapon)
end
function ai_helper.checked_move_core(ai, unit, x, y, move_type)
local check = ai.check_move(unit, x, y)
if (not check.ok) then
if (not ai_helper.is_incomplete_or_empty_move(check)) then
ai.stopunit_moves(unit)
ai_helper.checked_action_error(move_type .. ' from ' .. unit.x .. ',' .. unit.y .. ' to ' .. x .. ',' .. y, check.status .. ' (' .. check.result .. ')')
return check
end
end
if (move_type == 'ai.move_full') then
return ai.move_full(unit, x, y)
else
return ai.move(unit, x, y)
end
end
function ai_helper.checked_move_full(ai, unit, x, y)
return ai_helper.checked_move_core(ai, unit, x, y, 'ai.move_full')
end
function ai_helper.checked_move(ai, unit, x, y)
return ai_helper.checked_move_core(ai, unit, x, y, 'ai.move')
end
function ai_helper.checked_recruit(ai, unit_type, x, y)
local check = ai.check_recruit(unit_type, x, y)
if (not check.ok) then
ai_helper.checked_action_error('ai.recruit of ' .. unit_type .. ' at ' .. x .. ',' .. y, check.status .. ' (' .. check.result .. ')')
return check
end
return ai.recruit(unit_type, x, y)
end
function ai_helper.checked_stopunit_all(ai, unit)
local check = ai.check_stopunit(unit)
if (not check.ok) then
ai_helper.checked_action_error('ai.stopunit_all of ' .. unit.x .. ',' .. unit.y, check.status .. ' (' .. check.result .. ')')
return check
end
return ai.stopunit_all(unit)
end
function ai_helper.checked_stopunit_attacks(ai, unit)
local check = ai.check_stopunit(unit)
if (not check.ok) then
ai_helper.checked_action_error('ai.stopunit_attacks of ' .. unit.x .. ',' .. unit.y, check.status .. ' (' .. check.result .. ')')
return check
end
return ai.stopunit_attacks(unit)
end
function ai_helper.checked_stopunit_moves(ai, unit)
local check = ai.check_stopunit(unit)
if (not check.ok) then
ai_helper.checked_action_error('ai.stopunit_moves of ' .. unit.x .. ',' .. unit.y, check.status .. ' (' .. check.result .. ')')
return check
end
return ai.stopunit_moves(unit)
end
function ai_helper.robust_move_and_attack(ai, src, dst, target_loc, cfg)
-- Perform a move and/or attack with an AI unit in a way that is robust against
-- unexpected outcomes such as being ambushed or changes caused by WML events.
-- As much as possible, this function also tries to ensure that the gamestate
-- is changed in case an action turns out to be impossible due to such an
-- unexpected outcome.
--
-- Required input parameters:
-- @ai: the Lua ai table
-- @src: current coordinates of the AI unit to be used
-- @dst: coordinates to which the unit should move. This does not have to be
-- different from @src. In fact, the unit does not even need to have moves
-- left, as long as an attack is specified in the latter case. If another
-- AI unit is at @dst, it is moved out of the way.
--
-- Optional parameters:
-- @target_loc: coordinates of the enemy unit to be attacked. If not given, no
-- attack is attempted.
-- @cfg: table with optional configuration parameters:
-- partial_move: By default, this function performs full moves. If this
-- parameter is true, a partial move is done instead.
-- weapon: The number (starting at 1) of the attack weapon to be used.
-- If omitted, the best weapon is automatically selected.
-- all optional parameters for ai_helper.move_unit_out_of_way()
-- Notes:
-- - @src, @dst and @target_loc can be any table (including proxy units) that contains
-- the coordinates of the respective locations using either indices .x/.y or [1]/[2].
-- If both are given, .x/.y takes precedence over [1]/[2].
-- - This function only safeguards AI moves against outcomes that the AI cannot know
-- about, such as hidden units and WML events. It is assumed that the potential
-- move was tested for general feasibility (units are on AI side and have moves
-- left, terrain is passable, etc.) beforehand. If that is not done, it might
-- lead to very undesirable behavior, incl. the CA being blacklisted or even the
-- entire AI turn being ended.
local src_x, src_y = src.x or src[1], src.y or src[2] -- this works with units or locations
local dst_x, dst_y = dst.x or dst[1], dst.y or dst[2]
local unit = wesnoth.units.get(src_x, src_y)
if (not unit) then
return ai_helper.dummy_check_action(false, false, 'robust_move_and_attack::NO_UNIT')
end
-- Getting target at beginning also, in case events mess up things along the way
local target, target_x, target_y
if target_loc then
target_x, target_y = target_loc.x or target_loc[1], target_loc.y or target_loc[2]
target = wesnoth.units.get(target_x, target_y)
if (not target) then
return ai_helper.dummy_check_action(false, false, 'robust_move_and_attack::NO_TARGET')
end
end
local gamestate_changed = false
local move_result = ai_helper.dummy_check_action(false, false, 'robust_move_and_attack::NO_ACTION')
if (unit.moves > 0) then
if (src_x == dst_x) and (src_y == dst_y) then
move_result = ai.stopunit_moves(unit)
-- The only possible failure modes are non-recoverable (such as E_NOT_OWN_UNIT)
if (not move_result.ok) then return move_result end
if (not unit) or (not unit.valid) then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::UNIT_DISAPPEARED')
end
gamestate_changed = true
else
local unit_old_moves = unit.moves
local unit_in_way = wesnoth.units.get(dst_x, dst_y)
if unit_in_way and (unit_in_way.side == wesnoth.current.side) and (unit_in_way.moves > 0) then
local uiw_old_moves = unit_in_way.moves
ai_helper.move_unit_out_of_way(ai, unit_in_way, cfg)
if (not unit_in_way) or (not unit_in_way.valid) then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::UNIT_IN_WAY_DISAPPEARED')
end
-- Failed move out of way: abandon remaining actions
if (unit_in_way.x == dst_x) and (unit_in_way.y == dst_y) then
if (unit_in_way.moves == uiw_old_moves) then
-- Forcing a gamestate change, if necessary
ai.stopunit_moves(unit_in_way)
end
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::UNIT_IN_WAY_EMPTY_MOVE')
end
-- Check whether dst hex is free now (an event could have done something funny)
local unit_in_way = wesnoth.units.get(dst_x, dst_y)
if unit_in_way then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::ANOTHER_UNIT_IN_WAY')
end
gamestate_changed = true
end
if (not unit) or (not unit.valid) or (unit.x ~= src_x) or (unit.y ~= src_y) then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::UNIT_DISAPPEARED')
end
local check_result = ai.check_move(unit, dst_x, dst_y)
if (not check_result.ok) then
if (not ai_helper.is_incomplete_or_empty_move(check_result)) then
if (not gamestate_changed) then
ai.stopunit_moves(unit)
end
return check_result
end
end
if cfg and cfg.partial_move then
move_result = ai.move(unit, dst_x, dst_y)
else
move_result = ai.move_full(unit, dst_x, dst_y)
end
if (not move_result.ok) then return move_result end
if (not unit) or (not unit.valid) then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::UNIT_DISAPPEARED')
end
-- Failed move: abandon rest of actions
if (unit.x == src_x) and (unit.y == src_y) then
if (not gamestate_changed) and (unit.moves == unit_old_moves) then
-- Forcing a gamestate change, if necessary
ai.stopunit_moves(unit)
end
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::UNPLANNED_EMPTY_MOVE')
end
gamestate_changed = true
end
end
-- Tests after the move, before continuing to attack, to ensure WML events
-- did not do something funny
if (not unit) or (not unit.valid) then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::UNIT_DISAPPEARED')
end
if (unit.x ~= dst_x) or (unit.y ~= dst_y) then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::UNIT_NOT_AT_DESTINATION')
end
-- In case all went well and there's no attack to be done
if (not target_x) then return move_result end
if (not target) or (not target.valid) then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::TARGET_DISAPPEARED')
end
if (target.x ~= target_x) or (target.y ~= target_y) then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::TARGET_MOVED')
end
local weapon = cfg and cfg.weapon
local old_attacks_left = unit.attacks_left
local check_result = ai.check_attack(unit, target, weapon)
if (not check_result.ok) then
if (not gamestate_changed) then
ai.stopunit_all(unit)
end
return check_result
end
move_result = ai.attack(unit, target, weapon)
-- This should not happen, given that we just checked, but just in case
if (not move_result.ok) then return move_result end
if (not unit) or (not unit.valid) then
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::UNIT_DISAPPEARED')
end
if (unit.attacks_left == old_attacks_left) and (not gamestate_changed) then
ai.stopunit_all(unit)
return ai_helper.dummy_check_action(true, false, 'robust_move_and_attack::NO_ATTACK')
end
return move_result
end
----- General functionality and maths helper functions ------
ai_helper.filter = wesnoth.deprecate_api('ai_helper.filter', 'functional.filter', 3, '1.17.0', F.filter)
ai_helper.choose = wesnoth.deprecate_api('ai_helper.choose', 'functional.filter', 3, '1.17.0', F.choose)
function ai_helper.table_copy(t)
-- Make a copy of a table (rather than just another pointer to the same table)
local copy = {}
for k,v in pairs(t) do copy[k] = v end
return copy
end
function ai_helper.array_merge(a1, a2)
-- Merge two arrays without overwriting @a1 or @a2 -> create a new table
-- This only works with arrays, not general tables
local merger = {}
for _,a in pairs(a1) do table.insert(merger, a) end
for _,a in pairs(a2) do table.insert(merger, a) end
return merger
end
function ai_helper.serialize(input)
-- Convert @input to a string in a format corresponding to the type of @input
-- The string is all put into one line
local str = ''
if (type(input) == "number") or (type(input) == "boolean") then
str = tostring(input)
elseif type(input) == "string" then
str = string.format("%q", input)
elseif type(input) == "table" then
str = str .. "{ "
for k,v in pairs(input) do
str = str .. "[" .. ai_helper.serialize(k) .. "] = "
str = str .. ai_helper.serialize(v)
str = str .. ", "
end
str = str .. "}"
else
error("cannot serialize a " .. type(input), 2)
end
return str
end
function ai_helper.split(str, sep)
-- Split string @str into a table using the delimiter @sep (default: ',')
local sep, fields = sep or ",", {}
local pattern = string.format("([^%s]+)", sep)
string.gsub(str, pattern, function(c) fields[#fields+1] = c end)
return fields
end
--------- Location set related helper functions ----------
function ai_helper.get_LS_xy(index)
-- Get the x,y coordinates for the index of a location set
-- For some reason, there doesn't seem to be a LS function for this
local tmp_set = LS.create()
tmp_set.values[index] = 1
local xy = tmp_set:to_pairs()[1]
return xy[1], xy[2]
end
--------- Location, position or hex related helper functions ----------
function ai_helper.cartesian_coords(x, y)
-- Converts coordinates from hex geometry to cartesian coordinates,
-- meaning that y coordinates are offset by 0.5 every other hex
-- Example: (1,1) stays (1,1) and (3,1) remains (3,1), but (2,1) -> (2,1.5) etc.
return x, y + ((x + 1) % 2) / 2.
end
function ai_helper.get_angle(from_hex, to_hex)
-- Returns the angle of the direction from @from_hex to @to_hex
-- Angle is in radians and goes from -pi to pi. 0 is toward east.
-- Input hex tables can be of form { x, y } or { x = x, y = y }, which
-- means that it is also possible to pass a unit table
local x1, y1 = from_hex.x or from_hex[1], from_hex.y or from_hex[2]
local x2, y2 = to_hex.x or to_hex[1], to_hex.y or to_hex[2]
local _, y1cart = ai_helper.cartesian_coords(x1, y1)
local _, y2cart = ai_helper.cartesian_coords(x2, y2)
return math.atan(y2cart - y1cart, x2 - x1)
end
function ai_helper.get_direction_index(from_hex, to_hex, n, center_on_east)
-- Returns an integer index for the direction from @from_hex to @to_hex
-- with the full circle divided into @n slices
-- 1 is always to the east, with indices increasing clockwise
-- Input hex tables can be of form { x, y } or { x = x, y = y }, which
-- means that it is also possible to pass a unit table
--
-- Optional input:
-- @center_on_east (false): boolean. By default, the eastern direction is the
-- northern border of the first slice. If this parameter is set, east will
-- instead be the center direction of the first slice
local d_east = 0
if center_on_east then d_east = 0.5 end
local angle = ai_helper.get_angle(from_hex, to_hex)
local index = math.floor((angle / math.pi * n/2 + d_east) % n ) + 1
return index
end
function ai_helper.get_cardinal_directions(from_hex, to_hex)
local dirs = { "E", "S", "W", "N" }
return dirs[ai_helper.get_direction_index(from_hex, to_hex, 4, true)]
end
function ai_helper.get_intercardinal_directions(from_hex, to_hex)
local dirs = { "E", "SE", "S", "SW", "W", "NW", "N", "NE" }
return dirs[ai_helper.get_direction_index(from_hex, to_hex, 8, true)]
end
function ai_helper.get_hex_facing(from_hex, to_hex)
local dirs = { "se", "s", "sw", "nw", "n", "ne" }
return dirs[ai_helper.get_direction_index(from_hex, to_hex, 6)]
end
function ai_helper.find_opposite_hex_adjacent(hex, center_hex)
-- Find the hex that is opposite of @hex with respect to @center_hex
-- Both input hexes are of format { x, y }
-- Output: {opp_x, opp_y} -- or nil if @hex and @center_hex are not adjacent
-- (or no opposite hex is found, e.g. for hexes on border)
-- If the two input hexes are not adjacent, return nil
if (M.distance_between(hex[1], hex[2], center_hex[1], center_hex[2]) ~= 1) then return nil end
-- Finding the opposite x position is easy
local opp_x = center_hex[1] + (center_hex[1] - hex[1])
-- y is slightly more tricky, because of the hexagonal shape, but there's a trick
-- that saves us from having to build in a lot of if statements
-- Among the adjacent hexes, it is the one with the correct x, and y _different_ from hex[2]
for xa,ya in H.adjacent_tiles(center_hex[1], center_hex[2]) do
if (xa == opp_x) and (ya ~= hex[2]) then return { xa, ya } end
end
return nil
end
function ai_helper.find_opposite_hex(hex, center_hex)
-- Find the hex that is opposite of @hex with respect to @center_hex
-- Using "square coordinate" method by JaMiT
-- Note: this also works for non-adjacent hexes, but might return hexes that are not on the map!
-- Both input hexes are of format { x, y }
-- Output: { opp_x, opp_y }
-- Finding the opposite x position is easy
local opp_x = center_hex[1] + (center_hex[1] - hex[1])
-- Going to "square geometry" for y coordinate
local y_sq = hex[2] * 2 - (hex[1] % 2)
local yc_sq = center_hex[2] * 2 - (center_hex[1] % 2)
-- Now the same equation as for x can be used for y
local opp_y = yc_sq + (yc_sq - y_sq)
opp_y = math.floor((opp_y + 1) / 2)
return {opp_x, opp_y}
end
function ai_helper.is_opposite_adjacent(hex1, hex2, center_hex)
-- Returns true if @hex1 and @hex2 are opposite from each other with respect to @center_hex
local opp_hex = ai_helper.find_opposite_hex_adjacent(hex1, center_hex)
if opp_hex and (opp_hex[1] == hex2[1]) and (opp_hex[2] == hex2[2]) then return true end
return false
end
function ai_helper.get_named_loc_xy(param_core, cfg, required_for)
-- Get coordinates for either a named location or from x/y coordinates specified
-- in @cfg. The location can be provided:
-- - as name: cfg[param_core .. '_loc'] (string)
-- - or as coordinates: cfg[param_core .. '_x'] and cfg[param_core .. '_y'] (integers)
-- This is the syntax used by many Micro AIs.
-- Exception to this variable name syntax: if param_core = '', then the location
-- variables are 'location_id', 'x' and 'y'
--
-- Error messages are displayed if the named location does not exist, or if
-- the coordinates are not on the map. In addition, if @required_for (a string)
-- is provided, an error message is also displayed if neither a named location
-- nor both coordinates are provided. If @required_for is not passed and neither
-- input exists, nil is returned.
local param_loc = 'location_id'
if (param_core ~= '') then param_loc = param_core .. '_loc' end
local loc_id = cfg[param_loc]
if loc_id then
local loc = wesnoth.special_locations[loc_id]
if loc then
return loc
else
wml.error("Named location does not exist: " .. loc_id)
end
end
local param_x, param_y = 'x', 'y'
if (param_core ~= '') then param_x, param_y = param_core .. '_x', param_core .. '_y' end
local x, y = cfg[param_x], cfg[param_y]
if x and y then
if not wesnoth.current.map:on_board(x, y) then
wml.error("Location is not on map: " .. param_x .. ',' .. param_y .. ' = ' .. x .. ',' .. y)
end
return { x, y }
end
if required_for then
wml.error(required_for .. " requires either " .. param_loc .. "= or " .. param_x .. "/" .. param_y .. "= keys")
end
end
function ai_helper.get_multi_named_locs_xy(param_core, cfg, required_for)
-- Same as ai_helper.get_named_loc_xy, except that it takes comma separated
-- lists of locations.
-- The result is returned as an array of locations.
-- Empty table is returned if no locations are found.
local locs = {}
local param_loc = 'location_id'
if (param_core ~= '') then param_loc = param_core .. '_loc' end
local cfg_loc = cfg[param_loc]
if cfg_loc then
local loc_ids = ai_helper.split(cfg_loc, ",")
for _,loc_id in ipairs(loc_ids) do
local tmp_cfg = {}
tmp_cfg[param_loc] = loc_id
local loc = ai_helper.get_named_loc_xy(param_core, tmp_cfg)
table.insert(locs, loc)
end
return locs
end
local param_x, param_y = 'x', 'y'
if (param_core ~= '') then param_x, param_y = param_core .. '_x', param_core .. '_y' end
local cfg_x, cfg_y = cfg[param_x], cfg[param_y]
if cfg_x and cfg_y then
local xs = ai_helper.split(cfg_x, ",")
local ys = ai_helper.split(cfg_y, ",")
if (#xs ~= #ys) then
wml.error("Coordinate lists need to have same number of elements: " .. param_x .. ' and ' .. param_y)
end
for i,x in ipairs(xs) do
local tmp_cfg = {}
tmp_cfg[param_x] = tonumber(x)
tmp_cfg[param_y] = tonumber(ys[i])
local loc = ai_helper.get_named_loc_xy(param_core, tmp_cfg)
table.insert(locs, loc)
end
return locs
end
if required_for then
wml.error(required_for .. " requires either " .. param_loc .. "= or " .. param_x .. "/" .. param_y .. "= keys")
end
return locs
end
function ai_helper.get_locations_no_borders(location_filter)
-- Returns the same locations array as wesnoth.map.find(location_filter),
-- but excluding hexes on the map border.
--
-- This is faster than alternative methods, at least with the current
-- implementation of standard location filter evaluation by the engine.
-- Note that this might not work if @location_filter is a vconfig object.
local old_include_borders = location_filter.include_borders
location_filter.include_borders = false
local locs = wesnoth.map.find(location_filter)
location_filter.include_borders = old_include_borders
return locs
end
function ai_helper.get_closest_location(hex, location_filter, unit)
-- Get the location closest to @hex (in format { x, y })
-- that matches @location_filter (in WML table format)
-- @unit can be passed as an optional third parameter, in which case the
-- terrain needs to be passable for that unit
-- Returns nil if no terrain matching the filter was found
-- Find the maximum distance from 'hex' that's possible on the map
local max_distance = 0
local map = wesnoth.current.map
local to_top_left = M.distance_between(hex[1], hex[2], 0, 0)
if (to_top_left > max_distance) then max_distance = to_top_left end
local to_top_right = M.distance_between(hex[1], hex[2], map.width-1, 0)
if (to_top_right > max_distance) then max_distance = to_top_right end
local to_bottom_left = M.distance_between(hex[1], hex[2], 0, map.height-1)
if (to_bottom_left > max_distance) then max_distance = to_bottom_left end
local to_bottom_right = M.distance_between(hex[1], hex[2], map.width-1, map.height-1)
if (to_bottom_right > max_distance) then max_distance = to_bottom_right end
-- If the hex is supposed to be passable for a unit, it cannot be on the map border
local include_borders
if unit then include_borders = 'no' end
local radius = 0
while (radius <= max_distance) do
local loc_filter = {}
if (radius == 0) then
loc_filter = {
{ "and", { x = hex[1], y = hex[2], include_borders = include_borders, radius = radius } },
{ "and", location_filter }
}
else
loc_filter = {
{ "and", { x = hex[1], y = hex[2], include_borders = include_borders, radius = radius } },
{ "not", { x = hex[1], y = hex[2], radius = radius - 1 } },
{ "and", location_filter }
}
end
local locs = wesnoth.map.find(loc_filter)
local map = wesnoth.current.map
if unit then
for _,loc in ipairs(locs) do
local movecost = unit:movement(map[loc])
if (movecost <= unit.max_moves) then return loc end
end
else
if locs[1] then return locs[1] end
end
radius = radius + 1
end
return nil
end
function ai_helper.get_passable_locations(location_filter, unit)
-- Finds all locations matching @location_filter that are passable for
-- @unit. This also excludes hexes on the map border.
-- @unit is optional: if omitted, all hexes matching the filter, but
-- excluding border hexes are returned
-- All hexes that are not on the map border
local all_locs = ai_helper.get_locations_no_borders(location_filter)
local map = wesnoth.current.map
-- If @unit is provided, exclude terrain that's impassable for the unit
if unit then
local locs = {}
for _,loc in ipairs(all_locs) do
local movecost = unit:movement(map[loc])
if (movecost <= unit.max_moves) then table.insert(locs, loc) end
end
return locs
end
return all_locs
end
function ai_helper.get_healing_locations(location_filter)
-- Finds all locations matching @location_filter that provide healing, excluding border hexes.
local all_locs = ai_helper.get_locations_no_borders(location_filter)
local map = wesnoth.current.map
local locs = {}
for _,loc in ipairs(all_locs) do
if wesnoth.get_terrain_info(map[loc]).healing > 0 then
table.insert(locs, loc)
end
end
return locs
end
function ai_helper.distance_map(units, map)
-- Get the distance map DM for all units in @units (as a location set)
-- DM = sum ( distance_from_unit )
-- This is done for all elements of @map (a locations set), or for the entire map if @map is not given
local DM = LS.create()
if map then
map:iter(function(x, y, data)
local dist = 0
for _,unit in ipairs(units) do
dist = dist + M.distance_between(unit, x, y)
end
DM:insert(x, y, dist)
end)
else
for x, y in wesnoth.current.map:iter() do
local dist = 0
for _,unit in ipairs(units) do
dist = dist + M.distance_between(unit, x, y)
end
DM:insert(x, y, dist)
end
end
return DM
end
function ai_helper.inverse_distance_map(units, map)
-- Get the inverse distance map IDM for all units in @units (as a location set)
-- IDM = sum ( 1 / (distance_from_unit+1) )
-- This is done for all elements of @map (a locations set), or for the entire map if @map is not given
local IDM = LS.create()
if map then
map:iter(function(x, y, data)
local dist = 0
for _,unit in ipairs(units) do
dist = dist + 1. / (M.distance_between(unit, x, y) + 1)
end
IDM:insert(x, y, dist)
end)
else
for x, y in wesnoth.current.map:iter() do
local dist = 0
for _,unit in ipairs(units) do
dist = dist + 1. / (M.distance_between(unit, x, y) + 1)
end
IDM:insert(x, y, dist)
end
end
return IDM
end
function ai_helper.generalized_distance(x1, y1, x2, y2)
-- Determines distance of (@x1,@y1) from (@x2,@y2) even if
-- @x2 and @y2 are not necessarily both given (or not numbers)
-- Return 0 if neither is given
if (not x2) and (not y2) then return 0 end
-- If only one of the parameters is set
if (not x2) then return math.abs(y1 - y2) end
if (not y2) then return math.abs(x1 - x2) end
-- Otherwise, return standard distance
return M.distance_between(x1, y1, x2, y2)
end
function ai_helper.xyoff(x, y, ori, hex)
-- Finds hexes at a certain offset from @x,@y
-- @ori: direction/orientation: north (0), ne (1), se (2), s (3), sw (4), nw (5)
-- @hex: string for the hex to be queried. Possible values:
-- 's': self, 'u': up, 'lu': left up, 'ld': left down, 'ru': right up, 'rd': right down
-- This is all relative "looking" in the direction of 'ori'
-- returns x,y for the queried hex
wesnoth.deprecated_message('ai_helper.xyoff', 3, '1.17.0', "Use of ai_helper.xyoff is deprecated. There is no replacement as this is not a generally useful function, but equivalent results can be obtained with combinations of the wesnoth.map functions.")
-- Unlike Lua default, we count 'ori' from 0 (north) to 5 (nw), so that modulo operator can be used
ori = ori % 6
if (hex == 's') then return x, y end
-- This is all done with ifs, to keep it as fast as possible
if (ori == 0) then -- "north"
if (hex == 'u') then return x, y-1 end
if (hex == 'd') then return x, y+1 end
local dy = 0
if (x % 2) == 1 then dy=1 end
if (hex == 'lu') then return x-1, y-dy end
if (hex == 'ld') then return x-1, y+1-dy end
if (hex == 'ru') then return x+1, y-dy end
if (hex == 'rd') then return x+1, y+1-dy end
end
if (ori == 1) then -- "north-east"
local dy = 0
if (x % 2) == 1 then dy=1 end
if (hex == 'u') then return x+1, y-dy end
if (hex == 'd') then return x-1, y+1-dy end
if (hex == 'lu') then return x, y-1 end
if (hex == 'ld') then return x-1, y-dy end
if (hex == 'ru') then return x+1, y+1-dy end
if (hex == 'rd') then return x, y+1 end
end
if (ori == 2) then -- "south-east"
local dy = 0
if (x % 2) == 1 then dy=1 end
if (hex == 'u') then return x+1, y+1-dy end
if (hex == 'd') then return x-1, y-dy end
if (hex == 'lu') then return x+1, y-dy end
if (hex == 'ld') then return x, y-1 end
if (hex == 'ru') then return x, y+1 end
if (hex == 'rd') then return x-1, y+1-dy end
end
if (ori == 3) then -- "south"
if (hex == 'u') then return x, y+1 end
if (hex == 'd') then return x, y-1 end
local dy = 0
if (x % 2) == 1 then dy=1 end
if (hex == 'lu') then return x+1, y+1-dy end
if (hex == 'ld') then return x+1, y-dy end
if (hex == 'ru') then return x-1, y+1-dy end
if (hex == 'rd') then return x-1, y-dy end
end
if (ori == 4) then -- "south-west"
local dy = 0
if (x % 2) == 1 then dy=1 end
if (hex == 'u') then return x-1, y+1-dy end
if (hex == 'd') then return x+1, y-dy end
if (hex == 'lu') then return x, y+1 end
if (hex == 'ld') then return x+1, y+1-dy end
if (hex == 'ru') then return x-1, y-dy end
if (hex == 'rd') then return x, y-1 end
end
if (ori == 5) then -- "north-west"
local dy = 0
if (x % 2) == 1 then dy=1 end
if (hex == 'u') then return x-1, y-dy end
if (hex == 'd') then return x+1, y+1-dy end
if (hex == 'lu') then return x-1, y+1-dy end
if (hex == 'ld') then return x, y+1 end
if (hex == 'ru') then return x, y-1 end
if (hex == 'rd') then return x+1, y-dy end
end
return
end
function ai_helper.split_location_list_to_strings(list)
-- Convert a list of locations @list as returned by wesnoth.map.find into a pair of strings
-- suitable for passing in as x,y coordinate lists to wesnoth.map.find.
-- Could alternatively convert to a WML table and use the find_in argument, but this is simpler.
local locsx, locsy = {}, {}
for i,loc in ipairs(list) do
locsx[i] = loc[1]
locsy[i] = loc[2]