forked from brikikeks/tyrant_optimize
-
Notifications
You must be signed in to change notification settings - Fork 7
/
tyrant_optimize.cpp
4445 lines (4277 loc) · 160 KB
/
tyrant_optimize.cpp
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
// 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 3 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/>.
//------------------------------------------------------------------------------
// #define NDEBUG
#define BOOST_THREAD_USE_LIB
#ifndef _WIN32
#include <unistd.h>
#else
#include <io.h>
#define F_OK 0
#define access(f, m) _access((f), (m))
#endif
#include <array>
#include <cassert>
#include <chrono>
#include <cstring>
#include <ctime>
#include <functional>
#include <iostream>
#include <map>
#include <unordered_map>
#include <set>
#include <stack>
#include <fstream>
#include <string>
#include <iomanip>
#include <tuple>
#include <vector>
#include <math.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/math/distributions/binomial.hpp>
#include <boost/optional.hpp>
#include <boost/range/join.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <boost/timer/timer.hpp>
#include <boost/tokenizer.hpp>
#include "card.h"
#include "cards.h"
#include "deck.h"
#include "read.h"
#include "sim.h"
#include "tyrant.h"
#include "xml.h"
#include "hPMML.h"
#define DEFINE_GLOBALS
#include "algorithms.h"
// OpenMP Header
#ifdef _OPENMP
#include <omp.h>
#endif
// Android Headers
#if defined(ANDROID) || defined(__ANDROID__)
#include <jni.h>
#include <android/log.h>
#endif
using namespace tuo;
using namespace proc;
// init
/*
namespace tuo {
unsigned opt_num_threads=4;
gamemode_t gamemode{fight};
OptimizationMode optimization_mode{OptimizationMode::notset};
std::unordered_map<unsigned, unsigned> owned_cards;
const Card* owned_alpha_dominion{nullptr};
bool use_owned_cards{true};
bool opt_skip_unclaimed_decks{false};
//bool opt_trim_unclaimed_decks{false};
unsigned min_deck_len{1};
unsigned max_deck_len{10};
unsigned opt_freezed_cards{0};
unsigned freezed_cards{0};
unsigned fund{0};
long double target_score{100};
long double min_increment_of_score{0};
long double confidence_level{0.99};
bool use_top_level_card{true};
bool use_top_level_commander{true};
bool mode_open_the_deck{false};
bool use_owned_dominions{true};
bool use_maxed_dominions{false};
unsigned use_fused_card_level{0};
unsigned use_fused_commander_level{0};
bool print_upgraded{false};
bool print_values{false};
bool simplify_output{false};
bool show_ci{false};
bool use_harmonic_mean{false};
unsigned iterations_multiplier{10};
unsigned sim_seed{0};
unsigned flexible_iter{20};
unsigned flexible_turn{10};
Requirement requirement;
#ifndef NQUEST
Quest quest;
#endif
std::unordered_set<unsigned> allowed_candidates;
std::unordered_set<unsigned> disallowed_candidates;
std::chrono::time_point<std::chrono::system_clock> start_time;
long double maximum_time{0};
//anneal
long double temperature = 1000;
long double coolingRate = 0.001;
//genetic
unsigned generations = 50;
unsigned pool_size = 0;
unsigned min_pool_size = 20;
double opt_pool_keep = 1;
double opt_pool_mutate = 1;
double opt_pool_cross = 1;
//fort_climb
unsigned yfpool{0};
unsigned efpool{0};
std::vector<Faction> factions;
bool invert_factions{false};
bool only_recent{false};
bool prefered_recent{false};
unsigned recent_percent{5};
std::vector<Skill::Skill> skills;
bool invert_skills{false};
std::vector<Skill::Skill> prefered_skills;
unsigned prefered_factor{3};
#if defined(ANDROID) || defined(__ANDROID__)
JNIEnv *envv;
jobject objv;
#endif
}
*/
static const unsigned int crc32_table[] =
{
0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4};
unsigned int
xcrc32(const unsigned char *buf, int len, unsigned int init)
{
unsigned int crc = init;
while (len--)
{
crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
buf++;
}
return crc;
}
unsigned int file_xrcrc32(std::string filename, unsigned int init)
{
std::ifstream file;
file.open(filename);
std::string line;
unsigned int crc = init;
while (getline(file, line))
{
crc = xcrc32((const unsigned char *)line.c_str(), line.length(), crc);
}
return crc;
}
unsigned int checksumcards(std::string prefix)
{
unsigned int crc = 0;
// loop cardsections
unsigned int ii = 1;
crc = file_xrcrc32(prefix + "data/raids.xml", crc);
crc = file_xrcrc32(prefix + "data/missions.xml", crc);
std::string fname = prefix + "data/cards_section_1.xml";
while (access(fname.c_str(), F_OK) == 0)
{
crc = file_xrcrc32(fname, crc);
ii += 1;
fname = prefix + "data/cards_section_" + std::to_string(ii) + ".xml";
}
return crc;
}
void load_ml(std::string prefix)
{
if (use_ml)
{
win_model = hpmml::Model(prefix + "data/win.pmml");
stall_model = hpmml::Model(prefix + "data/stall.pmml");
loss_model = hpmml::Model(prefix + "data/loss.pmml");
points_model = hpmml::Model(prefix + "data/points.pmml");
}
}
// load database map from file
void load_db(std::string prefix)
{
if (use_db_load)
{
_DEBUG_MSG(1, "start loading db\n");
// open file to read from
std::ifstream file;
file.open(prefix + "data/database.yml");
// read map from file
std::string name;
uint64_t wins, draws, losses, points, count;
std::string version, check;
std::string line;
getline(file, line);
if (line.find(":") != std::string::npos)
version = line.substr(line.find(":") + 2);
std::cout << "DB version " << version << std::endl;
getline(file, line);
if (line.find(":") != std::string::npos)
check = line.substr(line.find(":") + 2);
std::cout << "DB checksum " << check << std::endl;
if (use_strict_db)
{
if (version.compare(TYRANT_OPTIMIZER_VERSION) != 0)
{
std::cout << "DB TUO version outdated" << std::endl;
std::cout << "DB TUO version " << version << " != " << TYRANT_OPTIMIZER_VERSION << std::endl;
std::cout << "DB ignoring database.yml" << std::endl;
use_db_load = false;
return;
}
if (check.compare(std::to_string(checksumcards(prefix))) != 0)
{
std::cout << "DB cards_sections mismatch to db" << std::endl;
std::cout << "DB cards_sections checksum " << checksumcards(prefix) << " != " << check << std::endl;
std::cout << "DB ignoring database.yml" << std::endl;
use_db_load = false;
return;
}
}
std::string hfield;
std::string hydeck;
std::string hedeck;
while (getline(file, line))
{
if (line.rfind("\t\t", 0) == 0 && line.find(":") != std::string::npos)
{
hedeck = line.substr(2, line.find(":") - 2);
std::istringstream reader(line.substr(line.find(":") + 2));
reader >> wins >> draws >> losses >> points >> count;
database[hfield][hydeck][hedeck] = {wins, draws, losses, points, count};
// std::cout << "load db: " << hfield << " " << hydeck << " " << hedeck << " " <<wins<< " "<< draws<< " "<< losses<< " " <<points<< " " <<count << std::endl;
}
else if (line.rfind("\t", 0) == 0 && line.find(":") != std::string::npos)
{
hydeck = line.substr(1, line.find(":") - 1);
}
else if (line.find(":") != std::string::npos)
{
hfield = line.substr(0, line.find(":"));
}
else
{
std::cout << "unknown db line: " << line;
}
}
// close file
file.close();
_DEBUG_MSG(1, "done loading db\n");
}
}
// write database map to file
void write_db(std::string prefix)
{
if (use_db_write)
{
_DEBUG_MSG(1, "start writing to db\n");
// open file to write to
std::ofstream file;
file.open(prefix + "data/database.yml");
file << "version: " << TYRANT_OPTIMIZER_VERSION << std::endl;
file << "xml_check_sum: " << checksumcards(prefix) << std::endl;
auto lines_to_write = db_limit;
// write map to file
for (auto it1 = database.begin(); lines_to_write != 0 && it1 != database.end(); ++it1)
{
file << it1->first << ":" << std::endl;
for (auto it2 = it1->second.begin(); lines_to_write != 0 && it2 != it1->second.end(); ++it2)
{
file << "\t" << it2->first << ":" << std::endl;
for (auto it3 = it2->second.begin(); lines_to_write != 0 && it3 != it2->second.end(); ++it3)
{
file << "\t\t" << it3->first << ": " << it3->second.wins << " " << it3->second.draws << " " << it3->second.losses << " " << it3->second.points << " " << it3->second.count << std::endl;
if (lines_to_write > 0)
lines_to_write--;
}
}
}
// close file
file.close();
_DEBUG_MSG(1, "done writing to db\n");
}
}
void init()
{
debug_str.clear();
database.clear();
thread_num_iterations = 0; // written by threads
thread_results = nullptr; // written by threads
thread_best_results = nullptr;
thread_compare = false;
thread_compare_stop = false; // written by threads
destroy_threads;
opt_num_threads = 4;
gamemode = fight;
optimization_mode = OptimizationMode::notset;
owned_cards.clear();
owned_alpha_dominion = nullptr;
use_owned_cards = true;
opt_skip_unclaimed_decks = false;
// opt_trim_unclaimed_decks=false;
min_deck_len = 1;
max_deck_len = 10;
opt_freezed_cards = 0;
freezed_cards = 0;
fund = 0;
target_score = 100;
min_increment_of_score = 0;
confidence_level = 0.99;
use_top_level_card = true;
use_top_level_commander = true;
mode_open_the_deck = false;
use_owned_dominions = true;
use_maxed_dominions = false;
use_fused_card_level = 0;
use_fused_commander_level = 0;
print_upgraded = false;
print_values = false;
vc_x = 0;
simplify_output = false;
show_ci = false;
use_harmonic_mean = false;
iterations_multiplier = 10;
sim_seed = 0;
flexible_iter = 20;
flexible_turn = 20;
eval_iter = 8;
eval_turn = 8;
requirement.num_cards.clear();
for (unsigned i(0); i < Skill::num_skills; ++i)
{
auto s = static_cast<Skill::Skill>(i);
x_skill_scale[s] = 1.0;
n_skill_scale[s] = 1.0;
c_skill_scale[s] = 1.0;
}
hp_scale = 1.0;
atk_scale = 1.0;
#ifndef NQUEST
// quest = new Quest(); //TODO Quest bugged in Android now here
#endif
allowed_candidates.clear();
disallowed_candidates.clear();
disallowed_recipes.clear();
// std::chrono::time_point<std::chrono::system_clock> start_time;
maximum_time = 0;
temperature = 1000;
coolingRate = 0.001;
generations = 50;
pool_size = 0;
min_pool_size = 20;
opt_pool_keep = 1;
opt_pool_mutate = 1;
opt_pool_cross = 1;
min_beam_size = 5;
yfpool = 0;
efpool = 0;
factions.clear();
invert_factions = false;
only_recent = false;
prefered_recent = false;
recent_percent = 5;
skills.clear();
invert_skills = false;
prefered_skills.clear();
prefered_factor = 3;
all_cards.clear();
// fix defaults
for (int i = 0; i < Fix::num_fixes; ++i)
fixes[i] = false;
// recommended/default fixes
fixes[Fix::enhance_early] = true;
fixes[Fix::revenge_on_death] = true;
fixes[Fix::death_from_bge] = true;
fixes[Fix::legion_under_mega] = true;
// Sort of a misnomer, but updated skills are also treated as fixes
fixes[Fix::barrier_each_turn] = true;
fixes[Fix::dont_evade_mimic_selection] = true;
fixes[Fix::leech_increase_max_hp] = true;
fixes[Fix::subdue_before_attack] = true;
fixes[Fix::counter_without_damage] = true;
fixes[Fix::poison_after_attacked] = true;
fixes[Fix::corrosive_protect_armor] = true;
db_limit = -1;
use_strict_db = true;
use_db_write = true;
use_db_load = true;
use_ml = false;
use_only_ml = false;
ml_precision = 0.01;
}
#if defined(ANDROID) || defined(__ANDROID__)
extern "C" JNIEXPORT void
JNICALL
Java_de_neuwirthinformatik_alexander_mtuo_TUO_callMain(
JNIEnv *env,
jobject obj /* this */, jobjectArray stringArray)
{
envv = env;
objv = obj;
// from: https://stackoverflow.com/questions/8870174/is-stdcout-usable-in-android-ndk and https://gist.github.com/dzhioev/6127982
class androidbuf : public std::streambuf
{
public:
enum
{
bufsize = 512
}; // ... or some other suitable buffer size
androidbuf() { this->setp(buffer, buffer + bufsize - 1); }
private:
int overflow(int c)
{
if (c == traits_type::eof())
{
*this->pptr() = traits_type::to_char_type(c);
this->sbumpc();
}
sync_me(c);
return traits_type::not_eof(c);
}
void sync_me(int overflow=0) {
if (this->pbase() != this->pptr())
{
char writebuf[bufsize+2];
memcpy(writebuf, this->pbase(), this->pptr() - this->pbase() );
writebuf[this->pptr() - this->pbase() ] = overflow;
writebuf[this->pptr() - this->pbase() + 1 ] = '\0';
//auto sss = std::string(writebuf).c_str();
///*
__android_log_print(ANDROID_LOG_DEBUG,
"TUO_TUO",
"%s",
writebuf);
//*/
jstring jstr = envv->NewStringUTF(writebuf);
jclass clazz = envv->FindClass("de/neuwirthinformatik/alexander/mtuo/TUO");
jmethodID messageMe = envv->GetMethodID(clazz, "output", "(Ljava/lang/String;)V");
envv->CallVoidMethod(objv, messageMe, jstr);
this->setp(buffer, buffer + bufsize - 1);
}
}
int sync()
{
sync_me(0);
return 0;
}
char buffer[bufsize];
};
auto ao = new androidbuf();
auto ae = new androidbuf();
std::cout.rdbuf(ao);
std::cerr.rdbuf(ae);
__android_log_write(ANDROID_LOG_DEBUG, "TUO_TUO", "START");
int stringCount = env->GetArrayLength(stringArray);
char **param = new char *[stringCount];
const char **cparam = new const char *[stringCount];
jstring *strs = new jstring[stringCount];
for (int i = 0; i < stringCount; i++)
{
strs[i] = (jstring)(*env).GetObjectArrayElement(stringArray, i);
cparam[i] = ((*env).GetStringUTFChars(strs[i], NULL));
param[i] = const_cast<char *>(cparam[i]);
}
main(stringCount, cparam);
std::cout << std::flush;
__android_log_write(ANDROID_LOG_DEBUG, "TUO_TUO", "END");
for (int i = 0; i < stringCount; i++)
{
env->ReleaseStringUTFChars(strs[i], cparam[i]);
}
// std::string text = "return";
// return env->NewStringUTF(text.c_str());
delete[] param;
delete[] cparam;
delete[] strs;
delete ao;
delete ae;
}
extern "C" JNIEXPORT jstring
JNICALL
Java_de_neuwirthinformatik_alexander_mtuo_TUO_stringFromJNI(JNIEnv *env,
jobject thiz, jstring s)
{
std::string str = env->GetStringUTFChars(s, NULL);
str += "hello.txt";
__android_log_write(ANDROID_LOG_DEBUG, "TUO_TUO", str.c_str());
FILE *file = fopen(str.c_str(), "w+");
if (file != NULL)
{
fputs("HELLO WORLD!\n", file);
fflush(file);
fclose(file);
}
return env->NewStringUTF("Hello from JNI (with file io)!");
}
#endif
using namespace std::placeholders;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
Deck *find_deck(Decks &decks, const Cards &all_cards, std::string deck_name)
{
Deck *deck = decks.find_deck_by_name(deck_name);
if (deck != nullptr)
{
deck->resolve();
return (deck);
}
decks.decks.emplace_back(Deck{all_cards});
deck = &decks.decks.back();
deck->set(deck_name);
deck->resolve();
return (deck);
}
//---------------------- $80 deck optimization ---------------------------------
unsigned get_required_cards_before_upgrade(std::unordered_map<unsigned, unsigned> &owned_cards,
const std::vector<const Card *> &card_list, std::map<const Card *, unsigned> &num_cards)
{
unsigned deck_cost = 0;
std::set<const Card *> unresolved_cards;
for (const Card *card : card_list)
{
++num_cards[card];
unresolved_cards.insert(card);
}
// un-upgrade according to type/category
// * use fund for normal cards
// * use only top-level cards for initial (basic) dominion (Alpha Dominion) and dominion material (Dominion Shard)
while (!unresolved_cards.empty())
{
// pop next unresolved card
auto card_it = unresolved_cards.end();
auto card = *(--card_it);
unresolved_cards.erase(card_it);
// assume unlimited common/rare level-1 cards (standard set)
if ((card->m_set == 1000) && (card->m_rarity <= 2) && (card->is_low_level_card()))
{
continue;
}
// keep un-defused (top-level) basic dominion & its material
if ((card->m_id == 50002) || (card->m_category == CardCategory::dominion_material))
{
continue;
}
// defuse if inventory lacks required cards and recipe is not empty
if ((fund || (card->m_category != CardCategory::normal)) && (owned_cards[card->m_id] < num_cards[card]) && !card->m_recipe_cards.empty())
{
unsigned num_under = num_cards[card] - owned_cards[card->m_id];
num_cards[card] = owned_cards[card->m_id];
// do count cost (in SP) only for normal cards
if (card->m_category == CardCategory::normal)
{
deck_cost += num_under * card->m_recipe_cost;
}
// enqueue recipe cards as unresolved
for (auto recipe_it : card->m_recipe_cards)
{
num_cards[recipe_it.first] += num_under * recipe_it.second;
unresolved_cards.insert(recipe_it.first);
}
}
}
return deck_cost;
}
inline unsigned get_required_cards_before_upgrade(const std::vector<const Card *> &card_list, std::map<const Card *, unsigned> &num_cards)
{
return get_required_cards_before_upgrade(owned_cards, card_list, num_cards);
}
unsigned get_deck_cost(const Deck *deck)
{
if (!use_owned_cards)
{
return 0;
}
std::map<const Card *, unsigned> num_in_deck;
unsigned deck_cost = 0;
if (deck->commander)
{
deck_cost += get_required_cards_before_upgrade({deck->commander}, num_in_deck);
}
deck_cost += get_required_cards_before_upgrade(deck->cards, num_in_deck);
for (auto it : num_in_deck)
{
unsigned card_id = it.first->m_id;
if (it.second > owned_cards[card_id])
{
return UINT_MAX;
}
}
return deck_cost;
}
bool is_in_recipe(const Card *card, const Card *material)
{
// is it already material?
if (card == material)
{
return true;
}
// no recipes
if (card->m_recipe_cards.empty())
{
return false;
}
// avoid illegal
if (card->m_category == CardCategory::dominion_material)
{
return false;
}
// check recursively
for (auto recipe_it : card->m_recipe_cards)
{
// is material found?
if (recipe_it.first == material)
{
return true;
}
// go deeper ...
if (is_in_recipe(recipe_it.first, material))
{
return true;
}
}
// found nothing
return false;
}
bool is_owned_or_can_be_fused(const Card *card)
{
if (owned_cards[card->m_id])
{
return true;
}
if (!fund && (card->m_category == CardCategory::normal))
{
return false;
}
std::map<const Card *, unsigned> num_in_deck;
unsigned deck_cost = get_required_cards_before_upgrade({card}, num_in_deck);
if ((card->m_category == CardCategory::normal) && (deck_cost > fund))
{
while (!card->is_low_level_card() && (deck_cost > fund))
{
card = card->downgraded();
num_in_deck.clear();
deck_cost = get_required_cards_before_upgrade({card}, num_in_deck);
}
if (deck_cost > fund)
{
return false;
}
}
std::map<unsigned, unsigned> num_under;
for (auto it : num_in_deck)
{
if (it.second > owned_cards[it.first->m_id])
{
if ((card->m_category == CardCategory::dominion_alpha) && use_maxed_dominions && !is_in_recipe(card, owned_alpha_dominion))
{
if (it.first->m_id != 50002)
{
num_under[it.first->m_id] += it.second - owned_cards[it.first->m_id];
}
continue;
}
return false;
}
}
if (!num_under.empty())
{
std::map<const Card *, unsigned> &refund = dominion_refund[owned_alpha_dominion->m_fusion_level][owned_alpha_dominion->m_level];
for (auto &refund_it : refund)
{
unsigned refund_id = refund_it.first->m_id;
if (!num_under.count(refund_id))
{
continue;
}
num_under[refund_id] = safe_minus(num_under[refund_id], refund_it.second);
if (!num_under[refund_id])
{
num_under.erase(refund_id);
}
}
}
return num_under.empty();
}
std::string alpha_dominion_cost(const Card *dom_card)
{
assert(dom_card->m_category == CardCategory::dominion_alpha);
if (!owned_alpha_dominion)
{
return "(no owned alpha dominion)";
}
std::unordered_map<unsigned, unsigned> _owned_cards;
std::unordered_map<unsigned, unsigned> refund_owned_cards;
std::map<const Card *, unsigned> num_cards;
std::map<const Card *, unsigned> &refund = dominion_refund[owned_alpha_dominion->m_fusion_level][owned_alpha_dominion->m_level];
unsigned own_dom_id = 50002;
if (is_in_recipe(dom_card, owned_alpha_dominion))
{
own_dom_id = owned_alpha_dominion->m_id;
}
else if (owned_alpha_dominion->m_id != 50002)
{
for (auto &it : refund)
{
if (it.first->m_category != CardCategory::dominion_material)
{
continue;
}
refund_owned_cards[it.first->m_id] += it.second;
}
}
_owned_cards[own_dom_id] = 1;
get_required_cards_before_upgrade(_owned_cards, {dom_card}, num_cards);
std::string value("");
for (auto &it : num_cards)
{
if (it.first->m_category != CardCategory::dominion_material)
{
continue;
}
value += it.first->m_name + " x " + std::to_string(it.second) + ", ";
}
if (!is_in_recipe(dom_card, owned_alpha_dominion))
{
num_cards.clear();
get_required_cards_before_upgrade(_owned_cards, {owned_alpha_dominion}, num_cards);
value += "using refund: ";
for (auto &it : refund)
{
signed num_under(it.second - (signed)num_cards[it.first]);
value += it.first->m_name + " x " + std::to_string(it.second) + "/" + std::to_string(num_under) + ", ";
}
}
// remove trailing ', ' for non-empty string / replace empty by '(none)'
if (!value.empty())
{
value.erase(value.end() - 2, value.end());
}
else
{
value += "(none)";
}
return value;
}
// check if claim_cards is necessary => i.e. can the deck be build from the ownedcards
bool claim_cards_needed(const std::vector<const Card *> &card_list)
{
std::map<const Card *, unsigned> num_cards;
get_required_cards_before_upgrade(card_list, num_cards);
for (const auto &it : num_cards)
{
const Card *card = it.first;
if (card->m_category == CardCategory::dominion_material && use_maxed_dominions)
continue;
if (card->m_category == CardCategory::dominion_alpha && use_maxed_dominions)
continue;
unsigned num_to_claim = safe_minus(it.second, owned_cards[card->m_id]);
if (num_to_claim > 0)
{
return true;
}
}
return false;
}
void claim_cards(const std::vector<const Card *> &card_list)
{
std::map<const Card *, unsigned> num_cards;
get_required_cards_before_upgrade(card_list, num_cards);
for (const auto &it : num_cards)
{
const Card *card = it.first;
if (card->m_category == CardCategory::dominion_material)
continue;
if (card->m_category == CardCategory::dominion_alpha)
continue;
unsigned num_to_claim = safe_minus(it.second, owned_cards[card->m_id]);
if (num_to_claim > 0)
{
owned_cards[card->m_id] += num_to_claim;
if (debug_print >= 0)
{
std::cerr << "WARNING: Need extra " << num_to_claim << " " << card->m_name << " to build your initial deck: adding to owned card list.\n";
}
}
}
}
bool valid_deck(Deck *your_deck)
{
if (claim_cards_needed({your_deck->commander}))
return false;
if (claim_cards_needed(your_deck->cards))
return false;
if (your_deck->alpha_dominion && claim_cards_needed({your_deck->alpha_dominion}))
return false;
return true; // valid
}
//------------------------------------------------------------------------------
FinalResults<long double> compute_score(const EvaluatedResults &results, std::vector<long double> &factors)
{
FinalResults<long double> final{0, 0, 0, 0, 0, 0, results.second};
long double max_possible = max_possible_score[(size_t)optimization_mode];
for (unsigned index(0); index < results.first.size(); ++index)
{
// std::cout << results.second << " " << results.first[index].points << " " << results.first[index].count << std::endl;
final.wins += results.first[index].wins * factors[index] * results.second / results.first[index].count;
final.draws += results.first[index].draws * factors[index] * results.second / results.first[index].count;
final.losses += results.first[index].losses * factors[index] * results.second / results.first[index].count;
// APN
auto trials = results.second;
auto prob = 1 - confidence_level;
auto successes = results.first[index].points * results.second / results.first[index].count / max_possible;
if (successes > trials)
{
successes = trials;
// printf("WARNING: biominal successes > trials");
_DEBUG_MSG(2, "WARNING: biominal successes > trials");
}
auto lower_bound = boost::math::binomial_distribution<>::find_lower_bound_on_p(trials, successes, prob) * max_possible;
auto upper_bound = boost::math::binomial_distribution<>::find_upper_bound_on_p(trials, successes, prob) * max_possible;
if (use_harmonic_mean)
{
final.points += factors[index] / (results.first[index].points * results.second / results.first[index].count);
final.points_lower_bound += factors[index] / lower_bound;
final.points_upper_bound += factors[index] / upper_bound;
}
else
{
final.points += results.first[index].points * factors[index] * results.second / results.first[index].count;
final.points_lower_bound += lower_bound * factors[index];
final.points_upper_bound += upper_bound * factors[index];
}
}
long double factor_sum = std::accumulate(factors.begin(), factors.end(), 0.);
final.wins /= factor_sum * (long double)results.second;
final.draws /= factor_sum * (long double)results.second;
final.losses /= factor_sum * (long double)results.second;
if (use_harmonic_mean)
{
final.points = factor_sum / ((long double)results.second * final.points);
final.points_lower_bound = factor_sum / final.points_lower_bound;
final.points_upper_bound = factor_sum / final.points_upper_bound;
}
else
{
final.points /= factor_sum * (long double)results.second;
final.points_lower_bound /= factor_sum;
final.points_upper_bound /= factor_sum;
}
return final;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Per thread data.
// seed should be unique for each thread.
// d1 and d2 are intended to point to read-only process-wide data.
void SimulationData::set_decks(std::vector<Deck *> const your_decks_, std::vector<Deck *> const &enemy_decks_)
{