/
FieldBOT.java
1523 lines (1333 loc) · 52.6 KB
/
FieldBOT.java
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
/*
Copyright (c) 2014 PlayerO1, https://github.com/playerO1
This class has been rewritten from NullOOJavaAI Copyright (c) 2008 Robin Vobruba <hoijui.quaero@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
New version FieldBot September 2018 for Spring 104.
*/
package fieldbot;
import fieldbot.AIUtil.CPULoadTimer;
import com.springrts.ai.AI;
import com.springrts.ai.oo.AIFloat3;
import com.springrts.ai.oo.OOAI;
import com.springrts.ai.oo.clb.*;
import fieldbot.AIUtil.MathPoints;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.*;
import com.json.parsers.JSONParser; // For ZeroK LUA message
import com.json.parsers.JsonParserFactory;
/**
* Serves as Interface for a Java Skirmish AIs for the Spring engine.
*
* @author hoijui - author of NullOOAI, rewrite to FieldBOT by PlayerO1
*/
public class FieldBOT extends OOAI implements AI {
private static class MyCustomLogFormatter extends Formatter {
private DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSS dd.MM.yyyy");
public String format(LogRecord record) {
// Create a StringBuffer to contain the formatted record
// start with the date.
StringBuffer sb = new StringBuffer();
// Get the date from the LogRecord and add it to the buffer
Date date = new Date(record.getMillis());
sb.append(dateFormat.format(date));
sb.append(" ");
// Get the level name and add it to the buffer
sb.append(record.getLevel().getName());
sb.append(": ");
// Get the formatted message (includes localization
// and substitution of paramters) and add it to the buffer
sb.append(formatMessage(record));
sb.append("\n");
return sb.toString();
}
}
private static void logProperties(Logger log, Level level, Properties props) {
log.log(level, "properties (items: " + props.size() + "):");
for (String key : props.stringPropertyNames()) log.log(level, key + " = " + props.getProperty(key));
}
private int skirmishAIId = -1;
protected int teamId = -1;
private Properties info = null;
private Properties optionValues = null;
public OOAICallback clb = null;
private String myLogFile = null;
private Logger log = null;
private static final int DEFAULT_ZONE = 0; // ????
public int currentFrime=-1; // Game frime
public CPULoadTimer cpuTimer; // for check CPU usage
/**
* Init
*/
public FieldBOT() {
cpuTimer=new CPULoadTimer();
}
// Message level
public static final int MSG_DBG_ALL=4;
public static final int MSG_DBG_SHORT=3;
public static final int MSG_ERR=2;
public static final int MSG_DLG=1;
public static final int MSG_NOSHOW=0;
protected static int LOG_level_show=MSG_ERR; // in game message log level
/**
* Send message to chat and to log file
* @param msg text
* @param msgShowLvl MSG_DBG_ALL, MSG_DBG_SHORT, MSG_ERR, MSG_DLG. It is only for chat, check with LOG_level_show. All message write in log file.
* @return 0 - success, -1 - fail
*/
public int sendTextMsg(String msg, int msgShowLvl) {
try {
if (msgShowLvl<=LOG_level_show) clb.getGame().sendTextMessage(msg, DEFAULT_ZONE);
log.info(msg);
} catch (Exception ex) {
ex.printStackTrace();
return -1;
}
return 0;
}
/**
* Print next message to chat and log file:
* ERROR %comment%, exception: e.toString()
* STACK TRACE> ... stacktrake lines
* @param comment method name, or other small comment
* @param e exception
*/
private void printStackTrakeToChat(String comment, Exception e) {
sendTextMsg("ERROR "+comment+", exception: "+e.toString(), MSG_ERR);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
sendTextMsg(" STACK TRACE> "+sw.toString(), MSG_ERR);
}
public boolean isDebugging() {
return true;
}
// ---------
public String botShortName;
//protected ArrayList<TBase> bases; // TODO ПЕРЕДЕЛАТЬ в AGroupManager. Было: Список баз.
protected ArrayList<AGroupManager> smartGroups=new ArrayList<AGroupManager>();
private ArrayList<AGroupManager> smartGroupsToRemove; // temp list for remove from cycle.
/**
* Average resource info
*/
public AdvECO avgEco;
public TEcoStrategy ecoStrategy;
public TWarStrategy warStrategy;
public ModSpecification modSpecific;
public EnvironmentInterface environmentInterface;
public TBOTTalking talkingDialogModule;
public TScoutModule scoutModule;
/**
* List of dead or sharing to other team units. Bot do not action with this list.
*/
protected ArrayList<Unit> deadLstUnit;
/**
* List of having commanders.
* TODO use it.
*/
protected ArrayList<Unit> commanders;
/**
* List of TechLevel (key) and unit count of this level (value)
*/
protected HashMap<Integer,Integer> techLevels; // TODO what better that HashMap for Integer?
public static final int IS_METAL_FIELD=1;
public static final int IS_NO_METAL=-1;
public static final int IS_NORMAL_METAL=0;
/**
* Metal map type
* -1 no metal map
* 0 normal map with metal spots
* 1 metal field - metal on all area
* (error init = -2)
*/
public int isMetalFieldMap=-2;
/**
* Use class TechUpTrigger for smart tech up process.
* 0 - fast
* 1 - smart, required some CPU time
* 2 - expert (better that smart, required more CPU)
*/
public int useTechUpMode;
private TechUpTrigger techUpTrigger;
/**
* Class for planing base square (ABasePlaning).
* 0 random
* 1 spiral
* 2 circle
* 3 tetris
*/
public int defauldBasePlaning=1;
/**
* Do automatic tech up. Or by text chat command "bot do tech up!"
*/
public boolean autoTechUp=true;
// ---------
@Override
public int init(int skirmishAIId, OOAICallback callback) {
cpuTimer.start();
int ret = -1;
this.skirmishAIId = skirmishAIId;
this.clb = callback;
this.teamId = clb.getSkirmishAI().getTeamId();
this.botShortName="bot";// ??? !!!
info = new Properties();
Info inf = clb.getSkirmishAI().getInfo();
int numInfo = inf.getSize();
for (int i = 0; i < numInfo; i++) {
String key = inf.getKey(i);
String value = inf.getValue(i);
info.setProperty(key, value);
if (key.equals("shortName")) this.botShortName=value;
}
// initialize the log
try {
myLogFile = callback.getDataDirs().allocatePath("log-team-" + teamId + ".txt", true, true, false, false);
FileHandler fileLogger = new FileHandler(myLogFile, false);
fileLogger.setFormatter(new MyCustomLogFormatter());
fileLogger.setLevel(Level.ALL);
log = Logger.getLogger("fieldbot");
log.addHandler(fileLogger);
if (isDebugging()) {
log.setLevel(Level.ALL);
} else {
log.setLevel(Level.INFO);
}
} catch (Exception ex) {
System.err.println("Field BOT: Failed initializing the logger!");
ex.printStackTrace();
ret = -2;
}
short opt_talkingDialogModule_allowEnemyTeamCommand=0;
short opt_armyControl=0;
try {
optionValues = new Properties();
OptionValues opVals = clb.getSkirmishAI().getOptionValues();
int numOpVals = opVals.getSize();
for (int i = 0; i < numOpVals; i++) {
String key = opVals.getKey(i);
String value = opVals.getValue(i);
optionValues.setProperty(key, value);
// --- Определение параметров запуска бота ---
if (key.equals("commandbyenemy")) {
if (value.equals("1")) opt_talkingDialogModule_allowEnemyTeamCommand=1;
if (value.equals("0")) opt_talkingDialogModule_allowEnemyTeamCommand=-1;
}
if (key.equals("autotechup")) {
if (value.equals("1")) autoTechUp=true;
if (value.equals("0")) autoTechUp=false;
}
useTechUpMode=0; // default
if (key.equals("smarttechup")) {
if (value.equals("2")) useTechUpMode=2;
if (value.equals("1")) useTechUpMode=1;
if (value.equals("0")) useTechUpMode=0;
}
if (key.equals("usearmy")) {
if (value.equals("1")) opt_armyControl=1;
if (value.equals("0")) opt_armyControl=-1;
}
if (key.equals("messagelevel")) {
try {
int lvl=Integer.parseInt(value);
LOG_level_show=lvl;
} catch (NumberFormatException e) {
//TODO show error.
}
}
if (key.equals("builddecorator")) {
if (value.equals("random")) defauldBasePlaning=0;
if (value.equals("spiral")) defauldBasePlaning=1;
if (value.equals("circle")) defauldBasePlaning=2;
if (value.equals("tetris")) defauldBasePlaning=3;
}
if (key.equals("metaldetect")) {
try {
isMetalFieldMap=Integer.parseInt(value);
} catch (NumberFormatException e) {
//TODO show error.
}
}
// ------
}
} catch (Exception e) {
log.log(Level.WARNING, "Failed read start properties.", e);
//ret = -5;
}
try {
log.info("initializing team " + teamId);
log.log(Level.FINE, "info:");
logProperties(log, Level.FINE, info);
log.log(Level.FINE, "options:");
logProperties(log, Level.FINE, optionValues);
ret = 0;
} catch (Exception ex) {
log.log(Level.SEVERE, "Failed initializing", ex);
ret = -3;
}
//----
smartGroups=new ArrayList<AGroupManager>();
smartGroupsToRemove = new ArrayList<AGroupManager>();
commanders=new ArrayList<Unit>();
techLevels=new HashMap<Integer, Integer>();
int retCode = init2();
if (retCode!=0) ret=retCode;
//----
if(ret!=0) sendTextMsg("ERROR: init return "+ret+";", MSG_ERR);
// init2(); try init into update(); cause Spring hard chash today.
cpuTimer.stop();
return ret;
}
protected boolean init2Done=false;
protected int init2() {
try {
short opt_talkingDialogModule_allowEnemyTeamCommand=0;
short opt_armyControl=0;
// --- Определение параметров запуска бота ---
{
String value;
if ( (value=optionValues.getProperty("commandbyenemy"))!=null) {
if (value.equals("1")) opt_talkingDialogModule_allowEnemyTeamCommand=1;
if (value.equals("0")) opt_talkingDialogModule_allowEnemyTeamCommand=-1;
}
}
if (isMetalFieldMap==-2) checkForMetal(); // test for metal map
modSpecific = new ModSpecification(this);
avgEco = new AdvECO(14, clb, modSpecific); // TODO check more better time for collect information
environmentInterface = new EnvironmentInterface(modSpecific, avgEco, this);
initMetalData(); // init metal data (required know about isMetalFieldMap)
scoutModule = new TScoutModule(this);// TODO maybe this make crash on S94 with NOTALobby?
ecoStrategy = new TEcoStrategy(this);
warStrategy = new TWarStrategy(this);
talkingDialogModule = new TBOTTalking(this);
if (opt_talkingDialogModule_allowEnemyTeamCommand==1) talkingDialogModule.allowEnemyTeamCommand=true;
if (opt_talkingDialogModule_allowEnemyTeamCommand==-1) talkingDialogModule.allowEnemyTeamCommand=false;
if (opt_armyControl==1) warStrategy.makeArmy=true;
if (opt_armyControl==-1) warStrategy.makeArmy=false;
deadLstUnit=new ArrayList<Unit>();
techUpTrigger=null;
// Check human query for start position (DON't WORK!)
AIFloat3 queryStartPoint=talkingDialogModule.checkStartPositionMessage();
if (queryStartPoint!=null) {
sendTextMsg("Command acepted: start at "+queryStartPoint.x+":"+queryStartPoint.z, MSG_DLG);
clb.getGame().sendStartPosition(false, queryStartPoint);
clb.getGame().sendStartPosition(true, queryStartPoint);
// TODO DO NOT WORK! Command acepted, but start on other position. It maybe bug on Spring 94.1. TEst it later.
}
addSmartGroup(new TBase(this, clb.getMap().getStartPos(), 2000)); // Init first base
} catch (Exception e) {
sendTextMsg("ERROR init, exception: "+e.toString(), MSG_ERR);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
sendTextMsg(" STACK TRACE> "+sw.toString(), MSG_ERR);
return -4;
}
init2Done = true;
return 0;
}
@Override
public int release(int reason) {
sendTextMsg("release: reason="+reason, MSG_DBG_SHORT);
return 0; // signaling: OK
}
/**
* Set variable isMetalFieldMap, test map for metal type
*/
public void checkForMetal()
{
Resource metal=clb.getResourceByName("Metal");//Resource.getInstance(clb, 0);
if (metal==null) {
sendTextMsg("Resource Metal not found in MOD!", MSG_ERR);
isMetalFieldMap=-2;// !!!!!!!
return;
}
AIFloat3 metalspot=clb.getMap().getResourceMapSpotsNearest(metal,clb.getMap().getStartPos());
if( !MathPoints.isValidPoint(metalspot) ) // y - высота
{
sendTextMsg("This is a map with no metal spots", MSG_DLG);
isMetalFieldMap=IS_NO_METAL;
}
else // isMetalFieldMap 0 and 1
{
// check for metal field
float dLmax=0.0f,dLavg=0.0f;
final double extractorR=clb.getMap().getExtractorRadius(metal);
final double r=extractorR*7.5;
final int nApprox=10;
AIFloat3 pCenter=clb.getMap().getStartPos();
for (int i=0;i<nApprox;i++) {
AIFloat3 pFind= new AIFloat3(pCenter);
double ang=2*Math.PI * ((double)i/(double)(nApprox+1));
pFind.x+=Math.cos( ang )*r; pFind.z+=Math.sin( ang )*r;
AIFloat3 p=clb.getMap().getResourceMapSpotsNearest(metal,pFind);
sendTextMsg("METAL TEST >pos="+pFind.x+":"+pFind.z+" result k="+p.x+":"+p.z, MSG_DBG_ALL);
float d = MathPoints.getDistanceBetweenFlat(pFind, p);
sendTextMsg(" >d="+d, MSG_DBG_ALL);
if (d>r) d=Math.min(Math.abs(pFind.x-p.x), Math.abs(pFind.z-p.z));// FIXME ??? почему??? но только так на метал. мап работает.
sendTextMsg(" >d fix="+d, MSG_DBG_ALL);
dLmax = Math.max(dLmax, d);
dLavg += d;
}
sendTextMsg("METAL TEST PARAM. pos="+pCenter.x+":"+pCenter.z+" Avg k="+dLavg+" nApprox="+nApprox+" dLmax="+dLmax+" extractorR="+extractorR, MSG_DBG_SHORT);
dLavg = ( dLavg / nApprox + dLmax ) / 2;
if (dLavg<=extractorR*2) {
isMetalFieldMap=IS_METAL_FIELD;
sendTextMsg("This is a map with metal field. Average k="+dLavg, MSG_DLG);
} else {
isMetalFieldMap=IS_NORMAL_METAL;
sendTextMsg("This is a map with normal metal spots. Near Points: "+metalspot.toString(), MSG_DLG);
}
}
}
/**
* Should be call for init metal data.
* Write info to allMetallSpots.
*/
private void initMetalData() {
// Init metal points
if (isMetalFieldMap==IS_METAL_FIELD || isMetalFieldMap==-2) allMetallSpots=null;
else {
Resource metal=clb.getResourceByName("Metal");
if (metal==null) sendTextMsg("Resource Metal not found on this mod for initMetalData()!", MSG_ERR);
if (allMetallSpots==null) allMetallSpots=new ArrayList<AIFloat3>();
else return;// !!!
if (isMetalFieldMap==IS_NORMAL_METAL) { //&& (allMetallSpots==null || allMetallSpots.isEmpty())) {
String modName = modSpecific.modName; // last: clb.getMod().getShortName()
boolean isZKmod=modName.equals("ZK");
// if (!isZKmod) {
// -- by engine --
allMetallSpots=clb.getMap().getResourceMapSpotsPositions(metal);
sendTextMsg("Num of metal point: "+allMetallSpots.size(), MSG_DLG);
// -----
// } else { // MOD SPECIFED FOR Zero-K!
// //TODO metal for Zero-K
// }
}
}
}
private List<AIFloat3> allMetallSpots;
/**
* return point for metal spots in radius.
* @param center
* @param r radius for search
* @return list with metal spots, or empty list if non-metal map or not have metal. Null if it is metal map (-1), or map type is not set (-2).
*/
public ArrayList<AIFloat3> getMetalSpotsInRadius(AIFloat3 center, float r) {
if (isMetalFieldMap==IS_METAL_FIELD || isMetalFieldMap==-2 || allMetallSpots==null) return null;
ArrayList<AIFloat3> mPoints=new ArrayList<AIFloat3>();
if (isMetalFieldMap==IS_NO_METAL) return mPoints;
for (AIFloat3 p:allMetallSpots) if (MathPoints.getDistanceBetweenFlat(center, p)<=r) mPoints.add(p);
return mPoints;
}
/**
* Get unit resource income-usage (can work with LUA metal maker by using modSpecific.getResourceConversionFor(...)).
*
* todo Deprecated: use EnvironmentInterface.getUnitResoureProduct(UnitDef, Resource);
*
* @param def unit type
* @param res resource type
* @return resource incoming (+) or resource using (-)
*/
@Deprecated
public float getUnitResoureProduct(UnitDef def, Resource res) {
return environmentInterface.getUnitResoureProduct(def, res);
}
/**
* Get unit resource income-usage (can work with LUA metal maker by using modSpecific.getResourceConversionFor(...)).
* It work faster that getUnitResoureProduct(UnitDef, Resource) for more that 1 resource item.
* @param def unit type
* @return resource incoming (+) or resource using (-) array for all resources
*/
public float[] getUnitResoureProduct(UnitDef def) {
return environmentInterface.getUnitResoureProduct(def);
}
public float getCost(UnitDef def, Resource res) {
return environmentInterface.getCost(def, res);
}
// ==================================
private boolean inGameInitDone=false; // post-start initialization pass mark
/**
* Execute tech up.
* @param bestLvl - to level
* @param onBase - where base will be do execute this tech up. Maybe null.
* @return tech up execute now - true, or not - false
*/
public boolean doTechUpToLevel(TTechLevel bestLvl, TBase onBase) {
//float t=ecoStrategy.getRashotBuildTimeLst(bestLvl.needBaseBuilders, avgEco.getAVGResourceToArr(), base.getBuildPower(false, true));
//sendTextMsg("Start tech Up from to > time="+t+" level="+bestLvl.toString(), FieldBOT.MSG_DBG_SHORT);
if (onBase==null) { // search base
for (TBase base:selectTBasesList()) {
if (bestLvl.byMorph()) {
if (base.contains(bestLvl.byMorph)) onBase=base;
} else {
HashSet<UnitDef> bBldLst=base.getBuildList(true);
for (UnitDef def:bestLvl.needBaseBuilders) if (bBldLst.contains(def))
{
onBase=base;
break;
}
}
if (onBase!=null) break;
}
}
if (onBase==null) return false;
if (bestLvl.byMorph()) {
// через morph
if (bestLvl.morphTo!=null) sendTextMsg(" Morphing "+bestLvl.byMorph.getDef().getHumanName()+" to "+bestLvl.morphTo.getHumanName(), FieldBOT.MSG_DLG);
else sendTextMsg(" error morphTo (getUnitDefForMprph) is null!", FieldBOT.MSG_ERR);
bestLvl.byMorph.executeCustomCommand(bestLvl.morphCMD.getId(), new ArrayList<Float>(), (short)0, Integer.MAX_VALUE);
for (UnitDef def:bestLvl.needBaseBuilders) if (def!=bestLvl.morphTo) onBase.currentBaseTarget.add(def, 1);
} else {
// простой вариант
for (UnitDef def:bestLvl.needBaseBuilders) onBase.currentBaseTarget.add(def, 1);
}
onBase.currentBaseTarget.needPrecissionRes=true; //!!!
if (techUpTrigger!=null) techUpTrigger=null; //!!!
return true;
}
/**
* Check and do tech up
* @param doEmidetly execute now - do not check time.
* @param test only test- do not execute, only print to chat.
* @return tech up execute now - true, or not - false
*/
public boolean checkAndTechUp(boolean doEmidetly, boolean test) { // TODO ПЕРЕДЕЛАТЬ и доделать!
boolean startTechUp=false;
sendTextMsg("Check for Tech Up level", FieldBOT.MSG_DBG_SHORT);
float currentRes[][];
if (ecoStrategy.useOptimisticResourceCalc) currentRes= avgEco.getSmartAVGResourceToArr();
else currentRes= avgEco.getAVGResourceToArr();
// TODO test. Было getAVGResourceToArr()
for (TBase base:selectTBasesList()) if (base.currentBaseTarget.isEmpty()) {
HashSet<UnitDef> onBaseBuildLst=base.getBuildList(true);
//float currentLvlK=TTechLevel.calcEcoK(base.getBuildList(true), this); // текущий уровень
ArrayList<TTechLevel> TechLvls=TTechLevel.GetAllVariantLevel( base.getContainUnitDefsList(false),onBaseBuildLst ,base, this);
ArrayList<TTechLevel> TechLvlsByMorph=TTechLevel.GetAllVariantLevelByMorph(base.getAllUnits(false), base.getContainUnitDefsList(false),onBaseBuildLst ,base, this);
sendTextMsg(" Tech level by morph count="+TechLvlsByMorph.size(), MSG_DBG_SHORT);
TechLvls.addAll(TechLvlsByMorph);
TTechLevel bestLvl=null;
float bestEco[]=TTechLevel.getMaxResProduct(onBaseBuildLst, this); // текущий уровень
//float bestEcoK=0.0f;
float bestBuilderF=TTechLevel.getMaxBuildPower(onBaseBuildLst);
bestLvl = null;
if ( !doEmidetly ) {
boolean allowTechUp=true;
switch (useTechUpMode) {
case 0:
bestLvl = ecoStrategy.selectLvl_bestForNow(TechLvls, base, bestEco, bestBuilderF, currentRes);
if (bestLvl!=null)
allowTechUp = ecoStrategy.isActualDoTechUp_fastCheck(base, onBaseBuildLst, bestLvl);
else allowTechUp=false;
break;
case 1:
bestLvl = ecoStrategy.selectLvl_bestForNow(TechLvls, base, bestEco, bestBuilderF, currentRes);
if (bestLvl!=null)
techUpTrigger = ecoStrategy.getPrecissionTechUpTimeFor(base, onBaseBuildLst, bestLvl );
else techUpTrigger = null;
if (techUpTrigger!=null) {
sendTextMsg("> "+techUpTrigger.toString(), FieldBOT.MSG_DBG_SHORT);
allowTechUp=techUpTrigger.trigger();
// TODO where remove it tech up was execute?
} else {
sendTextMsg("> tech up trigger is null!", FieldBOT.MSG_DBG_SHORT);
allowTechUp=false;
}
break;
case 2:
//ArrayList<TTechLevel> TechLvls_eco=ecoStrategy.selectLvl_whoBetterThat(TechLvls, bestEco, bestBuilderF); // TODO test, maybe 'selectLvl_whoBetterThat' remove realy better level.
techUpTrigger = ecoStrategy.getAbsolutePrecissionTechUpTimeFor(base, onBaseBuildLst, TechLvls);
if (techUpTrigger!=null) {
sendTextMsg("> "+techUpTrigger.toString(), FieldBOT.MSG_DBG_SHORT);
allowTechUp=techUpTrigger.trigger();
bestLvl=techUpTrigger.level;
} else {
sendTextMsg("> tech up trigger is null!", FieldBOT.MSG_DBG_SHORT);
allowTechUp=false;
}
break;
}
if (!allowTechUp) bestLvl=null;
}
if (bestLvl!=null) { // Execute tech up
float t=ecoStrategy.getRashotBuildTimeLst(bestLvl.needBaseBuilders, avgEco.getAVGResourceToArr(), base.getBuildPower(false, true));
sendTextMsg("Start tech Up from to > time="+t+" level="+bestLvl.toString(), FieldBOT.MSG_DBG_SHORT);
startTechUp=true;
if (!test)
{
startTechUp = doTechUpToLevel(bestLvl,base);
}
}
} else sendTextMsg("Base already have work."+base.toString(), FieldBOT.MSG_DBG_SHORT);
// TODO только на 1 базе.
return startTechUp;
}
public TBase getNearBase(AIFloat3 nearTo) {
TBase nearB=null;
float minL=Float.POSITIVE_INFINITY;
for (TBase base:selectTBasesList()) {
float l=MathPoints.getDistanceBetweenFlat(base.center, nearTo)-base.radius;
if (nearB==null || l<minL) {
minL=l;
nearB=base;
}
}
return nearB;
}
public AGroupManager getNearGroup(AIFloat3 nearTo) {
AGroupManager nearG=null;
float minL=Float.POSITIVE_INFINITY;
for (AGroupManager group:smartGroups) {
AIFloat3 gPos=group.getCenter();
if (gPos!=null) {
float l=MathPoints.getDistanceBetweenFlat(gPos, nearTo);
if (nearG==null || l<minL) {
minL=l;
nearG=group;
}
}
}
return nearG;
}
/**
* Create new base and send to new base constructor unit from all other base.
* @param newBasePoint base center
* @param workerUsagePercent how many workers take from other base to send on new base. Recomended value: 0.1-0.4; if 0 then defauld=2/5.
* @return return new base, or null if failed
*/
public TBase spawnNewBase(AIFloat3 newBasePoint, float workerUsagePercent)
{
// Check on free position from other TBases
TBase otherBase=getNearBase(newBasePoint);
if (otherBase!=null) {
if (MathPoints.getDistanceBetweenFlat(otherBase.getCenter(), newBasePoint) <= otherBase.radius) // TODO plas second radius
return null; // base collision
}
if (workerUsagePercent<=0) workerUsagePercent=2/5;
ArrayList<Unit> shareWorker= new ArrayList<Unit>();
for (TBase base:selectTBasesList()) { // TODO only from bases? Maybe from other group too?
// TODO ...
ArrayList<Unit> baseCons=new ArrayList<Unit>(base.idleCons);
baseCons.addAll(base.workingCons);// !!!
Iterator<Unit> itr1=baseCons.iterator();
while (itr1.hasNext()) {
Unit aCons = itr1.next();
UnitDef cDef=aCons.getDef();
if (!ModSpecification.isRealyAbleToMove(cDef)
|| modSpecific.isCommander(cDef)
|| aCons.isParalyzed()
|| !ModSpecification.isAbleToBuildBase(cDef) // So, they can build new base?
) itr1.remove(); // Если нельзя переместить на новую базу
}
// TODO select only fast unit
if (baseCons.size()>1) {
HashSet<UnitDef> baseCanBuild=base.getBuildList(true);
for (int i=0; i<Math.max(1,baseCons.size()*workerUsagePercent); i++)
{
Unit unit=baseCons.get(i);
base.removeUnit(unit);
shareWorker.add(unit);
UnitDef uDef=unit.getDef(); // Пополнение затрат
if (baseCanBuild.contains(uDef)) base.currentBaseTarget.add(uDef, 1);
}
}
}
if (!shareWorker.isEmpty()) {
TBase newB=new TBase(this, newBasePoint, 0); // 0 - auto size, default = 1000
addSmartGroup(newB);
for (Unit u:shareWorker) { // !!!
newB.addUnit(u); // Добавить и пойти на базу
u.moveTo(MathPoints.getRandomPointOnRadius(newB.center, newB.radius/2), (short)0, Integer.MAX_VALUE); //, DEFAULT_TIMEOUT);
}
newB.setAllAsWorking(shareWorker); // Пока не дойдут пометить как работающих
//sendTextMsg("New base created "+newB.toString()+", "+shareWorker+" units sending to new base.", FieldBOT.MSG_DBG_SHORT);
return newB;
} else {
//sendTextMsg("Can't create base: no enought free unit.", FieldBOT.MSG_DBG_SHORT);
return null;
}
}
/**
* Find base with maximal UnitDefs can build
* @param findWithoutBaseTarget find only idle base
* @return best base, or null
*/
public TBase getBestBase(boolean findWithoutBaseTarget) {
TBase bestBase=null; HashSet<UnitDef> lstOfUDefs=new HashSet<UnitDef>();
for (TBase base:selectTBasesList()) {
HashSet<UnitDef> tmpUDefs=base.getBuildList(true);
if (tmpUDefs.size()>lstOfUDefs.size() &&
(!findWithoutBaseTarget || !base.haveSpecialCommand())) // idle base.
{
bestBase=base;
lstOfUDefs=tmpUDefs;
}
}
return bestBase;
}
/**
* Set group for remove. It is safe for call from cycle FOR and iteratrs. Real removing group from list will be realized on update.
* @param group
*/
public void removeSmartGroup(AGroupManager group) {
if (!smartGroupsToRemove.contains(group)) {
sendTextMsg("Group removing:"+group, FieldBOT.MSG_DBG_SHORT);
smartGroupsToRemove.add(group);
}
}
public void addSmartGroup(AGroupManager group) {
smartGroups.add(group);
//bases.add(group);
}
public AGroupManager getOwnerGroup(Unit unit) {
for (AGroupManager agm:smartGroups) if (agm.contains(unit)) return agm;
return null;
}
/**
* This method call from groups, when they finish some target.
* @param group
*/
public void onGroupTargetFinished(AGroupManager group) {
// TODO onGroupTargetFinished
// send next to Eco and War strategy calls.
}
/**
* Select TBase list from smartGroup list
*/
public ArrayList<TBase> selectTBasesList() {
ArrayList<TBase> basesList=new ArrayList<TBase>();
for (AGroupManager sGroup:smartGroups)
if (sGroup instanceof TBase) basesList.add((TBase)sGroup);
return basesList;
}
protected void init3() {
Mod mod=clb.getMod();
sendTextMsg("MOD info. Name: "+mod.getHumanName()+" short name:"+mod.getShortName()+" version:"+mod.getVersion()+" description:"+mod.getDescription(), MSG_DBG_SHORT);
sendTextMsg("ENGINE: "+clb.getEngine().getVersion().getFull(), MSG_DBG_SHORT);
for (TBase base:selectTBasesList()) base.reinitCenter(); // !!! bug fix with start position for start boxes
// DEBUG: SHOW ALL UNITS INFO!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Печать списка всех юнитов
// sendTextMsg("---- UnitDef list (ALL "+modSpecific.allUnitDefs.size()+") ----", FieldBOT.MSG_DBG_ALL);
// for (UnitDef def:modSpecific.allUnitDefs) {
// sendTextMsg("ID="+def.getUnitDefId()+" "+def.getName()+" ("+def.getHumanName()+") level "+def.getTechLevel()+" isBuilder="+def.isBuilder(), FieldBOT.MSG_DBG_ALL);
// showUnitDefInfoDebug(def); // some other shows
// sendTextMsg("",FieldBOT.MSG_DBG_ALL);
//// if (def.getCustomParams()!=null && !def.getCustomParams().isEmpty()) { //SEGMENTATION FAULED in Spring 96, 94.1
//// sendTextMsg(" CustomParams:", FieldBOT.MSG_DBG_ALL);
//// for (Map.Entry<String, String> params :def.getCustomParams().entrySet()) {
//// sendTextMsg(" K:"+params.getKey()+" V:"+params.getValue(), FieldBOT.MSG_DBG_ALL);
//// }
//// }
// }
// sendTextMsg("---- ----", FieldBOT.MSG_DBG_ALL);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
@Override
public int update(int frame) {
try {
cpuTimer.start();
currentFrime=frame;
if (!init2Done) {
init2();
}
// sendTextMsg("update frame="+frame, MSG_DBG_ALL);
if (!deadLstUnit.isEmpty()) deadLstUnit.clear();
if (!smartGroupsToRemove.isEmpty()) { // TODO test.
for (AGroupManager group:smartGroupsToRemove) { // send units to other groups
List<Unit> freeUnits=group.getAllUnits(false);
// TODO what doing with units?
for (Unit u:freeUnits) addToSameGroup(u);
}
if (smartGroups.removeAll(smartGroupsToRemove)) smartGroupsToRemove.clear();
//TODO don't forget call removeSmartGroup(null) if add some methods/cashes for calling on this function;
}
avgEco.update(frame);
if (!inGameInitDone) {
init3();
inGameInitDone=true;
} else {
talkingDialogModule.update(frame);
scoutModule.update(frame);
// TODO spawn new base, send group for kame mex point if mapType=normal metal map. ecoStrategy.update(frame);
warStrategy.update(frame); // Army control
for (AGroupManager sGroup:smartGroups) sGroup.update(frame);
// --- Zero-K special ---
if (modSpecific.firstFactoryIsFree && frame>20) {
boolean aceptBuildFactory=false;
aceptBuildFactory = checkAndTechUp(true, false);
if (!aceptBuildFactory) {
talkingDialogModule.message(clb.getSkirmishAI().getSkirmishAIId(), "bot make Bot Factory"); // ZK: Gunship Plant, Cloaky Bot Factory, Light Vehicle Factory, Heavy Tank Factory, Amphibious Operations Plant, Shipyard
aceptBuildFactory=true;
//TODO make better!
//TODO checkAntDechUp_armyTechUp()
// TBase bestBase=getBestBase(true);
// if (bestBase!=null) {
// bestBase.
// }
}
if (aceptBuildFactory) modSpecific.firstFactoryIsFree=false;
}
// --- ---
// ======= Test Tech Up ==========
if (autoTechUp){
if (useTechUpMode>0) { // smart tech up
boolean techUpCheckTick=false;
if (frame%1500==1200) {
checkAndTechUp(false, false);
techUpCheckTick=true;
} else if (frame%500==400) {
if (techUpTrigger==null) checkAndTechUp(false, false);
techUpCheckTick=true;
}
if ( techUpCheckTick && techUpTrigger!=null ) {
if (techUpTrigger.trigger()) {
if (doTechUpToLevel(techUpTrigger.level, techUpTrigger.onBase))
techUpTrigger=null;//!!!
}
}
} else { // fast check tech up
if (frame%1000==500)
checkAndTechUp(false, false); // old tech up method, bad time choose.
}
}
// ===============================
}
// sendTextMsg("done update.", MSG_DBG_ALL);
cpuTimer.stop();
} catch (Exception e) {
printStackTrakeToChat("update",e);
cpuTimer.stop();
return -1;
}
return 0; // signaling: OK
}
/**
* Add unit to near base
* @param unit unit without owner base
* @return add to base, or false - not added.
*/
public boolean addToSameGroup(Unit unit) {
sendTextMsg("Unit from uncknown owner base add to base, ... try...", MSG_DBG_ALL);
if (unit.getTeam()!=teamId) { // !!! DEBUG!
sendTextMsg("unit not in AI team!", MSG_DBG_SHORT);
return false;
}
if (deadLstUnit.contains(unit)) {
sendTextMsg("unit in deadLstUnit! Error!", MSG_DBG_SHORT);
return false;
}
// TODO check on dead/sharing list
AGroupManager nearBase=null; float bestK=Float.NEGATIVE_INFINITY;//float bestDist=Float.POSITIVE_INFINITY;
for (AGroupManager sGroup:smartGroups) if (!smartGroupsToRemove.contains(sGroup)) {
//float l = TBase.getDistanceBetween(unit.getPos(), base.center);
float k=sGroup.doYouNeedUnit(unit);
if (k>bestK) {
bestK=k;
nearBase=sGroup;
}
}
if (nearBase!=null) {
sendTextMsg("Unit from uncknown owner base add to base, ... add...", MSG_DBG_ALL);
return nearBase.addUnit(unit);
} else {
sendTextMsg("Base not found for add unit!", MSG_DBG_SHORT);
return false;
}
}
/**
* For register unit, tech level. Only bot unit.
*/
private void onAddUnit(Unit unit) {
if (!unit.isBeingBuilt()) {
UnitDef def=unit.getDef();
if (modSpecific.isCommander(def)) commanders.add(unit);
modSpecific.onAddUnit(def); // TODO show debug message about unlock technology