-
Notifications
You must be signed in to change notification settings - Fork 0
/
Discord_Bot.py
1050 lines (933 loc) · 41.9 KB
/
Discord_Bot.py
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
import discord
from discord.ext import commands
from discord.ext.commands import cooldown, BucketType, CommandOnCooldown, Context, CommandNotFound, BadArgument
import requests as rq
from bs4 import BeautifulSoup
import csv
import json
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import config
IGNORE_EXCEPTIONS = (CommandNotFound, BadArgument)
client = commands.Bot(command_prefix=',')
client.remove_command('help')
@commands.Cog.listener()
async def on_command_error(self, ctx, exc):
if isinstance(exc, CommandOnCooldown):
emb = discord.Embed(title='Shut up and let me think!',
description=f'That command is on cooldown, try again in {exc.retry_after:,.2f} seconds.',
color=0xFFBF00)
await ctx.send(embed=emb)
@client.event
async def on_ready():
print('bot ready')
@client.command()
@cooldown(1,15, BucketType.user)
async def ping(ctx):
await ctx.send(f'pong {round(client.latency * 1000)}ms')
@client.command(pass_context=True)
@cooldown(1,15, BucketType.user)
async def help(ctx):
author=ctx.message.author
embed=discord.Embed(colour=discord.Colour.dark_blue())
embed.set_author(name='Help')
embed.add_field(name='Description',value='The Goal of this bot is to make graphs for Europa universalis 4,by using the Skanderbeg save data',inline=False)
embed.add_field(name=',ping',value='returns pong!',inline=False)
embed.add_field(name=',graphs',value=f'if you want to make graphs use this format: \n ,graphs Skanderbeg_Save_ID \n Ex: ,graphs d852c8 \n you can get the Skanderbeg_Save_ID in the skanderbeg site in the ID column in My Maps (https://skanderbeg.pm/maps.php)',inline=False)
embed.add_field(name=',creator', value='returns the discord id of me:the creator', inline=False)
await ctx.send(embed=embed)
@client.command()
@cooldown(1, 120, BucketType.user)
async def graphs(ctx, *, code):
await ctx.send('wait for the graphs')
a = code
save = code
print('do you want to compare this save with an older one?[y/n]')
resp1 = 'n'
save2 = ''
if resp1 == 'y':
print('type the older skanderbeg Save code')
save2 = input()
print('do you want to show only players?[y/n]')
ia = 'y'
try:
with open('folder.txt') as f:
folder = f.read()
f.close()
except:
f = open('folder.txt', 'x')
folder = ''
if folder == '':
print('please indicate the location of the folder where you want to store your graphs')
folder = ''
with open('folder.txt', 'wt') as z:
z.write(str(folder))
if ia == 'y' or ia == 'yes':
ia = '&playersOnly=yes'
else:
ia = ''
url = 'https://skanderbeg.pm/api.php?key=963df40b3b93a81013da34dfdd815583&scope=getCountryData&save=' + save + '&tag=IRE&value=inc_no_subs;total_development;buildings_value;provinces;total_army;qualityScore;total_mana_spent_on_deving;total_mana_on_teching_up;spent_total;fdp;total_mana_spent_on_deving;battleCasualties;max_manpower;continents;dev_clicks;total_navy;total_army;hex;player;countryName&' + ia + '&format=json'
response = rq.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
with open('data.json', 'w', encoding='utf-8') as f_out:
f_out.write(soup.prettify())
with open('data.json') as json_file:
try:
data = json.load(json_file)
except:
await ctx.send(
f'Invalid Skanderbeg Save id / the Skanderbeg server is offline \n Try to redo the command with the correct id or dm me with:,creator')
df = pd.read_json('data.json')
corpus = df.iloc[0][1]
csv_columns = ['tag', 'fdp', 'battleCasualties', 'max_manpower', 'countryName', 'player', 'total_development',
'spent_total', 'total_mana_on_teching_up', 'provinces', 'qualityScore', 'inc_no_subs', 'total_army',
'total_mana_spent_on_deving', 'buildings_value', 'continents', 'total_navy', 'dev_clicks',
'deving_stats', 'hex']
i = 0
dict = []
tags = []
for tag in data:
tags.append(tag)
while i < len(df.columns):
a = df.iloc[0][i]
a.update({'tag': tags[i]})
dict.append(a)
i = i + 1
csv_file = "found.csv"
try:
with open(csv_file, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in dict:
for key, value in data.items():
if key == 'provinces' and int(value) >= 1:
writer.writerow(data)
except IOError:
print("I/O error")
if save2 != '':
url = 'https://skanderbeg.pm/api.php?key=963df40b3b93a81013da34dfdd815583&scope=getCountryData&save=' + save2 + '&tag=IRE&value=inc_no_subs;total_development;buildings_value;provinces;total_army;qualityScore;total_mana_spent_on_deving;total_mana_on_teching_up;spent_total;fdp;total_mana_spent_on_deving;battleCasualties;max_manpower;continents;dev_clicks;total_navy;hex;total_army;player;countryName&' + ia + '&format=json'
response = rq.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
with open('data.json', 'w', encoding='utf-8') as f_out:
f_out.write(soup.prettify())
with open('data.json') as json_file:
data = json.load(json_file)
df = pd.read_json('data.json')
corpus = df.iloc[0][1]
csv_columns = ['tag', 'fdp', 'battleCasualties', 'max_manpower', 'countryName', 'player', 'total_development',
'spent_total', 'total_mana_on_teching_up', 'provinces', 'qualityScore', 'inc_no_subs',
'total_army',
'total_mana_spent_on_deving', 'buildings_value', 'continents', 'total_navy', 'dev_clicks',
'deving_stats', 'hex']
i = 0
dict = []
tags = []
for tag in data:
tags.append(tag)
while i < len(df.columns):
a = df.iloc[0][i]
a.update({'tag': tags[i]})
dict.append(a)
i = i + 1
csv_file = "found2.csv"
try:
with open(csv_file, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in dict:
for key, value in data.items():
if key == 'provinces' and int(value) >= 1:
writer.writerow(data)
except IOError:
print("I/O error")
with open('found.csv', 'r') as csvfile:
lines = csvfile.readlines()
x = 'found.csv'
y = 'found2.csv'
df1 = pd.read_csv(x, encoding='latin1')
try:
df2 = pd.read_csv(y, encoding='latin1')
except:
y = 'found.csv'
df2 = pd.read_csv(y, encoding='latin1')
def replace(df):
a = df.columns
list(a)
h = []
j = []
for x in a:
h.append(x)
if x == '|':
x = 'tag'
y = x.replace('|', '')
z = y.replace('_', '')
j.append(z)
df.rename(columns={x: y for x, y in zip(h, j)}, inplace=True)
replace(df1)
replace(df2)
df1['totalarmy'] = df1['totalarmy'].fillna(0)
df1['totalnavy'] = df1['totalnavy'].fillna(0)
df2['totalarmy'] = df2['totalarmy'].fillna(0)
df2['totalnavy'] = df2['totalnavy'].fillna(0)
df1['buildingsvalue'] = df1['buildingsvalue'].fillna(0)
df2['buildingsvalue'] = df2['buildingsvalue'].fillna(0)
lista1 = [df1, df2]
lista = [df1]
date = [1444, 1469, 1481, 1]
tags = df1['tag'].tolist()
tagss = tags
print(tags)
players = df1['countryName'].tolist()
i = 0
for player in players:
if type(player) == type(0.54):
players[i] = tags[i]
i += 1
def a_su_b(dfa, dfb, nomicolonne):
dfx = pd.DataFrame()
i = 0
length = len(nomicolonne)
while i < length:
z = nomicolonne[i]
x = [a / b for a, b in zip(dfa[z], dfb[z])]
dfx[z] = x
i += 1
return dfx
def calcolatorespaziatrura(ncolonne):
a = ((4 * ncolonne) + 45) / 2000
return a
def calcolosize(ncolonne):
size = ((1 / 5) * -ncolonne) + 14
return size
def humanvalue(dict, I, tags):
j = I
a = []
for i in tags:
x = dict[i]
try:
s = x[I]
y = round(s, 2)
a.append(y)
except:
pass
return (a)
def sumof(data):
a = 0
for row in data:
a = a + row
return a
def testosucolonne(columns, ncifre):
return columns
def devonnprovince(data):
x = [round(i / k, 1) for i, k in zip(data['realdevelopment'], data['provinces'])]
return x
def func(pct, allvals):
absolute = int(pct / 100. * np.sum(allvals))
return "{:.1f}%\n{:d}".format(pct, absolute)
def sostituisci(df):
dft = df.T
dict = dft.to_dict()
for i in list(df.index.values):
a = df['tag']
y = a[i]
dict[y] = dict.pop(i)
return dict
def human(df):
Humanplayers = df.loc[
(df['tag'] == 'TUR') | (df['tag'] == 'FRA') | (df['tag'] == 'MOS') | (df['tag'] == 'CAS') | (
df['tag'] == 'ENG') | (df['tag'] == 'HAB') | (df['tag'] == 'QOM') | (df['tag'] == 'PER') | (
df['tag'] == 'SWE') | (df['tag'] == 'BRA') | (df['tag'] == 'HOL') | (
df['tag'] == 'SWI') | (df['tag'] == 'PAL')]
return Humanplayers
def prova(listadf):
i = 0
for df in listadf:
dict = sostituisci(df)
humandict = {item: dict.get(item) for item in tagss}
playerdev = humanvalue(humandict, 'totaldevelopment', tags)
playerincome = humanvalue(humandict, 'incnosubs', tags)
playerbuildingsvalue = humanvalue(humandict, 'buildingsvalue', tags)
playerprovinces = humanvalue(humandict, 'provinces', tags)
playerbattlecasualites = humanvalue(humandict, 'battleCasualties', tags)
playertotalarmy = humanvalue(humandict, 'totalarmy', tags)
playerqualityscore = humanvalue(humandict, 'qualityScore', tags)
playermanadev = humanvalue(humandict, 'totalmanaspentondeving', tags)
playermanatech = humanvalue(humandict, 'totalmanaontechingup', tags)
playermoneyspent = humanvalue(humandict, 'spenttotal', tags)
playermaxmanpower = humanvalue(humandict, 'maxmanpower', tags)
playertotalnavy = humanvalue(humandict, 'totalnavy', tags)
playerfdp = humanvalue(humandict, 'fdp', tags)
playerclick = humanvalue(humandict, 'devclicks', tags)
if i == 0:
a = [playerdev]
b = [playerincome]
c = [playerbuildingsvalue]
d = [playerprovinces]
e = [playerbattlecasualites]
f = [playertotalarmy]
g = [playerqualityscore]
h = [playermanadev]
ix = [playermanatech]
l = [playermoneyspent]
n = [playermaxmanpower]
m = [playertotalnavy]
o = [playerfdp]
p = [playerclick]
i += 1
else:
i += 1
a.append(playerdev)
b.append(playerincome)
c.append(playerbuildingsvalue)
d.append(playerprovinces)
e.append(playerbattlecasualites)
f.append(playertotalarmy)
g.append(playerqualityscore)
h.append(playermanadev)
ix.append(playermanatech)
l.append(playermoneyspent)
n.append(playermaxmanpower)
m.append(playertotalnavy)
o.append(playerfdp)
p.append(playerclick)
dfplayerdev = pd.DataFrame(a, columns=players)
dfplayerincome = pd.DataFrame(b, columns=players)
dfplayerbuildingsvalue = pd.DataFrame(c, columns=players)
dfplayerprovinces = pd.DataFrame(d, columns=players)
dfplayerbattlecasualites = pd.DataFrame(e, columns=players)
dfplayertotalarmy = pd.DataFrame(f, columns=players)
dfplayerqualityscore = pd.DataFrame(g, columns=players)
dfplayermanadev = pd.DataFrame(h, columns=players)
dfplayermanatech = pd.DataFrame(ix, columns=players)
dfplayermoneyspent = pd.DataFrame(l, columns=players)
dfplayermaxmanpower = pd.DataFrame(n, columns=players)
dfplayertotalnavy = pd.DataFrame(m, columns=players)
playerfdp = pd.DataFrame(o, columns=players)
playerclick = pd.DataFrame(p, columns=players)
tutto = [dfplayerdev, dfplayerincome, dfplayerbuildingsvalue, dfplayerprovinces, dfplayerbattlecasualites,
dfplayertotalarmy, dfplayerqualityscore, dfplayermanadev, dfplayermanatech, dfplayermoneyspent,
dfplayermaxmanpower, dfplayertotalnavy, playerfdp, playerclick]
return tutto
ogni = prova(lista)
k = 0
# colori grafico
colori = ['black', 'grey', 'rosybrown', 'brown', 'darkred', 'red', 'tomato', 'coral', 'orangered', 'sienna', 'peru',
'orange', 'goldenrod', 'gold', 'khaki', 'olive', 'yellow', 'lawngreen', 'green', 'lime', 'teal', 'cyan',
'steelblue', 'navy', 'blue', 'blueviolet', 'indigo', 'violet', 'magenta', 'deeppink']
listaz = ogni[0].columns
colornazioni = {}
count = 0
hex = df1['hex']
for nation in listaz:
colornazioni[nation] = hex[count]
count = count + 1
az = np.linspace(0, 1, len(players))
massimo = len(lines) - 1
if massimo > 20:
resp = ' but the optimal maximum is around 20'
y = str(20)
else:
resp = ''
y = str(massimo)
print('how many nation do you want ot print? the max is ' + str(massimo) + resp)
y = int(y)
f = 100 / y
alpha1 = 0.8
alphagrid = 0.4
sz = calcolatorespaziatrura(y)
sizes = calcolosize(y)
for s in ogni:
if k == 0: # dev
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('Development')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
h += ((ap / somma) * 100)
percentuali.append(h)
balances = []
q = f
for l in percentuali:
d = l - q
balances.append(d)
q += f
j = max(balances)
pvalue = (1 - ((j ** 2) / 2500)) * 100
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
plt.ylim(0, 101)
plt.plot(percentuali, marker='o', color='r') # linea paretiana
ax1.set_title('development' + ' Balancing%=' + str(round(pvalue)) + '%')
plt.ylabel('% of dev on total')
j = 0
for i, v in enumerate(percentuali): # testo su linea
ax2.text(i - 0.10, v + 1, str(round(v)) + '%', color='black', fontweight='bold', size=sizes)
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
ax1.text(i - len(str(round(v, 1))) * sz, v + 0.5, str(round(v, 1)), color='black', fontweight='bold',
size=sizes)
plt.savefig(folder + 'dev.png')
plt.close()
if k == 1: # income
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
plt.xticks(rotation=-90)
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('income')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
h += ((ap / somma) * 100)
percentuali.append(h)
balances = []
q = f
for l in percentuali:
d = l - q
balances.append(d)
q += f
j = max(balances)
pvalue = (1 - ((j ** 2) / 2500)) * 100
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
plt.ylim(0, 101)
plt.plot(percentuali, marker='o', color='r') # linea paretiana
ax1.set_title('income' + ' Balancing%=' + str(round(pvalue)) + '%')
plt.ylabel('% of income on total')
j = 0
for i, v in enumerate(percentuali): # testo su linea
ax2.text(i - 0.10, v + 1, str(round(v)) + '%', color='black', fontweight='bold', size=sizes)
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
ax1.text(i - len(str(round(v))) * sz, v + 0.5, str(round(v)), color='black', fontweight='bold',
size=sizes)
plt.savefig(folder + 'income.png')
plt.close()
if k == 2: # valore immobili
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False)
if y>10:
hj = s.iloc[:, range(10, y)]
s = s.iloc[:, range(0, 10)]
others = 0
counting = 0
coloriar = []
hh = hj.values.tolist()
for value in hh[0]:
others = others + value
counting = counting + 1
s['Others'] = others
for nomej in s.columns:
try:
coloriar.append(colornazioni[nomej])
except:
coloriar.append('gray')
else:
coloriar = []
for nomej in s.columns:
try:
coloriar.append(colornazioni[nomej])
except:
coloriar.append('gray')
ax2 = s.loc[len(s) - 1].plot.pie(autopct=lambda pct: func(pct, s.loc[len(s) - 1]), startangle=90,
radius=1.3, colors=coloriar)
plt.grid(axis='y', alpha=alphagrid)
ax2.text(-0.3, 1.5, 'Buildings Value', color='black', fontweight='bold', size=sizes)
plt.savefig(folder + 'Buildings Value.png')
plt.close()
if k == 3: # province
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('provinces')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
h += ((ap / somma) * 100)
percentuali.append(h)
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
plt.ylim(0, 101)
plt.plot(percentuali, marker='o', color='g') # linea paretiana
ax1.set_title('provinces')
plt.ylabel('% of provinces on total')
j = 0
for i, v in enumerate(percentuali): # testo su linea
ax2.text(i - 0.10, v + 1, str(round(v)) + '%', color='black', fontweight='bold', size=sizes)
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre.
ax1.text(i - len(str(round(v, 1))) * sz, v + 0.5, str(round(v, 1)), color='black', fontweight='bold',
size=sizes)
plt.savefig(folder + 'provinces.png')
plt.close()
if k == 4:
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('Battle casualities')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
try:
h += ((ap / somma) * 100)
except:
pass
percentuali.append(h)
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
plt.ylim(0, 101)
plt.plot(percentuali, marker='o', color='g') # linea paretiana
ax1.set_title('Battle casualities')
plt.ylabel('% battle casualities on total')
j = 0
for i, v in enumerate(percentuali): # testo su linea
ax2.text(i - 0.10, v + 1, str(round(v)) + '%', color='black', fontweight='bold', size=sizes)
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
if v >= 100000:
ax1.text(i - len(str(round(v / 1000000, 1)) + 'M') * sz, v + 0.5, str(round(v / 1000000, 1)) + 'M',
color='black', fontweight='bold', size=sizes)
else:
ax1.text(i - len(str(round(v / 1000, 1)) + 'k') * sz, v + 0.5, str(round(v / 1000, 1)) + 'k',
color='black', fontweight='bold', size=sizes)
plt.savefig(folder + 'Battle casualities.png')
plt.close()
if k == 5:
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('Total armies')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
h += ((ap / somma) * 100)
percentuali.append(h)
balances = []
q = f
for l in percentuali:
d = l - q
balances.append(d)
q += f
j = max(balances)
pvalue = (1 - ((j ** 2) / 2500)) * 100
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
plt.ylim(0, 101)
plt.plot(percentuali, marker='o', color='y') # linea paretiana
ax1.set_title('armies' + ' Balancing%=' + str(round(pvalue)) + '%')
plt.ylabel('% Armies on total')
j = 0
for i, v in enumerate(percentuali): # testo su linea
ax2.text(i - 0.10, v + 1, str(round(v)) + '%', color='black', fontweight='bold', size=sizes)
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
ax1.text(i - len(str(int(v))) * sz, v + 0.5, str(int(v)), color='black', fontweight='bold', size=sizes)
plt.savefig(folder + 'armies.png')
plt.close()
if k == 7:
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('Mana spent on devving')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
try:
h += ((ap / somma) * 100)
except:
pass
percentuali.append(h)
ax1.set_title('Mana spent on devving')
j = 0
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
ax1.text(i - len(str(round(v / 1000, 1)) + 'k') * sz, v + 0.5, str(round(v / 1000, 1)) + 'k',
color='black',
fontweight='bold', size=sizes)
plt.savefig(folder + 'Mana spent on devving.png')
plt.close()
if k == 8:
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('Mana spent on teching up')
a = s.loc[len(s) - 1]
plt.ylim(a[-1] - 500, a[0] + 500)
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
try:
h += ((ap / somma) * 100)
except:
pass
percentuali.append(h)
ax1.set_title('Mana spent on teching up')
j = 0
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
ax1.text(i - len(str(round(v / 1000, 1)) + 'k') * sz, v + 0.5, str(round(v / 1000, 1)) + 'k',
color='black',
fontweight='bold', size=sizes)
plt.savefig(folder + 'Mana spent on teching up.png')
plt.close()
if k == 9:
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('money spent')
plt.title('money spent')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
if v >= 100000:
ax1.text(i - len(str(round(v / 1000000, 1)) + 'M') * sz, v + 0.5, str(round(v / 1000000, 1)) + 'M',
color='black', fontweight='bold', size=sizes)
else:
ax1.text(i - len(str(round(v / 1000, 1)) + 'k') * sz, v + 0.5, str(round(v / 1000, 1)) + 'k',
color='black', fontweight='bold', size=sizes)
plt.savefig(folder + 'moneyspent.png')
plt.close()
if k == 10:
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('max mp')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
h += ((ap / somma) * 100)
percentuali.append(h)
balances = []
q = f
for l in percentuali:
d = l - q
balances.append(d)
q += f
j = max(balances)
pvalue = (1 - ((j ** 2) / 2500)) * 100
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
plt.ylim(0, 101)
plt.plot(percentuali, marker='o', color='g') # linea paretiana
ax1.set_title('max manpower' + ' Balancing%=' + str(round(pvalue)) + '%')
plt.ylabel('% max mp on total')
j = 0
for i, v in enumerate(percentuali): # testo su linea
ax2.text(i - 0.10, v + 1, str(round(v)) + '%', color='black', fontweight='bold', size=12)
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
if v >= 100000:
ax1.text(i - len(str(round(v / 1000000, 1)) + 'M') * sz, v + 0.5, str(round(v / 1000000, 1)) + 'M',
color='black', fontweight='bold', size=sizes)
else:
ax1.text(i - len(str(round(v / 1000, 1)) + 'k') * sz, v + 0.5, str(round(v / 1000, 1)) + 'k',
color='black', fontweight='bold', size=sizes)
plt.savefig(folder + 'max manpower.png')
plt.close()
if k == 11:
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('total navy')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
h += ((ap / somma) * 100)
percentuali.append(h)
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
plt.ylim(0, 101)
plt.plot(percentuali, marker='o', color='g') # linea paretiana
ax1.set_title('total navy')
plt.ylabel('% total navy on total')
j = 0
for i, v in enumerate(percentuali): # testo su linea
ax2.text(i - 0.10, v + 1, str(round(v)) + '%', color='black', fontweight='bold', size=sizes)
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
ax1.text(i - len(str(int(v))) * sz, v + 0.5, str(int(v)), color='black', fontweight='bold', size=sizes)
plt.savefig(folder + 'total navy.png')
plt.close()
if k == 13:
try:
plt.figure(figsize=[19.2, 10.8])
s = s.sort_values(by=(len(s) - 1), axis=1, ascending=False) # sort data
s = s.iloc[:, range(0, y)]
coloriar = []
for nomej in s.columns:
coloriar.append(colornazioni[nomej])
ax1 = s.loc[len(s) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.ylabel('dev clicks')
somma = 0
for a in s.loc[len(s) - 1]: # somma ultima riga matrice
somma = somma + a
h = 0
percentuali = []
for ap in s.loc[len(s) - 1]:
h += ((ap / somma) * 100)
percentuali.append(h)
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
plt.ylim(0, 101)
plt.plot(percentuali, marker='o', color='g') # linea paretiana
ax1.set_title('total dev clicks')
plt.ylabel('% dev clicks on the total')
j = 0
for i, v in enumerate(percentuali): # testo su linea
ax2.text(i - 0.10, v + 1, str(round(v)) + '%', color='black', fontweight='bold', size=sizes)
for i, v in enumerate(s.loc[len(s) - 1]): # testo su barre
ax1.text(i - len(str(int(v))) * sz, v + 0.5, str(int(v)), color='black', fontweight='bold',
size=sizes)
plt.savefig(folder + 'dev clicks.png')
plt.close()
except:
pass
k += 1
def boh(lista):
a1 = []
b1 = []
c1 = []
d1 = []
for df in lista:
i = 0
tags1 = df['tag'].tolist()
players1 = df['countryName'].tolist()
for player in players1:
if type(player) == type(0.54):
players1[i] = tags1[i]
i += 1
a = pd.DataFrame([df['incnosubs'].tolist()], columns=players1)
b = pd.DataFrame([df['provinces'].tolist()], columns=players1)
c = pd.DataFrame([df['totaldevelopment'].tolist()], columns=players1)
d = pd.DataFrame([df['maxmanpower'].tolist()], columns=players1)
a1.append(a)
b1.append(b)
c1.append(c)
d1.append(d)
a2 = pd.concat(a1)
b2 = pd.concat(b1)
c2 = pd.concat(c1)
d2 = pd.concat(d1)
total = [a2, b2, c2, d2]
return total
h = boh(lista1)
dev = ogni[0]
pro = ogni[3]
manpower = ogni[10]
income = ogni[1]
fdp = ogni[12]
plt.figure(figsize=[19.2, 10.8])
fdpdev = [a * b for a, b in zip(dev.loc[0], fdp.loc[0])]
dffdpdev = pd.DataFrame(np.array([fdpdev]), columns=players)
dffdpdev = dffdpdev.append(fdp, ignore_index=True)
dffdpdev = dffdpdev.sort_values(by=0, axis=1, ascending=False)
dffdpdev = dffdpdev.iloc[:, range(0, y)]
plt.figure(figsize=[19.2, 10.8])
avgdev = [a / b for a, b in zip(dev.loc[0], pro.loc[0])]
dfavgdev = pd.DataFrame(np.array([avgdev]), columns=players)
dfavgdev = dfavgdev.sort_values(by=(len(dfavgdev) - 1), axis=1, ascending=False)
dfavgdev = dfavgdev.iloc[:, range(0, y)]
coloriar = []
for nomej in dfavgdev.columns:
coloriar.append(colornazioni[nomej])
ax1 = dfavgdev.loc[len(dfavgdev) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black') # bar plt
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
for i, v in enumerate(dfavgdev.loc[len(dfavgdev) - 1]): # testo su barre
ax1.text(i - len(str(round(v, 1))) * sz, v + 0.005, str(round(v, 1)), color='black', fontweight='bold',
size=sizes)
plt.title('avg dev')
plt.savefig(folder + 'avg dev.png')
plt.close()
plt.figure(figsize=[19.2, 10.8])
avgmanpower = [(a - 10000) / b for a, b in zip(manpower.loc[0], pro.loc[0])]
dfavgmanpower = pd.DataFrame(np.array([avgmanpower]), columns=players)
dfavgmanpower = dfavgmanpower.sort_values(by=(len(dfavgmanpower) - 1), axis=1, ascending=False) #
dfavgmanpower = dfavgmanpower.iloc[:, range(0, y)]
coloriar = []
for nomej in dfavgmanpower.columns:
coloriar.append(colornazioni[nomej])
ax1 = dfavgmanpower.loc[len(dfavgmanpower) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black')
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
for i, v in enumerate(dfavgmanpower.loc[len(dfavgmanpower) - 1]): # testo su barre
ax1.text(i - len(str(round(v / 1000, 1)) + 'k') * sz, v + 0.05, str(round(v / 1000, 1)) + 'k', color='black',
fontweight='bold', size=sizes)
plt.title('manpower per province')
plt.savefig(folder + 'manpower per province.png')
plt.close()
plt.figure(figsize=[19.2, 10.8])
avgincome = [(a - 2) / b for a, b in zip(income.loc[0], dev.loc[0])]
dfavgincome = pd.DataFrame(np.array([avgincome]), columns=players)
dfavgincome = dfavgincome.sort_values(by=(len(dfavgincome) - 1), axis=1, ascending=False) #
dfavgincome = dfavgincome.iloc[:, range(0, y)]
coloriar = []
for nomej in dfavgincome.columns:
coloriar.append(colornazioni[nomej])
ax1 = dfavgincome.loc[len(dfavgincome) - 1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black')
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
for i, v in enumerate(dfavgincome.loc[len(dfavgincome) - 1]): # testo su barre
ax1.text(i - len(str(round(v, 2))) * sz, v, str(round(v, 2)), color='black', fontweight='bold', size=sizes)
plt.title('income per dev(nation efficency)')
plt.savefig(folder + 'income per dev(nation efficency).png')
plt.close()
# diff income %
def differenza(playerincome, cosa):
global y
global alpha1
global alphagrid
plt.figure(figsize=[19.2, 10.8])
diffincome = []
diffincomeper = []
diff = lambda x: round(x.iloc[0] - x.iloc[1], 2)
diffper = lambda x: round(((x.iloc[0] / x.iloc[1]) * 100) - 100, 1)
playerincome.loc[2] = playerincome.apply(diff)
playerincome.loc[3] = playerincome.apply(diffper)
playerincome.dropna(axis=1, inplace=True)
dfdiffincome = pd.DataFrame(np.array([playerincome.iloc[-1].tolist(), playerincome.iloc[-2].tolist()]),
columns=playerincome.columns)
dfdiffincome = dfdiffincome.sort_values(by=1, axis=1, ascending=False)
if len(dfdiffincome.columns) <= y:
y = len(dfdiffincome.columns)
sz = calcolatorespaziatrura(y)
sizes = calcolosize(y)
dfdiffincomeper = pd.DataFrame(np.array([playerincome.iloc[-1].tolist()]), columns=playerincome.columns)
dfdiffincome = dfdiffincome.iloc[:, range(0, y)]
coloriar = []
for nomej in dfdiffincome.columns:
coloriar.append(colornazioni[nomej])
dfdiffincomeper = dfdiffincomeper.iloc[:, range(0, y)]
ax1 = dfdiffincome.iloc[-1].plot.bar(color=coloriar, alpha=alpha1, edgecolor='black')
plt.grid(axis='y', alpha=alphagrid)
plt.xticks(rotation=-90)
plt.title(cosa + ' gained in this session')
ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
plt.ylim(-5, 321)
for i, v in enumerate(dfdiffincome.iloc[0]): # testo su linea