-
Notifications
You must be signed in to change notification settings - Fork 8
/
it.py
8404 lines (6374 loc) · 378 KB
/
it.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
#!/usr/bin/python
from __future__ import division
import libtcodpy as libtcod
import random
from random import randint as roll
import math
import textwrap
#import shelve
import time
import os
#import multiprocessing
import cProfile as prof
import pstats
import copy
from collections import Counter, defaultdict, namedtuple
import itertools
import logging
import economy
import physics as phys
from traits import TRAITS, TRAIT_INFO, CULTURE_TRAIT_INFO, EXPERIENCE_PER_SKILL_LEVEL, MAX_SKILL_LEVEL
from dijkstra import Dijmap
import gen_languages as lang
import gen_creatures
import religion
import gui
import building_info
import combat
from helpers import *
import config as g
from wmap import *
from map_base import *
import history as hist
import goap
import data_importer as data
mouse = libtcod.Mouse()
key = libtcod.Key()
class Region:
#a Region of the map and its properties
def __init__(self, x, y):
self.region = None
self.x = x
self.y = y
self.color = None
self.char = 255
self.char_color = libtcod.black
self.region_number = None # For figuring out play region
self.agent_slots = {'land':{'slots':g.MAX_ECONOMY_AGENTS_PER_TILE, 'agents':[]}}
self.blocks_mov = False
self.blocks_vis = False
self.res = defaultdict(int)
self.entities = []
self.populations = []
self.objects = []
self.features = []
self.minor_sites = []
self.caves = []
self.all_sites = []
self.associated_events = set([])
self.height = 0
self.temp = 0
# self.rainfall = 0
# old variables, hopefully to be removed!
self.wdist = None
self.moist = None
self.region_number = None
# Chunk will be set after region has been created
self.chunk = None
self.culture = None
self.site = None
self.territory = None
self.explored = False
def add_resource(self, resource_name, amount):
self.res[resource_name] += amount
self.agent_slots[resource_name] = {'slots':g.MAX_ECONOMY_AGENTS_PER_TILE, 'agents':[]}
# Add location to to chunk of world this region is a part of
self.chunk.resources[resource_name].append((self.x, self.y))
def add_resource_gatherer_to_region(self, resource_name, agent):
self.agent_slots[resource_name]['agents'].append(agent)
agent.resource_gathering_region = self
# Add farm only to places with resource gatherers
if resource_name == 'land' and not self.has_minor_site(type_='farm'):
g.WORLD.add_farm(self.x, self.y, city=self.territory)
if resource_name in ('iron', 'bronze', 'copper') and not self.has_minor_site(type_='mine'):
g.WORLD.add_mine(self.x, self.y, city=self.territory)
def remove_resource_gatherer_from_region(self, resource_name, agent):
self.agent_slots[resource_name]['agents'].remove(agent)
agent.resource_gathering_region = None
# In future, abandoning the farm
#if resource_name == 'land' and self.has_minor_site(type_='farm') and not len(self.agent_slots['land']['agents']):
#
def has_open_slot(self, resource_name):
''' Return whether the list of agents working a particular resource is smaller than the limit for the total # of agents that can work it'''
return resource_name in self.agent_slots and ( len(self.agent_slots[resource_name]['agents']) < self.agent_slots[resource_name]['slots'] )
def clear_all_resources(self):
self.res = defaultdict(int)
self.agent_slots = {'land':{'slots':0, 'agents':[]}}
def in_play_region(self):
return g.WORLD.play_region == self.region_number
def has_feature(self, type_):
''' Check if certain feature is in region '''
for feature in self.features:
if feature.type_ == type_:
return 1
return 0
def has_minor_site(self, type_):
''' Check if certain feature is in region '''
for site in self.minor_sites:
if site.type_ == type_:
return 1
return 0
def get_features(self, type_):
''' Returns a list of all features, so that one may get, say, all caves in the region '''
feature_list = []
for feature in self.features:
if feature.type_ == type_:
feature_list.append(feature)
return feature_list
def get_base_color(self):
# Give the map a base color
base_rgb_color = g.MCFG[self.region]['base_color']
if base_rgb_color == 'use_world_map':
base_color = self.color
else:
base_color = libtcod.Color(*base_rgb_color)
return base_color
def add_minor_site(self, site):
''' Takes an already created site and adds it to the map '''
self.minor_sites.append(site)
self.all_sites.append(site)
g.WORLD.all_sites.append(site)
# CHUNK
self.chunk.add_minor_site(site)
def create_and_add_minor_site(self, world, type_, char, name, color):
''' Creates a new instance of a Site and adds it to the map '''
site = Site(world, type_, self.x, self.y, char, name, color)
self.add_minor_site(site)
return site
def add_cave(self, world, name):
cave = Site(world=world, type_='cave', x=self.x, y=self.y, char=g.CAVE_CHAR, name=name, color=libtcod.black, underground=1)
self.caves.append(cave)
self.all_sites.append(cave)
self.char = g.CAVE_CHAR
g.WORLD.all_sites.append(cave)
# CHUNK
self.chunk.add_cave(cave)
def get_location_description(self):
if self.site:
return self.site.name
# Say the name of the site, unless it is being described relative to other cities
elif len(self.minor_sites) or len(self.caves):
site_names = [site.get_name() for site in self.minor_sites + self.caves]
return join_list(site_names)
else:
city, dist = g.WORLD.get_closest_city(self.x, self.y)
if dist == 0:
return '{0}'.format(city.name)
elif 0 < dist <= 3:
return 'the {0} just to the {1} of {2}'.format(pl(self.region), cart2card(city.x, city.y, self.x, self.y), city.name)
elif dist <= 15:
return 'the {0} to the {1} of {2}'.format(pl(self.region), cart2card(city.x, city.y, self.x, self.y), city.name)
elif dist > 75:
return 'the distant {0}ern {1}'.format(cart2card(city.x, city.y, self.x, self.y), pl(self.region))
elif dist > 50:
return 'the {0} far, far to the {1} of {2}'.format(pl(self.region), cart2card(city.x, city.y, self.x, self.y), city.name)
elif dist > 15:
return 'the {0} far to the {1} of {2}'.format(pl(self.region), cart2card(city.x, city.y, self.x, self.y), city.name)
else:
return 'the unknown {0}'.format(pl(self.region))
def get_location_description_relative_to(self, relative_location):
wx, wy = relative_location
dist = g.WORLD.get_astar_distance_to(self.x, self.y, wx, wy)
if self.x == wx and self.y == wy:
return 'this very place'
elif dist is None:
return 'the unreachable {0}'.format(pl(self.region))
elif dist < 30:
return 'the {0} about {1} days\' journey to the {2}'.format(pl(self.region), dist, cart2card(wx, wy, self.x, self.y))
else:
return 'the {0} far to the {1}'.format(pl(self.region), cart2card(wx, wy, self.x, self.y))
class World(Map):
def __init__(self, width, height):
Map.__init__(self, width, height)
self.time_cycle = TimeCycle(self)
self.sites = []
self.all_sites = []
self.resources = []
self.ideal_locs = []
self.dynasties = []
self.all_figures = []
self.important_figures = []
self.famous_objects = set([])
### TODO - move this around; have it use the actual language of the first city
self.moons, self.suns = religion.create_astronomy()
self.equator = None
self.mountains = []
self.rivers = []
# Contiguous region set for play:
self.play_region = None
# Tuple of all play tiles
self.play_tiles = None
# Set up other important lists
self.default_mythic_culture = None
self.sentient_races = []
self.brutish_races = []
self.cultures = []
self.languages = []
self.ancient_languages = []
self.lingua_franca = None
self.cities = []
self.hideouts = []
self.factions = []
self.site_index = defaultdict(list)
# Dijmap where cities are the root nodes; set after cities are generated
self.distance_from_civilization_dmap = None
self.tiles_with_potential_encounters = set([])
## Set on initialize_fov() call
self.fov_recompute = False
self.fov_map = None
self.path_map = None
self.rook_path_map = None
self.road_fov_map = None
self.road_path_map = None
# economy.setup_resources()
#### load phys info ####
phys.main()
# Out of order for now, to get creation myth on load screen
self.gen_mythological_creatures()
self.cm = religion.CreationMyth(creator=self.default_mythic_culture.pantheon.gods[0], pantheon=self.default_mythic_culture.pantheon)
self.cm.create_myth()
#self.generate()
def add_famous_object(self, obj):
self.famous_objects.add(obj)
def remove_famous_object(self, obj):
self.famous_objects.remove(obj)
def add_to_site_index(self, site):
self.site_index[site.type_].append(site)
def generate(self):
#### Setup actual world ####
steps = 6
g.game.render_handler.progressbar_screen('Generating World Map', 'creating regions', 1, steps, [] ) # self.cm.story_text)
self.setup_world()
########################### Begin with heightmap ##################################
g.game.render_handler.progressbar_screen('Generating World Map', 'generating heightmap', 2, steps, []) # self.cm.story_text)
self.make_heightmap()
## Now, loop through map and check each land tile for its distance to water
g.game.render_handler.progressbar_screen('Generating World Map', 'setting moisture', 3, steps, []) # self.cm.story_text)
self.calculate_water_dist()
##### EXPERIMENTOIAENH ######
#self.calculate_rainfall()
########################## Now, generate rivers ########################
g.game.render_handler.progressbar_screen('Generating World Map', 'generating rivers', 4, steps, []) # self.cm.story_text)
self.gen_rivers()
################################ Resources ##########################################
g.game.render_handler.progressbar_screen('Generating World Map', 'setting resources and biome info', 5, steps, []) #self.cm.story_text)
# Print out creation myth
#for line in self.cm.story_text:
# g.game.add_message(line)
self.set_resource_and_biome_info()
##### End setup actual world #####
# For pathing
self.divide_into_regions()
######## Add some buttons #######
panel2.wmap_buttons = [
gui.Button(gui_panel=panel2, func=self.gen_history, args=[1],
text='Generate History', topleft=(4, g.PANEL2_HEIGHT-11), width=20, height=5, color=g.PANEL_FRONT, do_draw_box=True),
gui.Button(gui_panel=panel2, func=self.generate, args=[],
text='Regenerate Map', topleft=(4, g.PANEL2_HEIGHT-6), width=20, height=5, color=g.PANEL_FRONT, do_draw_box=True)
]
def tile_blocks_mov(self, x, y):
if self.tiles[x][y].blocks_mov:
return True
def draw_world_objects(self):
# Just have all world objects represent themselves
for figure in g.WORLD.all_figures:
if not self.tiles[figure.wx][figure.wy].site:
figure.w_draw()
for site in self.sites:
site.w_draw()
if g.player is not None:
g.player.w_draw()
#####################################
def make_world_road(self, x, y):
''' Add a road to the tile's features '''
if not self.tiles[x][y].has_feature('road'):
self.tiles[x][y].features.append(Feature(type_='road', x=x, y=y))
def set_road_tile(self, x, y):
N, S, E, W = 0, 0, 0, 0
if self.tiles[x+1][y].has_feature('road'):
E = 1
if self.tiles[x-1][y].has_feature('road'):
W = 1
if self.tiles[x][y+1].has_feature('road'):
S = 1
if self.tiles[x][y-1].has_feature('road'):
N = 1
char = self.get_line_tile_based_on_surrounding_tiles(N, S, E, W)
if char is None:
return
self.tiles[x][y].char = char
self.tiles[x][y].char_color = libtcod.darkest_sepia
def get_line_tile_based_on_surrounding_tiles(self, N, S, E, W):
''' Determines a tile for a river or road based on the connections it has '''
if N and S and E and W: char = 648 # chr(197)
elif N and S and E: char = 644 # chr(195)
elif N and E and W: char = 640 # chr(193)
elif S and E and W: char = 642 # chr(194)
elif N and S and W: char = 614 # chr(180)
elif E and W: char = 646 # chr(196)
elif E and N: char = 638 # chr(192)
elif N and S: char = 612 # chr(179)
elif N and W: char = 688 # chr(217)
elif S and W: char = 636 # chr(191)
elif S and E: char = 690 # chr(218)
elif N: char = 612 # chr(179)
elif S: char = 612 # chr(179)
elif E: char = 646 # chr(196)
elif W: char = 646 # chr(196)
elif not (N and S and E and W):
char = 255 # Empty character
return char
def get_surrounding_tile_heights(self, coords):
''' Return a list of the tile heights surrounding this one, including this tile itself '''
x, y = coords
heights = []
for xx in xrange(x-1, x+2):
for yy in xrange(y-1, y+2):
if self.is_val_xy((xx, yy)):
heights.append(self.tiles[xx][yy].height)
# If map edge, just append this tile's own height
else:
heights.append(self.tiles[x][y].height)
return heights
def get_surrounding_heights(self, coords):
world_x, world_y = coords
surrounding_heights = []
for x in xrange(world_x-1, world_x+2):
for y in xrange(world_y-1, world_y+2):
surrounding_heights.append(self.tiles[x][y].height)
return surrounding_heights
def get_surrounding_rivers(self, coords):
''' Return a list of the tile heights surrounding this one, including this tile itself '''
x, y = coords
river_dirs = []
for xx, yy in get_border_tiles(x, y):
if self.is_val_xy((xx, yy)) and self.tiles[xx][yy].has_feature('river'):
river_dirs.append((x-xx, y-yy))
## Quick hack for now - append oceans to rivers
if len(river_dirs) == 1:
for xx, yy in get_border_tiles(x, y):
if self.is_val_xy((xx, yy)) and self.tiles[xx][yy].region == 'ocean':
river_dirs.append((x-xx, y-yy))
break
return river_dirs
def get_closest_city(self, x, y, max_range=1000, valid_cities='all_cities_in_world'):
''' Find closest city from a given location. Optionally pass in a list of cities to restrict search by '''
cities = self.cities if valid_cities == 'all_cities_in_world' else valid_cities
# Attepmt to shave some time from the expensive astar algo below by checking if the current tile is a valid city,
# and cut the function short by returning that site if so
if self.tiles[x][y].site and self.tiles[x][y].site in cities:
return self.tiles[x][y].site, 0
# Normal case - loop through all cities and track distance / closest distance until we find the minimum
closest_city = None
closest_dist = max_range + 1 #start with (slightly more than) maximum range
for city in cities:
dist = self.get_astar_distance_to(x, y, city.x, city.y)
if dist < closest_dist: #it's closer, so remember it
closest_city = city
closest_dist = dist
return closest_city, closest_dist
def find_nearby_resources(self, x, y, distance):
# TODO - this code is pretty gnarly :-/
# Make a list of nearby resources at particular world coords
nearby_resources = []
nearby_resource_locations = []
for wx in xrange(x - distance, x + distance + 1):
for wy in xrange(y - distance, y + distance + 1):
if self.is_val_xy( (wx, wy) ) and self.tiles[wx][wy].res:
# Make sure there's a path to get the resource from (not blocked by ocean or whatever)
path = libtcod.path_compute(self.rook_path_map, x, y, wx, wy)
new_path_len = libtcod.path_size(self.rook_path_map)
if new_path_len:
for resource in self.tiles[wx][wy].res.iterkeys():
## Only add it if it's not already in it, and if we don't have access to it
if not resource in nearby_resources: # and not resource in self.native_res.keys():
nearby_resources.append(resource)
nearby_resource_locations.append((wx, wy))
elif resource in nearby_resources:
## Check whether the current instance of this resource is closer than the previous one
cur_dist = self.get_astar_distance_to(x, y, wx, wy)
prev_res_ind = nearby_resources.index(resource)
px, py = nearby_resource_locations[prev_res_ind]
prev_dist = self.get_astar_distance_to(x, y, px, py)
if cur_dist < prev_dist:
del nearby_resources[prev_res_ind]
del nearby_resource_locations[prev_res_ind]
nearby_resources.append(resource)
nearby_resource_locations.append((wx, wy))
return nearby_resources, nearby_resource_locations
def get_closest_resource(self, x, y, resource):
''' Given world x and y coords, find the closest instance of a particular resource '''
initial_chunk = self.tiles[x][y].chunk
resource_locations = [location for location in initial_chunk.resources[resource] if resource in initial_chunk.resources]
# Check if there are any on this chunk
closest_distance, closest_location = self.get_closest_location(x=x, y=y, locations=resource_locations)
# If there is a distance, and it's less than the chunk size, then this is a good location
if 0 <= closest_distance <= self.chunk_size:
return closest_distance, closest_location
# Find a list of nearby chunks to check the resources of - arbitrarily setting # of chunks to 5 for now
resource_locations = [location for chunk in self.get_nearby_chunks(chunk=initial_chunk, distance=3)
if chunk != initial_chunk for location in chunk.resources[resource]
if resource in chunk.resources and self.tiles[location[0]][location[1]].in_play_region()]
closest_distance, closest_location = self.get_closest_location(x=x, y=y, locations=resource_locations)
return closest_distance, closest_location
def get_random_location_away_from_civilization(self, min_dist, max_dist):
''' Finds a random tile in the play area that is within a range of distances from civilization '''
assert min_dist <= max_dist
# Loop through the play tiles until a tile is found that meets the criteria
while True:
wx, wy = random.choice(self.play_tiles)
if min_dist <= self.distance_from_civilization_dmap.dmap[wx][wy] <= max_dist:
break
return (wx, wy)
def setup_world(self):
# Fill world with empty regions
self.tiles = [[Region(x=x, y=y) for y in xrange(self.height)] for x in xrange(self.width)]
# Initialize the chunks inthe world - method inherited from map_base
self.setup_chunks(chunk_size=10, map_type='world')
# Equator line - temperature depends on this. Varies slightly from map to map
self.equator = int(round(self.height / 2)) + roll(-5, 5)
def distance_to_equator(self, y):
return abs(y - self.equator) / (self.height / 2)
def make_heightmap(self):
hm = libtcod.heightmap_new(self.width, self.height)
# Start with a bunch of small, wide hills. Keep them relatively low
for iteration in xrange(200):
maxrad = roll(10, 50)
x, y = roll(maxrad, self.width - maxrad), roll(maxrad, self.height - maxrad)
if libtcod.heightmap_get_value(hm, x, y) < 80:
libtcod.heightmap_add_hill(hm, x, y, roll(1, maxrad), roll(10, 25))
if roll(1, 4) == 1:
libtcod.heightmap_dig_hill(hm, x, y, roll(4, 20), roll(10, 30))
# Then add mountain ranges. Should be tall and thin
for iteration in xrange(100):
maxrad = 5
maxlen = 20 + maxrad
minheight = 5
maxheight = 10
x = roll(maxlen, self.width - maxlen)
y = roll(int(round(self.height / 10)), self.height - int(round(self.height / 10)))
if libtcod.heightmap_get_value(hm, x, y) < 120:
libtcod.line_init(x, y, roll(x - maxlen, x + maxlen), roll(y - maxlen, y + maxlen))
nx, ny = x, y
while nx is not None:
if libtcod.heightmap_get_value(hm, x, y) < 140:
libtcod.heightmap_add_hill(hm, nx, ny, roll(1, maxrad), roll(minheight, maxheight))
nx, ny = libtcod.line_step()
## Added 4/28/2014 - World size must be a power of 2 plus 1 for this to work
#libtcod.heightmap_mid_point_displacement(hm=hm, rng=0, roughness=.5)
# Erosion - not sure exactly what these params do
libtcod.heightmap_rain_erosion(hm=hm, nbDrops=self.width * self.height, erosionCoef=.05, sedimentationCoef=.05, rnd=0)
# And normalize heightmap
#libtcod.heightmap_normalize(hm, mi=1, ma=255)
libtcod.heightmap_normalize(hm, mi=1, ma=220)
#libtcod.heightmap_normalize(hm, mi=20, ma=170)
### Noise to vary wdist ### Experimental code ####
mnoise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
octaves = 20
div_amt = 20
thresh = .4
thresh2 = .8
scale = 130
mvar = 30
### End experimental code ####
# Add the info from libtcod's heightmap to the world's heightmap
for x in xrange(self.width):
for y in xrange(self.height):
############# New ####################
val = libtcod.noise_get_turbulence(mnoise, [x / div_amt, y / div_amt], octaves, libtcod.NOISE_SIMPLEX)
#### For turb map, low vals are "peaks" for us ##############
if val < thresh and self.height / 10 < y < self.height - (self.height / 10):
raise_terr = int(round(scale * (1 - val))) + roll(-mvar, mvar)
elif val < thresh2:
raise_terr = int(round((scale / 2) * (1 - val))) + roll(-int(round(mvar / 2)), int(round(mvar / 2)))
else:
raise_terr = 0
self.tiles[x][y].height = int(round(libtcod.heightmap_get_value(hm, x, y))) + raise_terr
self.tiles[x][y].height = min(self.tiles[x][y].height, 255)
if not 5 < x < self.width - 5 and self.tiles[x][y].height >= g.WATER_HEIGHT:
self.tiles[x][y].height = 99
#######################################
if self.tiles[x][y].height > 200:
self.mountains.append((x, y))
#### While we're looping, we might as well add temperature information
# weird formula for approximating temperature based on height and distance to equator
''' Original settings '''
base_temp = 16
height_mod = ((1.05 - (self.tiles[x][y].height / 255)) * 4)
equator_mod = (1.3 - self.distance_to_equator(y)) ** 2
''' Newer expermiental settings '''
#base_temp = 40
#height_mod = 1
#equator_mod = (1.3 - self.distance_to_equator(y)) ** 2
self.tiles[x][y].temp = base_temp * height_mod * equator_mod
#### And start seeding the water distance calculator
if self.tiles[x][y].height < g.WATER_HEIGHT:
self.tiles[x][y].wdist = 0
self.tiles[x][y].moist = 0
else:
self.tiles[x][y].wdist = None
self.tiles[x][y].moist = 100
# Finally, delete the libtcod heightmap from memory
libtcod.heightmap_delete(hm)
'''
def calculate_rainfall(self):
# An ok way to calclate rainfall?
for y in xrange(self.height):
# Seed initial rainfall based on lattitude
if 30 < y < self.height-30 or 20 < abs(y-self.equator):
rainfall = -10
else:
rainfall = 10
# West -> east winds
for x in xrange(self.width):
self.tiles[x][y].rainfall = rainfall
if self.tiles[x][y].height <= g.WATER_HEIGHT:
rainfall += 1
elif self.tiles[x][y].height <= g.MOUNTAIN_HEIGHT:
rainfall -= 1
else:
rainfall = 0
# East -> west winds
#for x in xrange(self.width):
# self.tiles[self.width-x][y].rainfall = rainfall
#
# if self.tiles[self.width-x][y].height <= g.WATER_HEIGHT:
# rainfall += 1
# elif self.tiles[self.width-x][y].height <= g.MOUNTAIN_HEIGHT:
# rainfall -= 1
# else:
# rainfall = 0
'''
def calculate_water_dist(self):
## Essentially a dijisktra map for water distance
wdist = 0
found_square = True
while found_square:
found_square = False
wdist += 1
for x in xrange(1, self.width - 1):
for y in xrange(1, self.height - 1):
if self.tiles[x][y].wdist is None:
# Only check water distance at 4 cardinal directions
#side_dir = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
#corner_dir = [(x-1, y-1), (x-1, y+1), (x+1, y-1), (x+1, y+1)]
for dx, dy in get_border_tiles(x, y):
if self.tiles[dx][dy].wdist == wdist - 1:
self.tiles[x][y].wdist = self.tiles[dx][dy].wdist + 1
# calculate "moisture" to add a little variability - it's related to water dist but takes height into account
# Also, LOWER is MORE moist because I'm lazy
self.tiles[x][y].moist = self.tiles[x][y].wdist * (1.7 - (self.tiles[x][y].height / 255)) ** 2
found_square = True
break
def gen_rivers(self):
self.rivers = []
river_connection_tiles = []
# Walk through all mountains tiles and make a river if there are none nearby
while len(self.mountains) > 1:
# Pop out a random mountain tile
(x, y) = self.mountains.pop(roll(0, len(self.mountains) - 1) )
# Check if another river already exists nearby, and abort if so
make_river = True
for riv_x in xrange(x - 4, x + 5):
for riv_y in xrange(y - 4, y + 5):
if self.tiles[riv_x][riv_y].has_feature('river'):
make_river = False
break
if make_river:
# create a river
#self.tiles[x][y].features.append(River(x=x, y=y))
riv_cur = [(x, y)]
new_x, new_y = x, y
found_lower_height = True
i = 0
while self.tiles[new_x][new_y].height > g.WATER_HEIGHT:
i += 1
if i >= 100:
logging.debug('river loop exceeded 100 iterations')
break
cur_x, cur_y = new_x, new_y
# Rivers try to flow through lower areas
low_height = self.tiles[new_x][new_y].height
if found_lower_height:
found_lower_height = False
for rx, ry in get_border_tiles(new_x, new_y):
if self.tiles[rx][ry].height <= low_height: # and not (nx, ny) in riv_cur:
low_height = self.tiles[rx][ry].height
new_x, new_y = rx, ry
found_lower_height = True
# if it does get trapped in a local minimum, flow in the direction of the lowest distance to water
# and preferentially in the lowest height of these tiles
if not found_lower_height:
wdist = 1000
height = 1000
for nx, ny in get_border_tiles(new_x, new_y):
if self.tiles[nx][ny].wdist <= wdist and self.tiles[nx][ny].height < height and not (nx, ny) in riv_cur:
wdist = self.tiles[nx][ny].wdist
height = self.tiles[nx][ny].height
new_x, new_y = nx, ny
if self.tiles[new_x][new_y].height < g.WATER_HEIGHT:
break
if not self.tiles[new_x][new_y].has_feature('river'):
riv_cur.append((new_x, new_y))
### Rivers cut through terrain if needed, and also make the areas around them more moist
# Try to lower the tile's height if it's higher than the previous tile, but don't go lower than 100
self.tiles[new_x][new_y].height = min(self.tiles[new_x][new_y].height, max(self.tiles[cur_x][cur_y].height - 1, g.WATER_HEIGHT))
for rx, ry in get_border_tiles(new_x, new_y):
self.tiles[rx][ry].moist /= 2
# If a river exists on the new tiles, stop
else:
river_connection_tiles.append((new_x, new_y))
break
# This sets the tile and color of the river
for i, (x, y) in enumerate(riv_cur):
self.tiles[x][y].char_color = libtcod.Color(20, 45, int(round(self.tiles[x][y].height)))
river_feature = River(x=x, y=y)
self.tiles[x][y].features.append(river_feature)
N, S, E, W = 0, 0, 0, 0
#### If this is not the first tile of the river...
if i > 0:
px, py = riv_cur[i - 1]
if i < len(riv_cur) - 1:
nx, ny = riv_cur[i + 1]
d1x, d1y = px - x, py - y
if (d1x, d1y) == (-1, 0) or self.tiles[x - 1][y].height < g.WATER_HEIGHT: W = 1
if (d1x, d1y) == (1, 0) or self.tiles[x + 1][y].height < g.WATER_HEIGHT: E = 1
if (d1x, d1y) == (0, 1) or self.tiles[x][y + 1].height < g.WATER_HEIGHT: S = 1
if (d1x, d1y) == (0, -1) or self.tiles[x][y - 1].height < g.WATER_HEIGHT: N = 1
river_feature.add_connected_dir(direction=(d1x, d1y))
if i < len(riv_cur) - 1:
d2x, d2y = nx - x, ny - y
if (d2x, d2y) == (-1, 0) or self.tiles[x - 1][y].height < g.WATER_HEIGHT: W = 1
if (d2x, d2y) == (1, 0) or self.tiles[x + 1][y].height < g.WATER_HEIGHT: E = 1
if (d2x, d2y) == (0, 1) or self.tiles[x][y + 1].height < g.WATER_HEIGHT: S = 1
if (d2x, d2y) == (0, -1) or self.tiles[x][y - 1].height < g.WATER_HEIGHT: N = 1
river_feature.add_connected_dir(direction=(d2x, d2y))
#### If this is the first tile of the river...
elif i == 0:
if (x - 1, y) in riv_cur: W = 1
elif (x + 1, y) in riv_cur: E = 1
elif (x, y + 1) in riv_cur: S = 1
elif (x, y - 1) in riv_cur: N = 1
char = self.get_line_tile_based_on_surrounding_tiles(N, S, E, W)
self.tiles[x][y].char = char
self.rivers.append(riv_cur)
# Add special tiles where rivers intersect
## TODO - does not work as intended in all cases (considering all nearby tiles when it should only consider ones it has directly connected to)
for x, y in river_connection_tiles:
N, S, E, W = 0, 0, 0, 0
if self.tiles[x-1][y].has_feature('river'): W = 1
if self.tiles[x+1][y].has_feature('river'): E = 1
if self.tiles[x][y+1].has_feature('river'): S = 1
if self.tiles[x][y-1].has_feature('river'): N = 1
char = self.get_line_tile_based_on_surrounding_tiles(N, S, E, W)
self.tiles[x][y].char = char
## Experimental code to vary moisture and temperature a bit
noisemap1 = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
noisemap2 = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
n1octaves = 12
n2octaves = 10
n1div_amt = 75
n2div_amt = 50
n1scale = 20
n2scale = 15
#1576
## Map edge is unwalkable
for y in xrange(self.height):
for x in xrange(self.width):
# moist
w_val = libtcod.noise_get_fbm(noisemap1, [x / n1div_amt, y / n1div_amt], n1octaves, libtcod.NOISE_SIMPLEX)
w_val += .1
self.tiles[x][y].moist = max(0, self.tiles[x][y].moist + int(round(w_val * n1scale)) )
# temp
t_val = libtcod.noise_get_fbm(noisemap2, [x / n2div_amt, y / n2div_amt], n2octaves, libtcod.NOISE_SIMPLEX)
self.tiles[x][y].temp += int(round(t_val * n2scale))
### End experimental code ####
def set_resource_and_biome_info(self):
''' TODO NEW FUNCTION DEFINITION TO MODIFY FOR NEW RAIN CODE '''
''' Finally, use the scant climate info generated to add biome and color information '''
mountain_height = g.MOUNTAIN_HEIGHT # minor optimization to make variable local
water_height = g.WATER_HEIGHT # minor optimization to make variable local
taiga_chars = (chr(5), '^')
forest_chars = (chr(5), chr(6))
rain_forest_chars = (chr(6), '*')
# Hardcoded positions where tundra cannot go in between (e.g. none in between world y height of tundra_min and tundra_max)
tundra_min = 35
tundra_max = self.height - 35
# Hardcoded positions where tundra cannot go in between (e.g. none in between world y height of tundra_min and tundra_max)
taiga_min = 45
taiga_max = self.height - 45
a = 3 # Used for coloring tiles (each rgb value will vary by +- this #)
for y in xrange(self.height):
for x in xrange(self.width):
this_tile = self.tiles[x][y] # minor optimization to avoid lookups
sc = int(this_tile.height) - 1
mmod = int(round(40 - this_tile.moist) / 1.4) - 25
## Ocean
if this_tile.height < water_height:
this_tile.blocks_mov = True
this_tile.region = 'ocean'
this_tile.clear_all_resources()
if this_tile.height < 75:
this_tile.color = libtcod.Color(7, 13, int(round(sc * 2)) + 10)
else:
this_tile.color = libtcod.Color(20, 60, int(round(sc * 2)) + 15)
#### MOUNTAIN ####
elif this_tile.height > mountain_height:
this_tile.blocks_mov = True
this_tile.blocks_vis = True
this_tile.region = 'mountain'
this_tile.clear_all_resources()
c = int(round((this_tile.height - 200) / 2))
d = -int(round(c / 2))
this_tile.color = libtcod.Color(d + 43 + roll(-a, a), d + 55 + roll(-a, a), d + 34 + roll(-a, a))
if this_tile.height > 235: this_tile.char_color = libtcod.grey # Tall mountain - snowy peak
else: this_tile.char_color = libtcod.Color(c + 38 + roll(-a, a), c + 25 + roll(-a, a), c + 21 + roll(-a, a))
this_tile.char = g.MOUNTAIN_TILE
######################## TUNDRA ########################
elif this_tile.temp < 18 and not (tundra_min < y < tundra_max):
this_tile.region = 'tundra'
this_tile.color = libtcod.Color(190 + roll(-a - 2, a + 2), 188 + roll(-a - 2, a + 2), 189 + roll(-a - 2, a + 2))
######################## TAIGA ########################
elif this_tile.temp < 23 and this_tile.moist < 22 and not (taiga_min < y < taiga_max):
this_tile.region = 'taiga'
this_tile.color = libtcod.Color(127 + roll(-a, a), 116 + roll(-a, a), 115 + roll(-a, a))
if not this_tile.has_feature('river'):
this_tile.char_color = libtcod.Color(23 + roll(-a, a), 58 + mmod + roll(-a, a), 9 + roll(-a, a))
this_tile.char = random.choice(g.TAIGA_TILES)
######################## TEMPERATE FOREST ########################
elif this_tile.temp < 30 and this_tile.moist < 18:
this_tile.region = 'temperate forest'
this_tile.color = libtcod.Color(53 + roll(-a, a), 75 + mmod + roll(-a, a), 32 + roll(-a, a))
if not this_tile.has_feature('river'):
this_tile.char_color = libtcod.Color(25 + roll(-a, a), 55 + mmod + roll(-a, a), 20 + roll(-a, a))
this_tile.char = random.choice(g.FOREST_TILES)
######################## TEMPERATE STEPPE ########################
elif this_tile.temp < 35:
this_tile.region = 'temperate steppe'
this_tile.color = libtcod.Color(65 + roll(-a, a), 97 + mmod + roll(-a, a), 41 + roll(-a, a))
if not this_tile.has_feature('river'):
this_tile.char_color = this_tile.color * .85
this_tile.char = g.TEMPERATE_STEPPE_TILE
######################## RAIN FOREST ########################
elif this_tile.temp > 47 and this_tile.moist < 18:
this_tile.region = 'rain forest'
this_tile.color = libtcod.Color(40 + roll(-a, a), 60 + mmod + roll(-a, a), 18 + roll(-a, a))
if not this_tile.has_feature('river'):
this_tile.char_color = libtcod.Color(16 + roll(-a, a), 40 + roll(-a - 5, a + 5), 5 + roll(-a, a))
this_tile.char = random.choice(g.RAIN_FOREST_TILES)
######################## TREE SAVANNA ########################
elif this_tile.temp >= 35 and this_tile.moist < 18:
this_tile.region = 'tree savanna'
this_tile.color = libtcod.Color(50 + roll(-a, a), 85 + mmod + roll(-a, a), 25 + roll(-a, a))
#this_tile.color = libtcod.Color(209, 189, 126) # grabbed from a savannah image
#this_tile.color = libtcod.Color(139, 119, 56)
if not this_tile.has_feature('river'):
if roll(1, 5) > 1:
this_tile.char_color = this_tile.color * .85
this_tile.char = g.TEMPERATE_STEPPE_TILE
else:
this_tile.char_color = this_tile.color * .75
this_tile.char = g.TREE_SAVANNA_TILE
######################## GRASS SAVANNA ########################
elif this_tile.temp >= 35 and this_tile.moist < 34:
this_tile.region = 'grass savanna'
this_tile.color = libtcod.Color(91 + roll(-a, a), 110 + mmod + roll(-a, a), 51 + roll(-a, a))
#this_tile.color = libtcod.Color(209, 189, 126) # grabbed from a savannah image
#this_tile.color = libtcod.Color(179, 169, 96)
if not this_tile.has_feature('river'):
this_tile.char_color = this_tile.color * .80
this_tile.char = g.TEMPERATE_STEPPE_TILE
######################## DRY STEPPE ########################
elif this_tile.temp <= 44:
this_tile.region = 'dry steppe'
this_tile.color = libtcod.Color(99 + roll(-a, a), 90 + roll(-a, a + 1), 59 + roll(-a, a + 1))
######################## SEMI-ARID DESERT ########################
elif this_tile.temp > 44 and this_tile.moist < 48: