-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path#vms-cc-pools-main.py#
4830 lines (3745 loc) · 182 KB
/
#vms-cc-pools-main.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 pygame, random, sys, glob, os
from pygame.locals import *
import pylab as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.cm as mpl
import vmsutils as utils
import colormaps as cmaps
import datetime
from dateutil.relativedelta import relativedelta
from datetime import timedelta
STARTDATE = datetime.datetime(2018, 8, 7, 00, 00) #1st trading on blockchain of a tomato in Kenya
print ("Start Date: ",STARTDATE.isoformat(' '))
startMonth = STARTDATE.month
currentMonthNum = startMonth
random.seed(18)
print (sys.version)
visual = True
cclMode = 0 #into to represent ccMode
displayPlots = visual#False#True
displayTrade = visual#False#True
savingsMode = False#visual#True
loanMode = savingsMode#False#visual#True
importMode = True
exportMode = True#False
seasonalMode = True#False
heatMode = True#False
heatOn = True#False #allows for the heatmap to turn on dynamically
ccMode = True
clientsModeB=False
seedingMode = False
autoMode = False#True #runs through several iterations of the simulation
clearingMode = True#False
bondingMode = True
NCHEAT = True
CCHEAT = True
saveImageMode = False
moveTrader= False
MINPUSAGECC = 0.99
if displayPlots == False:
os.environ["SDL_VIDEODRIVER"] = "dummy"
#MARKET DEMOGRAPHICS#
############SMALLMARKETLocal100
#pRETAIL = 40
#pFOREIGNRETAIL = 10
#pLOCALSERVICE = 20
#pLOCALPRODUCER = 20
#pEXPORTSERVICE = 10
############SMALLMARKETNONLOCAL
pRETAIL = 5
pFOREIGNRETAIL = 5
pLOCALSERVICE = 5
pLOCALPRODUCER = 5
pEXPORTSERVICE = 5
#
############MARKET100
#pRETAIL = 20
#pFOREIGNRETAIL = 20
#pLOCALSERVICE = 10
#pLOCALPRODUCER = 10
#pEXPORTSERVICE = 40
############MARKET200
#pRETAIL = 38
#pFOREIGNRETAIL = 10
#pLOCALSERVICE = 69
#pLOCALPRODUCER = 84
#pEXPORTSERVICE = 400
#numStartSCoops = 0
numStartSCoops = 1
numStartPCoops = 0
pNonAccepting = 0.1 #%
pNonAcceptingStep = 0.1
pNonAcceptingMax = 0.9
############MARKET200
#pRETAIL = 40
#pFOREIGNRETAIL = 22
#pLOCALSERVICE = 60
#pLOCALPRODUCER = 60
#pEXPORTSERVICE = 18
############MARKET1000
#pRETAIL = 200
#pFOREIGNRETAIL = 110
#pLOCALSERVICE = 300
#pLOCALPRODUCER = 300
#pEXPORTSERVICE = 90
#####FEW
#pRETAIL = 10
#pFOREIGNRETAIL = 5
#pLOCALSERVICE = 15
#pLOCALPRODUCER = 15
#pEXPORTSERVICE = 5
tRETAIL = 0
tFOREIGNRETAIL = 0
tLOCALPRODUCER = 0
tLOCALSERVICE = 0
if pRETAIL >= 1:
tRETAIL = 0
if pFOREIGNRETAIL >= 1:
tFOREIGNRETAIL = 1
if pLOCALPRODUCER >= 1:
tLOCALPRODUCER = 1
if pLOCALSERVICE >= 1:
tLOCALSERVICE = 1
#diversityLevelMax requirment on the minimum number of trade partners
diversityLevelMax = tRETAIL +tFOREIGNRETAIL + tLOCALPRODUCER + tLOCALSERVICE
#MAXTRADERS = 100
MAXTRADERS = pRETAIL + pFOREIGNRETAIL + pLOCALSERVICE + pLOCALPRODUCER + pEXPORTSERVICE
if pRETAIL == 1:
diversityLevelMax = diversityLevelMax -1
if pFOREIGNRETAIL == 1:
diversityLevelMax = diversityLevelMax -1
if pLOCALPRODUCER == 1:
diversityLevelMax = diversityLevelMax -1
if pLOCALSERVICE == 1:
diversityLevelMax = diversityLevelMax -1
#plt.rc('legend',fontsize=8) # using a size in points
#plt.rc('axes',titlesize=10) # using a size in points
os.environ['SDL_VIDEO_CENTERED'] = '1'
TRADEMOVERATE = 8#10#how fast are trades completed
DAILYCYCLES = 50#200#number of game cycles equalling one day
clickedTrader=1#-1#used for interface
clickedToken=-1#-1#used for interface
FFMPEG_BIN = "ffmpeg" # on Linux ans Mac OS
WINDOWWIDTH = 1244
WINDOWHEIGHT = 700
#SUBWINDOWWIDTH = WINDOWWIDTH -120
#SUBWINDOWHEIGHT = 420
SUBWINDOWWIDTH = WINDOWWIDTH - 80
SUBWINDOWHEIGHT = WINDOWHEIGHT - 80
BORDERWIDTH = 10
BORDERHEIGHT = 10
OFFSETWIDTH = 40
OFFSETHEIGHT = 40
CLOCKBORDERWIDTH = 30
CLOCKBORDERHEIGHT = 20
INFOWIDTH = 350
INFOHEIGHT = WINDOWHEIGHT-BORDERHEIGHT*2
TOFFSETWIDTH = OFFSETWIDTH - 10
legendOffsetX = BORDERWIDTH+30
legendOffsetY = INFOHEIGHT-150
TEXTCOLOR = (0, 0, 0)
BLUE = ( 0, 0, 255)
LIGHTBLUE = ( 20, 20, 155)
PURPLE = ( 150, 0, 120)
PINK = ( 250, 0, 220)
ORANGE = ( 200, 70, 10)
DARKORANGE = ( 235, 70, 30)
DARKERORANGE = ( 255, 120, 50)
RED = ( 255, 0, 0)
YELLOW = ( 255, 200, 0)
DARKRED = ( 155, 0, 0)
GREEN = ( 0, 255, 0)
WHITE = ( 255, 255, 255)
GREY = ( 111, 111, 222)
BLACK = ( 0, 0, 0)
BACKGROUNDCOLOR = BLACK
DARKGREEN = ( 0, 155, 0)
DARKERGREEN = ( 0, 80, 0)
LIGHTGREEN = ( 100, 255, 100)
heatSprites = pygame.sprite.Group()
legendSprites = pygame.sprite.Group()
tokenSprites = pygame.sprite.Group()
infoRect = pygame.Surface((INFOWIDTH,INFOHEIGHT)) # the size of your rect
infoRect.set_alpha(150) # alpha level infoRect.set_alpha(128)
#infoRect.fill((255,255,255))# this fills the entire surface
infoRect.fill((210,255,215))# this fills the entire surface
heatBtnSize = (65,20) # the size of your rect
heatBntRectal = pygame.Rect(legendOffsetX+250, legendOffsetY-35,heatBtnSize[0],heatBtnSize[1])
heatBtnRect = pygame.Surface(heatBtnSize) # the size of your rect
heatBtnRect.set_alpha(150) # alpha level infoRect.set_alpha(128)
#infoRect.fill((255,255,255))# this fills the entire surface
heatBtnRect.fill((110,255,215))# this fills the entire surface
clearBtnSize = (40,20) # the size of your rect
clearBntRectal = pygame.Rect(legendOffsetX+250, legendOffsetY+19,clearBtnSize[0],clearBtnSize[1])
clearBtnRect = pygame.Surface(clearBtnSize ) # the size of your rect
clearBtnRect.set_alpha(150) # alpha level infoRect.set_alpha(128)
#infoRect.fill((255,255,255))# this fills the entire surface
clearBtnRect.fill((110,255,215))# this fills the entire surface
tokenBtnSize = (55,20) # the size of your rect
tokenBntRectal = pygame.Rect(legendOffsetX+250, legendOffsetY-10,tokenBtnSize[0],tokenBtnSize[1])
tokenBtnRect = pygame.Surface(tokenBtnSize ) # the size of your rect
tokenBtnRect.set_alpha(150) # alpha level infoRect.set_alpha(128)
#infoRect.fill((255,255,255))# this fills the entire surface
tokenBtnRect.fill((110,255,215))# this fills the entire surface
tenxBtnSize = (40,20) # the size of your rect
tenxBntRectal = pygame.Rect(legendOffsetX+250, legendOffsetY+45,tenxBtnSize[0],tenxBtnSize[1])
tenxBtnRect = pygame.Surface(tenxBtnSize ) # the size of your rect
tenxBtnRect.set_alpha(150) # alpha level infoRect.set_alpha(128)
#infoRect.fill((255,255,255))# this fills the entire surface
tenxBtnRect.fill((110,255,215))# this fills the entire surface
BOARDMARGIN = 40
BOARDSIZEX=WINDOWWIDTH-INFOWIDTH-BORDERWIDTH*3-BOARDMARGIN
BOARDSIZEY=WINDOWHEIGHT-BORDERHEIGHT*2-BOARDMARGIN
boardRect = pygame.Surface((BOARDSIZEX,BOARDSIZEY)) # the size of your rect
boardRect.set_alpha(60) # alpha level infoRect.set_alpha(128)
boardRect.fill((255,255,255))# this fills the entire surface
BOARDOFFSETX = BORDERWIDTH*2+INFOWIDTH+BOARDMARGIN/2
BOARDOFFSETY = BORDERHEIGHT+BOARDMARGIN/2
'''
CELLSIZE = 2
wormCCSegmentRect = pygame.Surface((CELLSIZE+2, CELLSIZE+2))
wormCCInnerSegmentRect = pygame.Surface((CELLSIZE-1+2, CELLSIZE-1+2))
wormCCSegmentRect.fill(DARKGREEN)# this fills the entire surface
wormCCInnerSegmentRect.fill(LIGHTGREEN)# this fills the entire surface
wormNCSegmentRect = pygame.Surface((CELLSIZE, CELLSIZE))
wormNCInnerSegmentRect = pygame.Surface((CELLSIZE-1, CELLSIZE-1))
wormNCSegmentRect.fill(DARKERORANGE)# this fills the entire surface
wormNCInnerSegmentRect.fill(DARKORANGE)# this fills the entire surface
'''
try:
ccImage = pygame.image.load('nc.png')
ncImage = pygame.image.load('cc.png')
retailShopImage = pygame.image.load('shop-green.png')
foreignRetailShopImage = pygame.image.load('shop-red.png')
serviceShopImage = pygame.image.load('services.png')
coopShopImage = pygame.image.load('coop.png')
coopServicesShopImage = pygame.image.load('coopservices.png')
coopProductionShopImage = pygame.image.load('coopproduction.png')
productionShopImage = pygame.image.load('production.png')
marketImage = pygame.image.load('city.png')
workerImage = pygame.image.load('worker_sm.png')
curveImage = pygame.image.load('curve.png')
except:
print("png loaded")
#infoRect = pygame.Rect(BORDERWIDTH, BORDERHEIGHT, INFOWIDTH, INFOHEIGHT )
TOTALSTARTINGNC = 0
STOCKGROWTHRATE = 0 #stock increase per cycle?
STOCKCONSUMPTIONRATE = 1
SERVICESGROWTHCYCLE = 4 #services increase per cycle?
SERVICESGROWTHAMOUNT = 0 #services increase per cycle?
stockStartAmt = 5000
stockStartStd = stockStartAmt*.1
servicesStartAmt = 5000
servicesStartStd = servicesStartAmt*.1
STARTSIZE = 5 #dimension of traders
MINSIZE = 4 #smallest size of traders
MAXSIZE = 60 #max size of traders
TILESIZE = 4 #used for heatmap
coolingAmtOrig = 13#amount of cooling for heatmap
heatingAmtOrig = 19#amount of heating for heatmap
coolingFREQOrig = 2#for heatmap number of cycles to wait to cool
coolingAmt = coolingAmtOrig #for heatmap
heatingAmt = heatingAmtOrig #for heatmap
coolingFREQ = coolingFREQOrig #for heatmap number of cycles to wait to cool
TRADESIZE = 5 #size of trade graphic
MINTRADESIZE = 4 #maxsize of trade graphic
MAXTRADESIZE = 10 #minsize of trade graphic
#ccVault = 100000#amount of CC avalible to purchase
#ccXng = 1.5#amount of CC avalible to purchase
AVGTRADE = 200#average amount of $ traded
STDTRADE = 225#gaussian standard deviation from average Trade size
MINTRADEAMT = 50#int(AVGTRADE/3.0) #smallest $ trade possible
MAXTRADEAMT = 1000#int(AVGTRADE*3.0) #largest $ trade possible
IMPORTMULT = 4.00 #scaling the effect of market seasonaly
#TRADESCALEFACTOR = 0.8 #was used for scaling trade
IMPORTMULTSTEP=0.5
IMPORTMULTMAX=3.5#20.0
ccPercent = 0.1# Percentage of CC is accepted by retail shops
ccPercentStep = 0.05 # Optional stepping
ccLocalPercent = 1.0 #Percentage of CC accespted by local shops
ccLocalPercentStep = 0.01 # Optional stepping
#ncStartRange = 5000 # Amount of National Currency allocated at start
ncStartAmt = 500#10000 # Amount of National Currency allocated at start
ncStartStd = ncStartAmt*.2 # Amount of National Currency allocated at start
ncEndAmt = 300000 # Optional stepping
ncStepAmt = 500 # Optional stepping
ccStartAmt = 0 #Amount of CC allocated at start
ccStepAmt = 100
ccEndAmt = 5000
maxSavings = 5000 #maxSavings amount of savings
minSavings = 500 #minimum amount of savings
STARTSAVINGS = 0#400*MAXTRADERS #inital bank collateral
fractionalReserve = 0.10
#text_file = open("stats-v043-hpc.csv", "w")
#text_file.write('cclMode, ccPer,ccAmt,ncAmt,NCPur,CCPur,TotPur,exported,AllTrade,NCNumSales,CCNumSales,retailTradeNC,retailTradeCC,retailNC+CC,nonRetailNC, nonRetailCC, nonRetailNC+CC, cycles, bSaved, bLoaned, bDebt, bSavings, bNC\n')
NEIGHBORSEARCHSIZE = 200 #square area of nearest trade partners
MAXNEIGHBORSEARCHSIZE = NEIGHBORSEARCHSIZE*4 #square area of nearest trade partners
NUMTRADEPARTNERS = 5 # total number of trading partners
if MAXTRADERS <=5:
#numBuddies = MAXTRADERS-1 #those nearest
NUMTRADEPARTNERS = MAXTRADERS-1 # total number of trading partners
#elif MAXTRADERS >30:
#numBuddies = MAXTRADERS-1 #those nearest
# NUMTRADEPARTNERS = 15 # total number of trading partners
#MAXTRADES = 1 # of active trades between Trader and TradePartners
theta = np.linspace(0.0, 2 * np.pi, MAXTRADERS, endpoint=False)
thetawidth = (2*np.pi) / MAXTRADERS
pltColor = 'gold'
TRADEBINTICKS = DAILYCYCLES*3 #count the volume of trade in this many ticks = 1 week
PLTFREQ = TRADEBINTICKS #how often to update the plots automatically
pause = False
if autoMode == True:
#importMode = False
#exportMode = False
#seasonalMode = True#False
#heatOn = False
#heatMode = True
#ccMode = True#False
#savingsMode = False
#loanMode = False
clearingMode = False
ONEYEAR = DAILYCYCLES*365
HALFYEAR = int(ONEYEAR/2.0)
QUARTERYEAR = int(HALFYEAR/2.0)
MONTH = ONEYEAR/12
#Cycles used in autoMode
heatModeCycle = 30*ONEYEAR
importModeCycle = 30*ONEYEAR
exportModeCycle = 30*ONEYEAR#STARTDATE+timedelta(years=30)#30*ONEYEAR#2*MONTH
seasonalModeCycle = 30*ONEYEAR#STARTDATE+timedelta(years=30)#30*ONEYEAR#4*MONTH
ccModeCycle = 30*ONEYEAR#STARTDATE+timedelta(years=30)#30*ONEYEAR#1*ONEYEAR+8*MONTH
savingsModeCycle = 30*ONEYEAR#STARTDATE+timedelta(years=30)#999*0.5*MONTH#1*ONEYEAR+8*MONTH
loanModeCycle = 30*ONEYEAR#STARTDATE+timedelta(years=30)#9999*0.5*MONTH#1*ONEYEAR+8*MONTH
clearingModeCycle = DAILYCYCLES*15#30*ONEYEAR#STARTDATE+timedelta(days=15)#1*int(MONTH/2)
endCycle = 66*ONEYEAR#STARTDATE+timedelta(months=18)#1*ONEYEAR+8*MONTH
repeatCycle = 0#2*ONEYEAR#500*DAILYCYCLES#MONTH#0.25*MONTH#1*ONEYEAR # how long to run in repeatMode
numRepeatsTot = 1
lastRepeatCycle = 0
lastRepeatCycleTicks = 0
numRepeats = 0
overAllCycle = 0
tickLocs = [1, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 350]
#monthTicks = ('Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun')
#relative amount of exportationbuying external goods
#seasonalMarketArray = [ .5, .6, .4, .5, .4, .95, .5, .05, .2, .6, .4, .55, .5]
monthTicks = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan')
#seasonalMarketArray = [.05, .2, .6, .4, .55, .5, .5, .6, .4, .5, .4, .95, .5, .05]
seasonalMarketArray = [.05, .2, .4, .5, .6, .4, .5, .3, .4, .3, .9, 1.2, 1.1, .05]
seasonalImportSmooth = []
seasonalImportOrig = []
seasonalImportFlat = []
sRounds = []
importExportRatio = 1.08
DAYSINYEAR=365
rounds = DAYSINYEAR #number of days in a year for seasonality
cycles = 0
def toggleHeatMode(onswitch):
global heatMode
global heatingAmt
global coolingAmt
heatMode = onswitch
if heatMode == False: #coolit
heatingAmt = 0
else:
heatingAmt = heatingAmtOrig
coolingAmt = coolingAmtOrig
coolingFREQ = coolingFREQOrig
heatOn=True
print ("Adjust HeatMap Mode", heatMode)
def toggleCCMode(onswitch,players):
return
global ccMode
ccMode = onswitch
#ccAmt = 100
for p in players:
if ccMode == False: #coolit
p.cc = []#0
else:
p.cc = []#p.STARTCC
print ("Adjust CC Mode", ccMode)
def toggleSavingsMode(onswitch):
global savingsMode
savingsMode = onswitch
print ("Adjust Savings Mode", savingsMode)
def toggleLoanMode(onswitch):
global loanMode
loanMode = onswitch
print ("Adjust Loan Mode", loanMode)
def toggleImportMode(onswitch):
global importMode
importMode = onswitch
print ("Adjust Import Mode", importMode)
def toggleClearingMode(onswitch):
global clearingMode
clearingMode = onswitch
#print ("Adjust Clearing Mode", clearingMode)
def toggleExportMode(onswitch):
global exportMode
exportMode = onswitch
print ("Adjust export Mode", exportMode)
def toggleBondingMode(onswitch):
global bondingMode
global curveImage
bondingMode = onswitch
if bondingMode == False:
for le in legendSprites:
if le.legendType == utils.EXCHANGE:
newImage = pygame.image.load('curve.png').convert_alpha()
curveImage = newImage
le.image = newImage
for tt in traders:
if tt.ownToken == False:
tt.preferedToken = None
elif bondingMode == True:
for le in legendSprites:
if le.legendType == utils.EXCHANGE:
newImage = pygame.image.load('curve2.png').convert_alpha()
#newImage = pygame.transform.rotozoom(newImage, 0, 1.6)
#utils.fill(newImage,pygame.Color(3, 67, 100, 50))
curveImage = newImage
le.image = newImage
for tt in traders:
topBal = 0
topToken = None
tt.preferedToken = None
for cci in tt.cc:
if cci.balance > topBal and cci.token.trading:
topBal = cci.balance
topToken = cci.token
if topToken is not None:
tt.preferedToken = topToken
print ("prefered token", utils.currencyTypeToString(topToken.tokenID))
print ("Adjust bondingMode", bondingMode)
def toggleSeasonalMode(onswitch):
global seasonalMode
global seasonalImportSmooth
global seasonalImportOrig
global seasonalImportFlat
seasonalMode = onswitch
if seasonalMode == False:
seasonalImportSmooth = seasonalImportFlat
else:
seasonalImportSmooth = seasonalImportOrig
print ("Adjust Seasonal Mode ", seasonalMode)
#return the current day based ont he start day
def cyclesToDate():
global cycles
global DAILYCYCLES
simdays = int(cycles/DAILYCYCLES)
STARTDATE = datetime.datetime(2018, 8, 7, 00, 00) #1st trading on blockchain of a tomato in Kenya
#STARTDATE = datetime.datetime(2017, 12, 1, 00, 00)
currentDate = STARTDATE+timedelta(days=simdays)
#print ("Current Date: ",currentDate.isoformat(' '))
return currentDate #currentDate.day
def cyclesToMonth():
days = cyclesToDays()
months = int(days/MONTHS)
return months
def buddiesMode(event,t):
#print ("Show everyone who clicked Trader trades with!")
global clientsModeB
for z in t.tradeBuddies:
z.drawCon =True
z.drawConColor = PURPLE
z.drawSelf(background)
clientsModeB = False
if displayTrade:
pygame.display.update()
def clientsMode(event,t):
# If the mouse moves on top of a player - set his fill and his tradebuddies
#print ("Show everyone who trades with clicked Trader!")
global clientsModeB
for z in traders:
for zt in z.tradeBuddies:
if zt.rect.center == t.rect.center:
z.drawCon =True
z.drawConColor = RED
z.drawSelf(background)
clientsModeB = True
if displayTrade:
pygame.display.update()
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
global pause
global displayPlots
global importMode
global exportMode
global savingsMode
global loanMode
while True:
for event in pygame.event.get():
if event.type == QUIT:
print("<><><>Terminate on Key Press")
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
print("<><><>Terminate on Key Press")
terminate()
elif event.key == pygame.K_SPACE:
pause = True
print ("PAUSE")
paused()
elif event.key == pygame.K_p:
displayPlots = True
print ("PLOTS1")
return
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
def paused():
global pause
print ("Paused called", pause)
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == KEYUP:
if event.key == K_ESCAPE: # pressing escape quits
print("<><><>Terminate on Key Press")
terminate()
elif event.key == pygame.K_SPACE:
pause = False
elif event.key == pygame.K_p:
displayPlots = True
print ("PLOTS2")
return
pygame.display.update()
#mainClock.tick(FPS)
mainClock.tick()
def getGini(allPlayers):
moneyList = []
for p in allPlayers:
moneyList.append(p.nc)
#print (moneyList)
result = GRLC(moneyList)
return float(result[0])
def toggleSeedingMode(traders,mode):
if False: #mode==True:
for b in traders:
if b.subType!=utils.FOREIGNRETAIL:
b.cc = []#ccStartAmt
b.STARTCC = ccStartAmt
b.debt = ccStartAmt
b.aScale = (STARTSIZE-MINSIZE)/float(1+b.STARTNC+b.STARTSTOCK+b.STARTCC+b.STARTSERVICES)
b.maxMoney = (MAXSIZE - b.bScale)/b.aScale
b.minMoney = (MINSIZE - b.bScale)/b.aScale
theBank.debt = theBank.debt + ccStartAmt
theBank.savings = theBank.savings + ccStartAmt
theBank.loaned = theBank.loaned + ccStartAmt
theBank.saved = theBank.saved + ccStartAmt
else:
for b in traders:
if b.subType!=utils.FOREIGNRETAIL:
b.cc = []
b.STARTCC = 0
b.aScale = (STARTSIZE-MINSIZE)/float(1+b.STARTNC+b.STARTSTOCK+b.STARTCC+b.STARTSERVICES)
b.maxMoney = (MAXSIZE - b.bScale)/b.aScale
b.minMoney = (MINSIZE - b.bScale)/b.aScale
#b.debt = ccStartAmt
theBank.debt = 0
theBank.savings = 0
theBank.loaned = 0
theBank.saved = 0
def generateTraders(traders):
global theBank
global theMarkets
global TOTALSTARTINGNC
global numStartCoops
global clickedTrader
sCoops = 0
pCoops = 0
zIndex = 0
for i in range(0, pEXPORTSERVICE, 1):
t = Trader(utils.GENERIC,100,100,zIndex)
t.setupExportServiceTrader()
traders.append(t)
zIndex = zIndex+1
TOTALSTARTINGNC=TOTALSTARTINGNC+t.nc
for i in range(0, pRETAIL, 1):
t = Trader(utils.GENERIC,100,100,zIndex)
t.setupRetailShop()
traders.append(t)
zIndex = zIndex+1
TOTALSTARTINGNC=TOTALSTARTINGNC+t.nc
for i in range(0, pFOREIGNRETAIL, 1):
t = Trader(utils.GENERIC,100,100,zIndex)
t.setupForeignRetailShop()
traders.append(t)
zIndex = zIndex+1
TOTALSTARTINGNC=TOTALSTARTINGNC+t.nc
for i in range(0, pLOCALSERVICE, 1):
t = Trader(utils.GENERIC,100,100,zIndex)
zIndex = zIndex+1
TOTALSTARTINGNC=TOTALSTARTINGNC+t.nc
if sCoops < numStartSCoops:
t.coop = True
print("serviceCoop")
sCoops +=1
t.setupLocalServices()
traders.append(t)
for i in range(0, pLOCALPRODUCER, 1):
t = Trader(utils.GENERIC,100,100,zIndex)
zIndex = zIndex+1
TOTALSTARTINGNC=TOTALSTARTINGNC+t.nc
if pCoops < numStartPCoops:
t.coop = True
print("ProdCoop")
pCoops +=1
#t = Trader(utils.GENERIC,OFFSETWIDTH+SUBWINDOWWIDTH/2+BORDERWIDTH/2,OFFSETHEIGHT+SUBWINDOWHEIGHT-BORDERHEIGHT*3-5,zIndex)
t.setupLocalProduction()
traders.append(t)
def isntViewable(newPos):
if newPos[0]>=(BOARDOFFSETX+BOARDSIZEX) or newPos[0]<=BOARDOFFSETX or newPos[1]>=(BOARDOFFSETY+BOARDSIZEY-30) or newPos[1]<=BOARDOFFSETY+30:
return True
else:
return False
def generateTraderLocationsSpiral(traders):
xinc = 2
yinc = 2
radius = 100.0
rotation = np.pi
startAngle = 0.0
numSpokes = 10
resolution = radius / numSpokes#len(traders)
#print ("resolution",resolution)
radiusIncrement = 20#radius / resolution
rotationIncrement = rotation / resolution
spokeRotationIncrement = (np.pi * 2.0) / 5#float(numSpokes)
spokeRotation = startAngle
direction = 1
extraOff = 32
startx = INFOWIDTH+OFFSETWIDTH*2
endx = WINDOWWIDTH
starty = extraOff
endy = WINDOWHEIGHT
pos = (int(INFOWIDTH+(endx-startx)/2),int((endy-starty)/2))
#print ("startPos ",pos)
#keep moving the radius out (will have to stager Trader Types)
curRadius = radiusIncrement#0.0
curAngle = spokeRotation
tradersShuffle = utils.shuffleMix(traders)
for t in tradersShuffle:
#if t.coop==True:
# continue
#while curRadius <= radius:
newx = int(curRadius * np.sin(curAngle))
newy = int(curRadius * np.cos(curAngle))
newPos = (pos[0] + newx, pos[1] + (direction * newy))
if isntViewable(newPos):
#print(newPos[0])
#print("x range: ",startx, endx-extraOff,utils.traderTypeToString(t.subType))
#print(newPos[1])
#print("y range: ",extraOff,endy-extraOff, utils.traderTypeToString(t.subType))
direction = direction*-1
curRadius = radiusIncrement*2.5
curAngle = spokeRotation#spokeRotationIncrement
newx = int(curRadius * np.sin(curAngle))
newy = int(curRadius * np.cos(curAngle))
newPos = (pos[0] + newx, pos[1] + (direction * newy))
spokeRotation += spokeRotationIncrement
t.setLocation(newPos[0],newPos[1])
collisionRect = True
collisions=0
rounda = 0
tempPos = newPos
finda = 0
#print("index",t.tIndex)
while collisionRect:
tLocXopy = list(traders)
tLocXopy.remove(t)
for odat in tLocXopy:
odatRect = odat.rect.inflate(5,5)
if t.rect.colliderect(odatRect) == True or isntViewable(t.rect.center):
collisionRect = True
collisions=collisions+1
#print ("collided", t.rect, odatRect)
break
if collisionRect == True:
tempPos = (tempPos[0]+xinc,tempPos[1]+yinc)
t.setLocation(tempPos[0],tempPos[1])
finda+=1
if isntViewable(tempPos):
#print ("****---",finda)
if finda > 300:
xinc = xinc*-1
yinc = yinc*-1
tempPos = (newPos[0]+xinc,newPos[1]+yinc)
t.setLocation(tempPos[0],tempPos[1])
finda = 0
elif finda > 200:
xinc = xinc*1
yinc = yinc*-1
tempPos = (newPos[0]+xinc,newPos[1]+yinc)
t.setLocation(tempPos[0],tempPos[1])
elif finda > 100:
xinc = xinc*-1
yinc = yinc*1
tempPos = (newPos[0]+xinc,newPos[1]+yinc)
t.setLocation(tempPos[0],tempPos[1])
if collisions==0:
collisionRect = False
collisions = 0
rounda +=1
#print (rounda)
if rounda > 600:
collisionRect = False
print ("Overlapping Error",round, finda)
Rx = random.randint(startx, endx)
Ry = random.randint(starty, endy)
t.setLocation(Rx,Ry)
curRadius += radiusIncrement
curAngle += rotationIncrement
#pygame.draw.aalines(display, (255, 255, 255), False, spoke)
#t.setLocation(newPos[0],newPos[1])
def generateTraderLocations(traders):
extraOff = 10
#Set location
traderNumt = 0
for t in traders:
#if t.coop==True:
# continue
traderNumt = traderNumt + 1
#while len(traders) < MAXTRADERS:
traderLocx = random.randint(INFOWIDTH+OFFSETWIDTH+BORDERWIDTH+STARTSIZE+extraOff, OFFSETWIDTH+SUBWINDOWWIDTH-STARTSIZE-BORDERWIDTH)
traderLocy = random.randint(OFFSETHEIGHT+BORDERHEIGHT+extraOff, OFFSETHEIGHT+SUBWINDOWHEIGHT-STARTSIZE-BORDERHEIGHT-extraOff)
t.setLocation(traderLocx,traderLocy)
#t = Trader(GENERICTRADER,traderLocx,traderLocy,STARTSIZE,theMarkets)
#largerBankRect = theBank.rect.inflate(50,50)
#don't overlap on other traders
collisionRect = False
maxCollisionChecks = 200
currentCollisionCheck = 1
while collisionRect == False and currentCollisionCheck<maxCollisionChecks:
currentCollisionCheck = currentCollisionCheck +1
#if currentCollisionCheck == maxCollisionChecks:
# print (traderNumt ,"Collision in Locations")
tLocXopy = list(traders)
tLocXopy.remove(t)
for odat in tLocXopy:
#odatRect = odat.rect.inflate(1,1)
odatRect = odat.rect.inflate(5,5)
if t.rect.colliderect(odatRect) == True:
collisionRect = True
#print ("collided", t.rect, odatRect)
break
if collisionRect == True:
traderLocx = random.randint(INFOWIDTH+OFFSETWIDTH+BORDERWIDTH+STARTSIZE+extraOff, OFFSETWIDTH+SUBWINDOWWIDTH-STARTSIZE-BORDERWIDTH)
traderLocy = random.randint(OFFSETHEIGHT+BORDERHEIGHT+extraOff, OFFSETHEIGHT+SUBWINDOWHEIGHT-STARTSIZE-BORDERHEIGHT-extraOff)
#t = Trader(GENERICTRADER,traderLocx,traderLocy,STARTSIZE,theMarkets)
t.setLocation(traderLocx,traderLocy)
collisionRect = False
else:
collisionRect = True
break
def generateTraderLocation(trader):
global traders
extraOff = 10
#Set location
traderNumt = 0
if True:
#if t.coop==True:
# continue
traderNumt = traderNumt + 1
#while len(traders) < MAXTRADERS:
traderLocx = random.randint(INFOWIDTH+OFFSETWIDTH+BORDERWIDTH+STARTSIZE+extraOff, OFFSETWIDTH+SUBWINDOWWIDTH-STARTSIZE-BORDERWIDTH)
traderLocy = random.randint(OFFSETHEIGHT+BORDERHEIGHT+extraOff, OFFSETHEIGHT+SUBWINDOWHEIGHT-STARTSIZE-BORDERHEIGHT-extraOff)
trader.setLocation(traderLocx,traderLocy)
#t = Trader(GENERICTRADER,traderLocx,traderLocy,STARTSIZE,theMarkets)
#largerBankRect = theBank.rect.inflate(50,50)
#don't overlap on other traders
collisionRect = False
maxCollisionChecks = 200
currentCollisionCheck = 1
while collisionRect == False and currentCollisionCheck<maxCollisionChecks:
currentCollisionCheck = currentCollisionCheck +1
#if currentCollisionCheck == maxCollisionChecks:
# print (traderNumt ,"Collision in Locations")
tLocXopy = list(traders)
#tLocXopy.remove(trader)
for odat in tLocXopy:
#odatRect = odat.rect.inflate(1,1)
odatRect = odat.rect.inflate(5,5)
if trader.rect.colliderect(odatRect) == True:
collisionRect = True
#print ("collided", trader.rect, odatRect)
break
if collisionRect == True:
traderLocx = random.randint(INFOWIDTH+OFFSETWIDTH+BORDERWIDTH+STARTSIZE+extraOff, OFFSETWIDTH+SUBWINDOWWIDTH-STARTSIZE-BORDERWIDTH)
traderLocy = random.randint(OFFSETHEIGHT+BORDERHEIGHT+extraOff, OFFSETHEIGHT+SUBWINDOWHEIGHT-STARTSIZE-BORDERHEIGHT-extraOff)
#t = Trader(GENERICTRADER,traderLocx,traderLocy,STARTSIZE,theMarkets)
trader.setLocation(traderLocx,traderLocy)
collisionRect = False
else:
collisionRect = True
break
def generateTradeBuddies(playerList):
for dude in playerList:
if dude.subType==utils.FOREIGNRETAIL:
continue
currentList = list(playerList)
currentList.remove(dude)
#neighborsList = generateNeighbors(dude,currentList,NEIGHBORSEARCHSIZE,numBuddies)
#while len(dude.tradeBuddies) < numBuddies and len(neighborsList) >0: