Beispiel #1
0
    def __init__(self, sector, r_factor=0.40, g_factor=0.40, b_factor=0.75, seed=95837203, size=512):
        self.seed = randrange(1,10000) if seed is None else seed
        self.sector = sector

        self.parallax_speed = 0.1

        self.starting_left = 0 - self.sector.screen_width/2
        self.starting_top  = 0 + self.sector.screen_height/2

        self.r_factor = r_factor
        self.g_factor = g_factor
        self.b_factor = b_factor

        self.noise_zoom = 2.0
        self.noise_octaves = 4.0

        self.size = size

        self.r_rand = libtcod.random_new_from_seed(self.seed)
        self.g_rand = libtcod.random_new_from_seed(self.seed+1)
        self.b_rand = libtcod.random_new_from_seed(self.seed+2)
        self.c_rand = libtcod.random_new_from_seed(self.seed*2)
        self.s_rand = libtcod.random_new_from_seed(self.seed*3)

        self.r_noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY, self.r_rand)
        self.g_noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY, self.g_rand)
        self.b_noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY, self.b_rand)
        self.c_noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY, self.c_rand)
        self.s_noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY, self.s_rand)

        self.grid = [[None for i in range(self.size)] for i in range(self.size)]
        self.last_top = None
        self.last_left = None
Beispiel #2
0
    def __init__(self, mapsize, resources):
        self.world_width = mapsize
        self.world_height = self.world_width / 2
        self.grid = []
        self.world_noise = libtcod.noise_new(3)
        self.resource_noise = libtcod.noise_new(3)
        self.name = 'map_name'
        for x in xrange(self.world_width):
            row = []
            for y in xrange(self.world_height):
                row.append(
                    GridCoordinate(x, y, self.world_width, self.world_height,
                                   self.world_noise, self.resource_noise))
            self.grid.append(row)
        libtcod.noise_delete(self.world_noise)
        libtcod.noise_delete(self.resource_noise)
        for x in xrange(self.world_width):
            for y in xrange(self.world_height):
                self.grid[x][y].neighbors = get_neighbors(self, x, y)

        # Spawn resource nodes where the resource density is sufficiently high
        for x in xrange(self.world_width):
            for y in xrange(self.world_height):
                if self.grid[x][y].resource_density > self.RESOURCE_THRESHHOLD:
                    new_node = ResourceNode(x, y, resources)
                    print x, y

        # Pathfinding graph for all land tiles; remove sea tiles and delete
        # neighbor, cost entry in the neighbors list
        self.land_graph = self.grid
        for x in xrange(self.world_width):
            for y in xrange(self.world_height):
                cell = self.land_graph[x][y]
                if cell.elevation >= 0:
                    cell.neighbors = {}
                for key in cell.neighbors.copy():
                    if key.elevation >= 0:
                        if key in cell.neighbors:
                            del cell.neighbors[key]

        # Pathfinding graph for all sea tiles
        self.sea_graph = self.grid
        for x in xrange(self.world_width):
            for y in xrange(self.world_height):
                cell = self.sea_graph[x][y]
                if cell.elevation > 0:
                    cell.neighbors = {}
                for key in cell.neighbors.copy():
                    if key.elevation > 0:
                        if key in cell.neighbors:
                            del cell.neighbors[key]
Beispiel #3
0
	def generate(self):
		print 'Starting world map generation....'
		t0 = libtcod.sys_elapsed_seconds()
		accepted = False
		world = 1
		while not accepted:
			print 'World #' + str(world) + '....'
			self.noise = libtcod.noise_new(2, self.rnd)
			libtcod.noise_set_type(self.noise, libtcod.NOISE_PERLIN)
			game.heightmap = libtcod.heightmap_new(game.WORLDMAP_WIDTH, game.WORLDMAP_HEIGHT)
			#game.precipitation = libtcod.heightmap_new(game.WORLDMAP_WIDTH, game.WORLDMAP_HEIGHT)
			#game.temperature = libtcod.heightmap_new(game.WORLDMAP_WIDTH, game.WORLDMAP_HEIGHT)
			#game.biome = libtcod.heightmap_new(game.WORLDMAP_WIDTH, game.WORLDMAP_HEIGHT)

			self.add_landmass()
			self.smooth_edges()
			self.set_landmass(self.randomize('float', 0.30, 0.45, 3), self.sandheight)
			self.add_rivers()
			self.create_map_images()
			self.place_dungeons()
			accepted = self.analyse_world()
			world += 1
			print '-------------'
		t1 = libtcod.sys_elapsed_seconds()
		print 'World map generation finished.... (%.3f seconds)' % (t1 - t0)
Beispiel #4
0
def test_noise():
    noise = libtcodpy.noise_new(1)
    libtcodpy.noise_set_type(noise, libtcodpy.NOISE_SIMPLEX)
    libtcodpy.noise_get(noise, [0])
    libtcodpy.noise_get_fbm(noise, [0], 4)
    libtcodpy.noise_get_turbulence(noise, [0], 4)
    libtcodpy.noise_delete(noise)
Beispiel #5
0
	def generate(self, empty=False):
		default_block_tiles = {'Dungeon': 'wall', 'Cave': 'cavern wall', 'Maze': 'wall', 'Mountain Peak': 'high mountains', 'Mountains': 'mountains', 'High Hills': 'hills', 'Low Hills': 'medium grass', 'Forest': 'grass', 'Plains': 'grass', 'Coast': 'sand', 'Shore': 'shallow water', 'Sea': 'deep water', 'Ocean': 'very deep water'}
		self.objects = [game.char]
		self.tile = [[{} for y in range(self.map_height)] for x in range(self.map_width)]
		if not empty:
			for x in range(self.map_width):
				for y in range(self.map_height):
					self.set_tile_values(default_block_tiles[self.type], x, y, reset=False)
		game.fov_noise = libtcod.noise_new(1, 1.0, 1.0)
		game.fov_torchx = 0.0
		success = False

		if not empty:
			if self.type == 'Dungeon':
				rooms = self.create_dungeon()
				self.place_doors()
				self.place_objects()
				self.place_traps('floor')
				self.place_stairs(rooms)
			elif self.type == 'Cave':
				while not success:
					success = self.create_cave_maze('cave', 'dirt', 'cavern wall', 55, True)
				self.place_objects()
				self.place_traps('dirt')
				self.add_stalagmites()
			elif self.type == 'Maze':
				while not success:
					success = self.create_cave_maze('maze', 'floor', 'wall', 45, False)
				self.place_objects()
				self.place_traps('floor')
			else:
				self.create_outdoor_map(default_block_tiles[self.type])
				self.place_objects()
Beispiel #6
0
	def __init__(self):
		global debug, font_width, font_height, con, panel, ps, fov_noise, savefiles, baseitems, prefix, suffix, tiles, monsters
		IO.load_settings()
		debug = dbg.Debug()
		debug.enable = True
		for key, value in fonts.items():
			if setting_font == key:
				libtcod.console_set_custom_font(value['file'], libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_ASCII_INROW)
				font_width = value['width']
				font_height = value['height']
		self.init_root_console()
		#libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'Immortal ' + VERSION, False)

		con = libtcod.console_new(MAP_WIDTH, MAP_HEIGHT)
		panel = libtcod.console_new(MESSAGE_WIDTH, MESSAGE_HEIGHT)
		ps = libtcod.console_new(PLAYER_STATS_WIDTH, PLAYER_STATS_HEIGHT)
		fov_noise = libtcod.noise_new(1, 1.0, 1.0)
		savefiles = [f for f in os.listdir('saves') if os.path.isfile(os.path.join('saves', f))]
		IO.load_high_scores()
		baseitems = BaseItemList()
		baseitems.init_parser()
		prefix = PrefixList()
		prefix.init_parser()
		suffix = SuffixList()
		suffix.init_parser()
		tiles = mapgen.TileList()
		tiles.init_parser()
		monsters = MonsterList()
		monsters.init_parser()
		self.main_menu()
    def generateWater(self):
        #noise_octaves = 4.0
        noise_zoom = 2.0
        noise_hurst = libtcod.NOISE_DEFAULT_HURST
        noise_lacunarity = libtcod.NOISE_DEFAULT_LACUNARITY

        mapped = self.mappedArea

        noise = libtcod.noise_new(2, noise_hurst, noise_lacunarity)
        for y in range(self.height):
                for x in range(self.width):
                    f = [noise_zoom * x / (self.width), noise_zoom * y / (self.height)]
                    noisefloat = libtcod.noise_get(noise, f, libtcod.NOISE_PERLIN)
                    if noisefloat >= float(0) and noisefloat <= 0.1:
                        mapped[x][y].tileType = "water"
                        mapped[x][y].blocked = False
                        mapped[x][y].block_sight = False
                        mapped[x][y].slows = True

        #Block the edges of the map so player can't crash the game
        for y in range(self.height):
            #mapped[0][y].tileType = None
            mapped[0][y].blocked = True
            mapped[self.width-1][y].blocked = True
        for x in range(self.width):
            mapped[x][0].blocked = True
            mapped[x][self.height-1].blocked = True
Beispiel #8
0
 def add_noise(self):
     libtcod.heightmap_normalize(self.hm, 0, 1)
     self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST,
                                    libtcod.NOISE_DEFAULT_LACUNARITY)
     libtcod.noise_set_type(self.noise, libtcod.NOISE_PERLIN)
     libtcod.heightmap_add_fbm(self.hm, self.noise, 1, 1, 1, 1, 8, 0.5, 0.5)
     libtcod.heightmap_normalize(self.hm, 0, 255)
Beispiel #9
0
def create():
	display.create_surface('background')
	display.create_surface('text')
	display.blit_background('background')
	
	roll()
	
	NOISE = tcod.noise_new(2, h=tcod.NOISE_DEFAULT_HURST, random=tcod.random_new())
	
	for y in range(0, constants.WINDOW_HEIGHT):
		for x in range(0, constants.WINDOW_WIDTH):
			_noise_values = [(ZOOM * x / (constants.WINDOW_WIDTH)),
			                 (ZOOM * y / (constants.WINDOW_HEIGHT))]
			_height = 1 - tcod.noise_get_turbulence(NOISE, _noise_values, tcod.NOISE_SIMPLEX)
			_dist_to_crosshair = 30
			_crosshair_mod = abs((_dist_to_crosshair - 1))
			
			if _height > .4:
				_height = (_height - .4) / .4
				_r, _g, _b = numbers.clip(30 * _height, 20, 255), 50 * _height, numbers.clip(30 * _height, 30, 255)
			
			else:
				_r, _g, _b = 20, 0, 30
			
			_r += 30# * _crosshair_mod
			
			if x < SIDEBAR_WIDTH:
				if y < 7:
					_r = numbers.interp(_r, .0, .4)
					_g = numbers.interp(_g, .0, .4)
					_b = numbers.interp(_b, .0, .4)
					
				elif y < 43:
					_r = numbers.interp(_r, .0, .6)
					_g = numbers.interp(_g, .0, .6)
					_b = numbers.interp(_b, .0, .6)
					
				elif y < constants.WINDOW_HEIGHT:
					_r = numbers.interp(_r, 1, .7)
					_g = numbers.interp(_g, 1, .7)
					_b = numbers.interp(_b, 1, .7)

				else:
					_r = (int(round(_r * 1.0)))
					_g = (int(round(_g * .2)))
					_b = (int(round(_b * .2)))
			
			if x > SIDEBAR_WIDTH + 3 and x < constants.WINDOW_WIDTH - 6:
				if y > 18 and y < 36:
					_r = numbers.interp(_r, 255, .1)
					_g = numbers.interp(_g, 255, .1)
					_b = numbers.interp(_b, 255, .1)
			
			if x > SIDEBAR_WIDTH + 3 and x < constants.WINDOW_WIDTH - 6:
				if y > 10 and y < 16:
					_r = numbers.interp(_r, .0, .4)
					_g = numbers.interp(_g, .0, .4)
					_b = numbers.interp(_b, .0, .4)
			
			display._set_char('background', x, y, ' ', (0, 0, 0), (_r, _g, _b))
Beispiel #10
0
def make_map():
    global map, objects
 
    #the list of objects with just the player
    objects = [player]
    player.x = MAP_WIDTH / 2
    player.y = MAP_HEIGHT / 2
 
    myrng = libtcod.random_new(123)
    noise2d = libtcod.noise_new(2,libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY, myrng)
    libtcod.noise_set_type(noise2d, libtcod.NOISE_PERLIN)

    #fill map with "normal" tiles
    map = [[Tile(False, libtcod.light_gray)
        for y in range(MAP_HEIGHT)]
            for x in range(MAP_WIDTH)]

    #add color
    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            value = int((libtcod.noise_get_fbm(noise2d,[x/float(MAP_WIDTH),y/float(MAP_HEIGHT)],32) + 1) * 96 )
            map[x][y] = Tile(False, libtcod.Color(value,value,value))

    r = [libtcod.random_get_int(0, CRATER_MIN_SIZE, (CRATER_MIN_SIZE + (CRATER_MAX_SIZE - CRATER_MIN_SIZE) * (MAX_CRATERS - i)**2/(MAX_CRATERS**2)) ) for i in range(MAX_CRATERS)]
    r.sort(reverse=True)
    for i in range(MAX_CRATERS):
        x = libtcod.random_get_int(0, 0, MAP_WIDTH - 1)
        y = libtcod.random_get_int(0, 0, MAP_HEIGHT - 1)
        # r = libtcod.random_get_int(0, CRATER_MIN_SIZE, (CRATER_MIN_SIZE + (CRATER_MAX_SIZE - CRATER_MIN_SIZE) * (MAX_CRATERS - i)/MAX_CRATERS) )
        make_crater(x, y, r[i])

    spawn_silicon(noise2d)
Beispiel #11
0
def noise_example():
	noise1d = libtcod.noise_new(1)
	for s in range(10):
		x = s / float(5)
		v = libtcod.noise_get(noise1d, [x])
		print(v)	
	libtcod.noise_delete(noise1d)
Beispiel #12
0
	def create(self):
		w=self.width=cfg.OW_WIDTH
		h=self.height=cfg.OW_HEIGHT
		th=cfg.OW_TREE_THRES
		
		self.level=[[OverworldTile(j,i) for i in xrange(h)] for j in xrange(w)]
		self.console=libtcod.console_new(w,h)

		backColor=libtcod.Color(0, 0, 0)
		
		noise2d = libtcod.noise_new(2)
		
		for x in xrange(w):
			for y in xrange(h):
				zoom=0.09
				f = [zoom * x,zoom * y]
				val = libtcod.noise_get(noise2d,f)
				c1=int((((val*-1)+1)/2)*30)
				c2=10+int(((val+1)/2)*20)
				
				if val>th:				
					self.level[x][y].setChar(23)
					self.level[x][y].setColors(libtcod.Color(0, 200, 0),libtcod.Color(0, 0, 0))
					self.level[x][y].setBlocked(True)
				else:
					self.level[x][y].setChar(176)
					self.level[x][y].setColors(libtcod.Color(0, c1, 0),libtcod.Color(0, c2, 0))
		
		
		while len(self.pathable)<400: self.findPathable()
		self.clearUnpathableAreas()
		#self.findPathable() # Now a final scan for the full area
			
		# Place town
		
		town_pos=random.choice(self.pathable)
		town=OverworldTileEntity(town_pos[0],town_pos[1])
		town.setColors(libtcod.Color(0, 100, 150),libtcod.Color(40, 40, 0))
		self.tile_entity.append(town)
		self.town=town
		
		# Place dungeons
		
		for i in xrange(cfg.DUNGEONS):
		
			validLocation=False
			pos=None
			while not validLocation:
				validLocation=True
				pos=random.choice(self.pathable)
				for entity in self.tile_entity:
					if entity.position()==pos:
						validLocation=False
				
			dungeon=OverworldTileEntity(pos[0],pos[1])
			dungeon.setColors(libtcod.Color(200, 0, 0),libtcod.Color(40, 0, 0))
			self.tile_entity.append(dungeon)
			
		self.buildBlockedMap()
Beispiel #13
0
def create():
    global NOISE

    display.create_surface("background")

    NOISE = tcod.noise_new(2, h=tcod.NOISE_DEFAULT_HURST, random=tcod.random_new())

    paint_map(initial=True)
Beispiel #14
0
def noise_2d(width, height):
    noise = libtcod.noise_new(2)
    noise_map = {}
    for x in range(width):
        for y in range(height):
            value = libtcod.noise_get(noise, [x * 0.06, y * 0.06])
            noise_map[(x, y)] = value * 100

    return noise_map
Beispiel #15
0
 def __init__(self, w, h):
     global TROPICS_THRESHOLD, TEMPERATE_THRESHOLD, TAIGA_THRESHOLD
     
     self.w = w
     self.h = h
     
     self.equator = h/2
     TROPICS_THRESHOLD = (self.equator/2)/3
     TEMPERATE_THRESHOLD = self.equator/2
     TAIGA_THRESHOLD = self.equator - self.equator*0.1
     self.tiles = [[ Tile(ix,iy, False, map_tile=True)
         for iy in range(h) ]
             for ix in range(w)]
     x,y = 0,0
     self.traffic = [[0
                      for y in range(h)]
                         for x in range(w)]
     #this holds the *colour* value of the tiles temps.
     self.temperature_map = [[0
                      for y in range(h)]
                         for x in range(w)]
     self.moisture_map = [[0
                      for y in range(h)]
                         for x in range(w)]
     
     self.hm = libtcod.heightmap_new(self.w, self.h)
     self.hm2 = libtcod.heightmap_new(self.w, self.h)
     self.hm3 = libtcod.heightmap_new(self.w, self.h)
     
     self.generate_land(self.hm)
     self.generate_land(self.hm2)
     self.generate_land(self.hm3)
     
     libtcod.noise_set_type(self.noise, libtcod.NOISE_SIMPLEX)
     self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
     #libtcod.heightmap_add_fbm(self.hm3, self.noise, 1, 1, 0, 0, 8, 0.8, 0.5)
     #self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
     #libtcod.heightmap_add_fbm(self.hm3, self.noise, 1, 1, 0, 0, 8, 0.8, 0.5)
     #self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
     #libtcod.heightmap_add_fbm(self.hm3, self.noise, 1, 1, 0, 0, 8, 0.8, 0.5)
     self.multiply_noise()
     self.multiply_noise()
     libtcod.heightmap_normalize(self.hm, 0, 255)
     #libtcod.heightmap_normalize(self.hm2, 0, 255)
     #libtcod.heightmap_normalize(self.hm3, 0, 255)
     #libtcod.heightmap_rain_erosion(self.hm, (self.w + self.h)*4, 0.5, 0.1, None)
     
     self.add_noise()
     self.turn_to_tiles()
     self.determine_temperatures()
     self.normalise_temperatures()
     self.wind_gen = Particle_Map(self,1500)
     self.generate_mini_map(10)
     self.cities = []
     self.dungeons = []
     self.generate_city(libtcod.random_get_int(0, 4, 10))
     self.generate_dungeons(10)
Beispiel #16
0
def create():
    global NOISE

    display.create_surface('background')

    NOISE = tcod.noise_new(2,
                           h=tcod.NOISE_DEFAULT_HURST,
                           random=tcod.random_new())

    paint_map(initial=True)
Beispiel #17
0
 def generate(self, border_size = 1, air_buffer = 10):
     noise_2d = libtcod.noise_new(2)
     self.tiles = [[ Dirt(libtcod.noise_get(noise_2d,[x,y])*3) for y in range(self.height) ] for x in range(self.width) ]
     for x in range(self.width):
         for y in range(self.height):
             if x < border_size or y < border_size or  x > ((self.width - 1) - border_size) or y > ((self.height - 1) - border_size):
                 self.tiles[x][y] = Wall()
             elif y < border_size + air_buffer:
                 self.tiles[x][y] = Air()
     self.update()    
Beispiel #18
0
    def generate_land(self,hm):
        
        print hm.w, hm.h
        #self.noise = perlin_noise.PerlinNoiseGenerator()
        #self.noise.generate_noise(self.w, self.h, 1, 16)
        #print str(self.noise.noise[1][1])
        self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
        libtcod.heightmap_add_fbm(hm, self.noise, 1, 1, 0, 0, 8, 0.5, 0.8)
        print "scale", str(libtcod.heightmap_get_value(hm, 1, 1))
        self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
        libtcod.noise_set_type(self.noise, libtcod.NOISE_PERLIN)
        libtcod.heightmap_scale_fbm(hm, self.noise, 1, 1, 0, 0, 8, 0.5, 0.8)
        
#        self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
#        libtcod.heightmap_add_fbm(hm, self.noise, 1, 1, 0, 0, 8, 0.8, 0.5)
#        
        libtcod.heightmap_normalize(hm, 0, 255)
        print "normalized", str(libtcod.heightmap_get_value(hm, 1, 1))
        
        return hm
Beispiel #19
0
    def make_house():
        bsp_tree = tcod.bsp_new_with_size(0, 0, HOUSE_WIDTH - 1, HOUSE_HEIGHT - 1)
        tcod.bsp_split_recursive(bsp_tree, 0, BSP_DEPTH, MIN_ROOM_WIDTH, MIN_ROOM_HEIGHT,
                                 MAX_H_RATIO, MAX_V_RATIO)

        tcod.bsp_traverse_inverted_level_order(bsp_tree, handle_node)
        house_array[-1][-1] = Tile("wall", True, True)

        noise = tcod.noise_new(2, HURST, LACNULARITY)
        for x in xrange(HOUSE_WIDTH):
            for y in xrange(HOUSE_HEIGHT):
                if tcod.noise_get_turbulence(noise, [x, y], 32.0, tcod.NOISE_SIMPLEX) > THRESHOLD:
                    house_array[y][x] = Tile("floor", True, True)
Beispiel #20
0
    def generate_land(self, hm):

        print hm.w, hm.h
        #self.noise = perlin_noise.PerlinNoiseGenerator()
        #self.noise.generate_noise(self.w, self.h, 1, 16)
        #print str(self.noise.noise[1][1])
        self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST,
                                       libtcod.NOISE_DEFAULT_LACUNARITY)
        libtcod.heightmap_add_fbm(hm, self.noise, 1, 1, 0, 0, 8, 0.5, 0.8)
        print "scale", str(libtcod.heightmap_get_value(hm, 1, 1))
        self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST,
                                       libtcod.NOISE_DEFAULT_LACUNARITY)
        libtcod.noise_set_type(self.noise, libtcod.NOISE_PERLIN)
        libtcod.heightmap_scale_fbm(hm, self.noise, 1, 1, 0, 0, 8, 0.5, 0.8)

        #        self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
        #        libtcod.heightmap_add_fbm(hm, self.noise, 1, 1, 0, 0, 8, 0.8, 0.5)
        #
        libtcod.heightmap_normalize(hm, 0, 255)
        print "normalized", str(libtcod.heightmap_get_value(hm, 1, 1))

        return hm
Beispiel #21
0
    def __init__(self, width, height):
        self.size = width 
        self.width = width
        self.height = height
        self.units = []
        self.selected_unit = None

        self.world_img = libtcod.image_new(self.width, self.height)
        self.ground_map = libtcod.map_new(width, height)
        self.deepsea_map = libtcod.map_new(width, height)
        
        self.noise_zoom = 5.0
        self.noise_octaves = 8.0

        self.center = [self.width/2, self.height/2]

        self.map_list = [[Tile(True, libtcod.black) for y in range(height)] for x in range(width)]

        self.world_noise = libtcod.noise_new(2)
        self.ocean_noise = libtcod.noise_new(2)
        libtcod.noise_set_type(self.world_noise, libtcod.NOISE_PERLIN)
        self.generate_land()
Beispiel #22
0
    def __init__(self, w, h):
        global TROPICS_THRESHOLD, TEMPERATE_THRESHOLD, TAIGA_THRESHOLD

        self.w = w
        self.h = h

        self.equator = h / 2
        TROPICS_THRESHOLD = (self.equator / 2) / 3
        TEMPERATE_THRESHOLD = self.equator / 2
        TAIGA_THRESHOLD = self.equator - self.equator * 0.1
        self.tiles = [[Tile(ix, iy, False, map_tile=True) for iy in range(h)]
                      for ix in range(w)]
        x, y = 0, 0
        self.traffic = [[0 for y in range(h)] for x in range(w)]
        #this holds the *colour* value of the tiles temps.
        self.temperature_map = [[0 for y in range(h)] for x in range(w)]
        self.moisture_map = [[0 for y in range(h)] for x in range(w)]

        self.hm = libtcod.heightmap_new(self.w, self.h)
        self.hm2 = libtcod.heightmap_new(self.w, self.h)
        self.hm3 = libtcod.heightmap_new(self.w, self.h)

        self.generate_land(self.hm)
        self.generate_land(self.hm2)
        self.generate_land(self.hm3)

        libtcod.noise_set_type(self.noise, libtcod.NOISE_SIMPLEX)
        self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST,
                                       libtcod.NOISE_DEFAULT_LACUNARITY)
        #libtcod.heightmap_add_fbm(self.hm3, self.noise, 1, 1, 0, 0, 8, 0.8, 0.5)
        #self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
        #libtcod.heightmap_add_fbm(self.hm3, self.noise, 1, 1, 0, 0, 8, 0.8, 0.5)
        #self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)
        #libtcod.heightmap_add_fbm(self.hm3, self.noise, 1, 1, 0, 0, 8, 0.8, 0.5)
        self.multiply_noise()
        self.multiply_noise()
        libtcod.heightmap_normalize(self.hm, 0, 255)
        #libtcod.heightmap_normalize(self.hm2, 0, 255)
        #libtcod.heightmap_normalize(self.hm3, 0, 255)
        #libtcod.heightmap_rain_erosion(self.hm, (self.w + self.h)*4, 0.5, 0.1, None)

        self.add_noise()
        self.turn_to_tiles()
        self.determine_temperatures()
        self.normalise_temperatures()
        self.wind_gen = Particle_Map(self, 1500)
        self.generate_mini_map(10)
        self.cities = []
        self.dungeons = []
        self.generate_city(libtcod.random_get_int(0, 4, 10))
        self.generate_dungeons(10)
Beispiel #23
0
def render_all():
    global fov_map, color_dark_wall, color_light_wall
    global color_dark_ground, color_light_ground
    global fov_recompute, FOV_TORCH, FOV_TORCHX, FOV_NOISE, noise

    dx = 0.0
    dy = 0.0
    di = 0.0

    if fov_recompute:
        # recompute FOV if needed (the player moved or something)
        fov_recompute = False
        libtcod.map_compute_fov(fov_map, player.x, player.y, TORCH_RADIUS, FOV_LIGHT_WALLS, FOV_ALGO)
    if FOV_TORCH:
        FOV_TORCHX += 0.2
        tdx = [FOV_TORCHX + 20.0]
        dx = libtcod.noise_simplex(noise, tdx) * 1.5
        tdx[0] += 30.0
        dy = libtcod.noise_simplex(noise, tdx) * 1.5
        di = 0.2 * libtcod.noise_simplex(noise, [FOV_TORCHX])
        FOV_NOISE = libtcod.noise_new(1, 1.0, 1.0)

        # go through all tiles, and set their background color according to the FOV
        for y in range(MAP_HEIGHT):
            for x in range(MAP_WIDTH):
                visible = libtcod.map_is_in_fov(fov_map, x, y)
                wall = map[x][y].block_sight
                if not visible:
                    # if it's not visible right now, the player can only see it if it's explored
                    if map[x][y].explored:
                        if wall:
                            libtcod.console_set_back(con, x, y, color_dark_wall, libtcod.BKGND_SET)
                        else:
                            libtcod.console_set_back(con, x, y, color_dark_ground, libtcod.BKGND_SET)
                else:
                    # it's visible
                    if wall:
                        libtcod.console_set_back(con, x, y, color_light_wall, libtcod.BKGND_SET)
                    else:
                        libtcod.console_set_back(con, x, y, color_light_ground, libtcod.BKGND_SET)
                    # since it's visible, explore it
                    map[x][y].explored = True

    # draw all objects in the list
    for object in objects:
        object.draw()

    # blit the contents of "con" to the root console
    libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0)
Beispiel #24
0
def initialize_fov():
    global fov_recompute, fov_map, fov_noise
    fov_recompute = True

    libtcod.console_clear(con)  # Unexplored areas start black (which
                                # is the default background color)

    #create the FOV map, according to the generated map
    fov_noise = libtcod.noise_new(1, 1.0, 1.0)
    fov_map = libtcod.map_new(MAP_WIDTH, MAP_HEIGHT)
    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            libtcod.map_set_properties(fov_map, x, y,
                                       not map[x, y].block_sight,
                                       not map[x, y].blocked)
Beispiel #25
0
def initialze(scale=50, weather=False):
    global noise_field, height_map
    noise_field = libtcod.noise_new(2, 0.5, 2.0, rnd)  # 0.5f  and 2.0f
    libtcod.noise_set_type(noise_field, libtcod.NOISE_SIMPLEX)

    height_map = libtcod.heightmap_new(Constants.MAP_WIDTH, Constants.MAP_HEIGHT)

    for y in range(Constants.MAP_HEIGHT):
        for x in range(Constants.MAP_WIDTH):
            libtcod.heightmap_set_value(height_map, x, y, get_noise_value(x, y, scale=scale))

    libtcod.heightmap_normalize(height_map, 0.0, 1.0)
    # libtcod.heightmap_add_hill(height_map, 40, 40, 6, 0.8)
    if weather:
        libtcod.heightmap_rain_erosion(height_map, 5000, 0.75, .75)
Beispiel #26
0
def initialize_fov():
    global fov_recompute, fov_map, fov_noise
    fov_recompute = True

    libtcod.console_clear(con)  # Unexplored areas start black (which
    # is the default background color)

    #create the FOV map, according to the generated map
    fov_noise = libtcod.noise_new(1, 1.0, 1.0)
    fov_map = libtcod.map_new(MAP_WIDTH, MAP_HEIGHT)
    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            libtcod.map_set_properties(fov_map, x, y,
                                       not map[x, y].block_sight,
                                       not map[x, y].blocked)
Beispiel #27
0
 def _build_background(self):
     """
     Make a background noise that will more or less look like
     an old map.
     """
     noise = tcod.noise_new(2)
     tcod.noise_set_type(noise, tcod.NOISE_SIMPLEX)
     background = []
     for y in range(self.height):
         background.append([])
         for x in range(self.width):
             background[y].append(
                 tcod.noise_get_turbulence(noise, [y / 100.0, x / 100.0],
                                           32.0))
     tcod.noise_delete(noise)
     return background
Beispiel #28
0
def Percipitaion(preciphm, temphm):

    libtcod.heightmap_add(preciphm, 2)

    for x in xrange(WORLD_WIDTH):
        for y in xrange(WORLD_HEIGHT):
            temp = libtcod.heightmap_get_value(temphm, x, y)

    precip = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST,
                               libtcod.NOISE_DEFAULT_LACUNARITY)

    libtcod.heightmap_add_fbm(preciphm, precip, 2, 2, 0, 0, 32, 1, 1)

    libtcod.heightmap_normalize(preciphm, 0.0, 1.0)

    return
Beispiel #29
0
 def _build_background(self):
     """
     Make a background noise that will more or less look like
     an old map.
     """
     noise = tcod.noise_new(2)
     tcod.noise_set_type(noise, tcod.NOISE_SIMPLEX)
     background = []
     for y in range(self.height):
         background.append([])
         for x in range(self.width):
             background[y].append(
                 tcod.noise_get_turbulence(noise,
                                           [y / 100.0, x / 100.0], 32.0))
     tcod.noise_delete(noise)
     return background
Beispiel #30
0
def initialze(scale=50, weather=False):
    global noise_field, height_map
    noise_field = libtcod.noise_new(2, 0.5, 2.0, rnd)  # 0.5f  and 2.0f
    libtcod.noise_set_type(noise_field, libtcod.NOISE_SIMPLEX)

    height_map = libtcod.heightmap_new(Constants.MAP_WIDTH,
                                       Constants.MAP_HEIGHT)

    for y in range(Constants.MAP_HEIGHT):
        for x in range(Constants.MAP_WIDTH):
            libtcod.heightmap_set_value(height_map, x, y,
                                        get_noise_value(x, y, scale=scale))

    libtcod.heightmap_normalize(height_map, 0.0, 1.0)
    # libtcod.heightmap_add_hill(height_map, 40, 40, 6, 0.8)
    if weather:
        libtcod.heightmap_rain_erosion(height_map, 5000, 0.75, .75)
Beispiel #31
0
    def generateDepth(self):
        #noise_octaves = 4.0
        noise_zoom = 2.0
        noise_hurst = libtcod.NOISE_DEFAULT_HURST
        noise_lacunarity = libtcod.NOISE_DEFAULT_LACUNARITY

        mapped = self.mappedArea
        
        water_color = libtcod.sky

        if self.mapType == "desert":
            water_level = 0.04
        else:
            water_level = 0.07

        noise = libtcod.noise_new(2, noise_hurst, noise_lacunarity)
        for y in range(self.height):
                for x in range(self.width):
                    f = [noise_zoom * x / (self.width), noise_zoom * y / (self.height)]
                    noisefloat = abs(libtcod.noise_get(noise, f, libtcod.NOISE_PERLIN))
                    if noisefloat >= float(0) and noisefloat <= water_level:
                        tile = mapped[x][y]
                        tile.tileType = "water"
                        tile.blocked = False
                        tile.block_sight = False
                        tile.slows = True
                        #Depth = Color darkness
                        depth = int(10 - (noisefloat * 100))
                        tile.color = water_color - libtcod.Color(5 * depth, 5 * depth, 5 * depth)
                        tile.height = 0 - depth
                    else:
                        tile = mapped[x][y]
                        height = int(noisefloat / 0.03)
                        if height > 12:
                            height = 12
                        tile.height = height

        #Block the edges of the map so player can't crash the game
        for y in range(self.height):
            #mapped[0][y].tileType = None
            mapped[0][y].blocked = True
            mapped[self.width-1][y].blocked = True
        for x in range(self.width):
            mapped[x][0].blocked = True
            mapped[x][self.height-1].blocked = True
Beispiel #32
0
    def spherical_noise(self,
            noise_dx=0.0,
            noise_dy=0.0,
            noise_dz=0.0,
            noise_octaves=4.0,
            noise_zoom=1.0,
            noise_hurst=libtcod.NOISE_DEFAULT_HURST,
            noise_lacunarity=libtcod.NOISE_DEFAULT_LACUNARITY,
            width=None,
            height=None,
            seed=None):
        self.rnd = libtcod.random_new_from_seed(self.seed) if seed is None else libtcod.random_new_from_seed(seed)

        noise = libtcod.noise_new(3, noise_hurst, noise_lacunarity, self.rnd)
        hm = libtcod.heightmap_new(width, height)

        noise_dx += 0.01
        noise_dy += 0.01
        noise_dz += 0.01

        pi_times_two = 2 * math.pi
        pi_div_two = math.pi / 2.0

        theta = 0.0
        phi = pi_div_two * -1.0
        x = 0
        y = 0

        while phi <= pi_div_two:
            while theta <= pi_times_two:
                f = [
                    noise_zoom * math.cos(phi) * math.cos(theta),
                    noise_zoom * math.cos(phi) * math.sin(theta),
                    noise_zoom * math.sin(phi),
                ]
                value = libtcod.noise_get_fbm(noise, f, noise_octaves, libtcod.NOISE_PERLIN)
                # print((x, y, value))
                libtcod.heightmap_set_value(hm, x, y, value)
                theta += (pi_times_two / width)
                x += 1
            phi += (math.pi / (height-1))
            y += 1
            x = 0
            theta = 0.0
        return hm
Beispiel #33
0
def Percipitaion(preciphm):

    libtcod.heightmap_add(preciphm, 2)

    for x in xrange(WORLD_WIDTH):
        for y in xrange(WORLD_HEIGHT):
                if y > WORLD_HEIGHT/2 - WORLD_HEIGHT/10 and y < WORLD_HEIGHT/2 + WORLD_HEIGHT/10:
                    val = y
                    val = abs(y - WORLD_HEIGHT/2)
                    libtcod.heightmap_set_value(preciphm, x, y, val/4)
                        
    precip = libtcod.noise_new(2,libtcod.NOISE_DEFAULT_HURST, libtcod.NOISE_DEFAULT_LACUNARITY)

    libtcod.heightmap_add_fbm(preciphm,precip ,8, 8, 0, 0, 32, 1, 1)

    libtcod.heightmap_normalize(preciphm, 0.0, 1.0)                       

    return
Beispiel #34
0
def get_cylindrical_projection(stars, width=360, height=180):
    """
    Return a tcod console instance of width and height that renders an equirectangular projection of the given list of stars.
    """
    console = tcod.console_new(width, height)

    for star in stars:
        azimuthal = int((star.azimuthal * width) / (2 * math.pi))
        polar = int((star.polar / math.pi) * height)

        # Color Work
        rgb = temperature_to_rgb(random.uniform(4000, 20000))
        brightness = 1.0 - star.radial * 0.75

        color = tcod.Color(rgb[0], rgb[1], rgb[2])
        (h, s, v) = tcod.color_get_hsv(color)
        tcod.color_set_hsv(color, h, s, brightness)

        tcod.console_put_char_ex(console, azimuthal, polar, star.sprite, color,
                                 tcod.black)

    # Background Texture
    noise3d = tcod.noise_new(3)
    for map_x in range(width):
        for map_y in range(height):
            azimuthal = (map_x / (width * 1.0)) * 2.0 * math.pi
            polar = (map_y / (height * 1.0)) * math.pi
            x = math.sin(polar) * math.cos(azimuthal)
            y = math.sin(polar) * math.sin(azimuthal)
            z = math.cos(polar)
            blue = int(
                tcod.noise_get_turbulence(noise3d, [x, y, z], 32.0) * 16.0 +
                16.0)
            green = int(tcod.noise_get(noise3d, [x, y, z]) * 8.0 + 8.0)
            red = int(tcod.noise_get_fbm(noise3d, [x, y, z], 32.0) * 4.0 + 4.0)
            background = tcod.Color(red, green, blue)

            if map_y == height / 2 or map_x == 0 or map_x == width / 2:
                background = tcod.darkest_yellow

            tcod.console_set_char_background(console, map_x, map_y, background)

    tcod.noise_delete(noise3d)
    return console
Beispiel #35
0
    def generateWater(self):
        #noise_octaves = 4.0
        noise_zoom = 2.0
        noise_hurst = libtcod.NOISE_DEFAULT_HURST
        noise_lacunarity = libtcod.NOISE_DEFAULT_LACUNARITY

        mapped = self.mappedArea
        
        water_color = libtcod.sky
        water_color1 = water_color - libtcod.Color(6, 6, 6)
        water_color2 = water_color1 - libtcod.Color(6, 6, 6)
        water_color3 = water_color2 - libtcod.Color(8, 8, 8)

        noise = libtcod.noise_new(2, noise_hurst, noise_lacunarity)
        for y in range(self.height):
                for x in range(self.width):
                    f = [noise_zoom * x / (self.width), noise_zoom * y / (self.height)]
                    noisefloat = abs(libtcod.noise_get(noise, f, libtcod.NOISE_PERLIN))
                    if noisefloat >= float(0) and noisefloat <= 0.08:
                        tile = mapped[x][y]
                        tile.tileType = "water"
                        tile.blocked = False
                        tile.block_sight = False
                        tile.slows = True
                        #Depth = Color darkness
                        depth = 10 - (noisefloat * 100)
                        if depth <= 5:
                            tile.color = water_color
                        elif 5 < depth <= 7:
                            tile.color = water_color1
                        elif 7 < depth < 9:
                            tile.color = water_color2
                        else:
                            tile.color = water_color3

        #Block the edges of the map so player can't crash the game
        for y in range(self.height):
            #mapped[0][y].tileType = None
            mapped[0][y].blocked = True
            mapped[self.width-1][y].blocked = True
        for x in range(self.width):
            mapped[x][0].blocked = True
            mapped[x][self.height-1].blocked = True
Beispiel #36
0
def map_init_noise(width, height):
    map_gen = []
    noise = libtcodpy.noise_new(2)
    libtcodpy.noise_set_type(noise, libtcodpy.NOISE_SIMPLEX)
    for x in range(0, width):
        aux = []
        for y in range(0, height):
            if libtcodpy.noise_get(noise, [(x + 1) / 3, y / 3]) > 0.6:
                aux.append(
                    Tile(False, True, False, 0,
                         GAME.tiles.image_at((0, 0, 32, 32)),
                         GAME.tiles.image_at((0, 32, 32, 32))))  # WALL
            else:
                aux.append(
                    Tile(True, False, True, 0,
                         GAME.tiles.image_at((32, 0, 32, 32)),
                         GAME.tiles.image_at((32, 32, 32, 32))))  #F LOOR
        map_gen.append(aux)
    map_gen = map_set_borders(map_gen, width - 1, height - 1)  # BORDERS
    return map_gen
Beispiel #37
0
def test_heightmap():
    hmap = libtcodpy.heightmap_new(16, 16)
    repr(hmap)
    noise = libtcodpy.noise_new(2)

    # basic operations
    libtcodpy.heightmap_set_value(hmap, 0, 0, 1)
    libtcodpy.heightmap_add(hmap, 1)
    libtcodpy.heightmap_scale(hmap, 1)
    libtcodpy.heightmap_clear(hmap)
    libtcodpy.heightmap_clamp(hmap, 0, 0)
    libtcodpy.heightmap_copy(hmap, hmap)
    libtcodpy.heightmap_normalize(hmap)
    libtcodpy.heightmap_lerp_hm(hmap, hmap, hmap, 0)
    libtcodpy.heightmap_add_hm(hmap, hmap, hmap)
    libtcodpy.heightmap_multiply_hm(hmap, hmap, hmap)

    # modifying the heightmap
    libtcodpy.heightmap_add_hill(hmap, 0, 0, 4, 1)
    libtcodpy.heightmap_dig_hill(hmap, 0, 0, 4, 1)
    libtcodpy.heightmap_rain_erosion(hmap, 1, 1, 1)
    libtcodpy.heightmap_kernel_transform(hmap, 3, [-1, 1, 0], [0, 0, 0],
                                         [.33, .33, .33], 0, 1)
    libtcodpy.heightmap_add_voronoi(hmap, 10, 3, [1, 3, 5])
    libtcodpy.heightmap_add_fbm(hmap, noise, 1, 1, 1, 1, 4, 1, 1)
    libtcodpy.heightmap_scale_fbm(hmap, noise, 1, 1, 1, 1, 4, 1, 1)
    libtcodpy.heightmap_dig_bezier(hmap, [0, 16, 16, 0], [0, 0, 16, 16], 1, 1,
                                   1, 1)

    # read data
    libtcodpy.heightmap_get_value(hmap, 0, 0)
    libtcodpy.heightmap_get_interpolated_value(hmap, 0, 0)

    libtcodpy.heightmap_get_slope(hmap, 0, 0)
    libtcodpy.heightmap_get_normal(hmap, 0, 0, 0)
    libtcodpy.heightmap_count_cells(hmap, 0, 0)
    libtcodpy.heightmap_has_land_on_border(hmap, 0)
    libtcodpy.heightmap_get_minmax(hmap)

    libtcodpy.noise_delete(noise)
    libtcodpy.heightmap_delete(hmap)
Beispiel #38
0
def make_heightmap(size, seed):

    # Gradient generated by distance to the northeast corner (creates northeast ocean).
    gradient1 = lt.heightmap_new(size, size)
    for col in xrange(size):
        for row in xrange(size):
            distance = ((row - size) ** 2 + col ** 2) ** 0.5
            lt.heightmap_set_value(gradient1, row, col, distance)
    lt.heightmap_clamp(gradient1, mi=0, ma=WORLD_SIZE)
    lt.heightmap_scale(gradient1, 2)
    # Similar gradient, but cube root (creates mountains around edge).
    gradient2 = lt.heightmap_new(size, size)
    for col in xrange(size):
        for row in xrange(size):
            distance = ((row - size) ** 2 + col ** 2) ** 0.33
            lt.heightmap_set_value(gradient2, row, col, distance)
    lt.heightmap_clamp(gradient2, mi=0, ma=WORLD_SIZE / 6)
    lt.heightmap_scale(gradient2, 5)

    # Height map based on Perlin noise.
    heightmap = lt.heightmap_new(size, size)
    random = lt.random_new()
    if seed:
        random = lt.random_new_from_seed(seed)
    perlin = lt.noise_new(2, h=2, l=2, random=random)

    lt.heightmap_add_fbm(heightmap, perlin, mulx=3, muly=3, addx=0, addy=0, octaves=8, delta=50, scale=100)

    # Add in gradients.
    lt.heightmap_add_hm(heightmap, gradient1, heightmap)
    lt.heightmap_add_hm(heightmap, gradient2, heightmap)

    lt.heightmap_normalize(heightmap, mi=-100, ma=105)
    lt.heightmap_clamp(heightmap, mi=-50, ma=100)
    lt.heightmap_normalize(heightmap, mi=-100, ma=100)
    visualize(heightmap)

    return heightmap
Beispiel #39
0
def generate(width, height):
	_weight_map, _tile_map, _solids, _node_grid = mapgen.create_map(width, height)
	
	_c_x, _c_y = width/2, height/2
	_zoom = 1.2
	_noise = tcod.noise_new(3)
	_possible_trees = set()
	
	for y in range(height):
		for x in range(width):
			_c_dist = numbers.float_distance((x, y), (_c_x, _c_y)) / float(max([width, height]))
			_noise_values = [(_zoom * x / (constants.MAP_VIEW_WIDTH)),
					         (_zoom * y / (constants.MAP_VIEW_HEIGHT))]
			_noise_value = numbers.clip(tcod.noise_get_turbulence(_noise, _noise_values, tcod.NOISE_SIMPLEX) - .7, .5-_c_dist, 1)
			
			if _noise_value > .3:
				_tile = tiles.grass(x, y)
				_possible_trees.add((x, y))
				
			elif _noise_value > .2:
				if random.uniform(.2, .3) + (_noise_value-.2) > .3:
					if _c_dist < .35:
						_tile = tiles.grass(x, y)
						_possible_trees.add((x, y))
					else:
						_tile = tiles.grass(x, y)
						_possible_trees.add((x, y))
				else:
					#TODO: Slowly dither in swamp water
					if _c_dist < .35:
						_tile = tiles.swamp_water(x, y)
					else:
						_tile = tiles.swamp_water(x, y)
			
			elif _noise_value >= 0:
				_r_val = random.uniform(0, .2) + (_noise_value)
				
				if _r_val > .2:
					_tile = tiles.swamp_water(x, y)
				else:
					if random.uniform(0, .2) + (_noise_value) > .2:
						_tile = tiles.swamp_water(x, y)
					else:
						_tile = tiles.tall_grass(x, y)
			
			elif _noise_value < 0:
				_tile = tiles.tall_grass(x, y)
				_possible_trees.add((x, y))
			
			else:
				_tile = tiles.swamp(x, y)
				
			_tile_map[y][x] = _tile
			_weight_map[y][x] = _tile['w']
	
	#############
	#Trader camp#
	#############
	
	_s_x, _s_y = ((width/2)-20, (height/2)-20)
	_building_space = set()
	_walls = set()
	
	#Building
	_width, _height = random.choice([(20, 20), (12, 20), (20, 12)])
	_random_dir = random.randint(0, 3)
	
	if _random_dir == 1:
		_door_x = _width / 2
		_door_y = 0
	
	elif _random_dir == 2:
		_door_x = _width / 2
		_door_y = _height
	
	elif _random_dir == 3:
		_door_x = 0
		_door_y = _height / 2
	
	else:
		_door_x = _width
		_door_y = _height / 2
	
	if _width > _height:
		if _random_dir in [1, 3]:
			_mod = .75
		else:
			_mod = .25
		
		_trade_room_x = int(round(_width * _mod))
		_trade_room_y = -1
		_trade_window_x = _trade_room_x
		_trade_window_y = _height / 2
	else:
		if _random_dir == 1:
			_mod = .75
		else:
			_mod = .25
		
		_trade_room_x = -1
		_trade_room_y = int(round(_height * _mod))
		_trade_window_x = _width / 2
		_trade_window_y = _trade_room_y
	
	for y in range(_height+1):
		_y = _s_y+y
		
		for x in range(_width+1):
			_x = _s_x+x
			
			if (x, y) == (_door_x, _door_y):
				_tile = tiles.concrete(_x, _y)
			
			elif x == 0 or y == 0 or x == _width or y == _height:
				_tile = tiles.wooden_fence(_x, _y)
				_solids.add((_x, _y))
				_walls.add((_x, _y))
			
			else:
				if x == _trade_window_x and y == _trade_window_y:
					_tile = tiles.trade_window(_x, _y)
					
				elif x == _trade_room_x or y == _trade_room_y:
					_tile = tiles.wooden_fence(_x, _y)
					_solids.add((_x, _y))
					_walls.add((_x, _y))
				
				else:
					_tile = tiles.wood_floor(_x, _y)
			
			_weight_map[_y][_x] = _tile['w']
			_tile_map[_y][_x] = _tile
			_building_space.add((_x, _y))
	
	#Wall
	_width, _height = _width * 4, _height * 4
	_ground_space = set()
	
	for y in range(_height + 1):
		_y = _s_y + y
		_yy = _y - int(round(_height * .4))
		
		for x in range(_width + 1):
			_x = _s_x + x
			_xx = _x - int(round(_width * .4))
			
			if random.uniform(0, 1) >= .75:
				continue
			
			if x == 0 or y == 0 or x == _width or y == _height:
				_tile = tiles.wooden_fence(_xx, _yy)
			else:
				if (_xx, _yy) in _building_space:
					continue
				
				_ground_space.add((_xx, _yy))
				
				continue
			
			_weight_map[_yy][_xx] = _tile['w']
			_tile_map[_yy][_xx] = _tile
			_solids.add((_xx, _yy))
	
	#Ground: Inside wall - outside building
	_ground_seeds = random.sample(list(_ground_space - _building_space), 50)
	
	for x, y in _ground_seeds:
		_walker_x = x
		_walker_y = y
		_last_dir = -2, -2
		
		for i in range(random.randint(80, 90)):
			_tile = tiles.concrete_striped(_walker_x, _walker_y)
			_weight_map[_walker_y][_walker_x] = _tile['w']
			_tile_map[_walker_y][_walker_x] =_tile
			
			_dir = random.randint(-1, 1), random.randint(-1, 1)
			_n_x = _walker_x + _dir[0]
			_n_y = _walker_y + _dir[1]
			
			while (_n_x, _n_y) in _building_space or (_n_x, _n_y) in _solids or _last_dir == _dir:
				_dir = random.randint(-1, 1), random.randint(-1, 1)
				_n_x = _walker_x + _dir[0]
				_n_y = _walker_y + _dir[1]
			
			_last_dir = _dir[0] * -1, _dir[0] * -1
			_walker_x = _n_x
			_walker_y = _n_y
	
	#Bushes around outside wall
	
	#Campfires

	"""for room in _rooms:
		_build_doors = []

		for plot_x, plot_y in room['plots']:
			_room = _building[(plot_x, plot_y)]
			_build_walls = ['north', 'south', 'east', 'west']

			for n_plot_x, n_plot_y in [(plot_x-1, plot_y), (plot_x+1, plot_y), (plot_x, plot_y-1), (plot_x, plot_y+1)]:
				if ((n_plot_x, n_plot_y) == _room['door_plot']) or (not _build_doors and not (n_plot_x, n_plot_y) in room['plots'] and (n_plot_x, n_plot_y) in _building):
					if n_plot_x - plot_x == -1:
						_build_doors.append('west')

						if 'west' in _build_walls:
							_build_walls.remove('west')

					elif n_plot_x - plot_x == 1:
						_build_doors.append('east')

						if 'east' in _build_walls:
							_build_walls.remove('east')

					if n_plot_y - plot_y == -1:
						_build_doors.append('north')

						if 'north' in _build_walls:
							_build_walls.remove('north')

					elif n_plot_y - plot_y == 1:
						_build_doors.append('south')

						if 'south' in _build_walls:
							_build_walls.remove('south')

				if (n_plot_x, n_plot_y) in _building:
					if n_plot_x - plot_x == -1 and not _building[(n_plot_x, n_plot_y)]['type'] in buildinggen.ROOM_TYPES[room['type']]['avoid_rooms']:
						if 'west' in _build_walls:
							_build_walls.remove('west')

					elif n_plot_x - plot_x == 1 and not _building[(n_plot_x, n_plot_y)]['type'] in buildinggen.ROOM_TYPES[room['type']]['avoid_rooms']:
						if 'east' in _build_walls:
							_build_walls.remove('east')

					if n_plot_y - plot_y == -1 and not _building[(n_plot_x, n_plot_y)]['type'] in buildinggen.ROOM_TYPES[room['type']]['avoid_rooms']:
						if 'north' in _build_walls:
							_build_walls.remove('north')

					elif n_plot_y - plot_y == 1 and not _building[(n_plot_x, n_plot_y)]['type'] in buildinggen.ROOM_TYPES[room['type']]['avoid_rooms']:
						if 'south' in _build_walls:
							_build_walls.remove('south')

			_x, _y = (_s_x + (plot_x*_room_size)), (_s_y + (plot_y*_room_size))

			for y in range(_y, _y+_room_size):
				for x in range(_x, _x+_room_size):
					if ((x-_x == 0 and 'west' in _build_walls) or (y-_y == 0 and 'north' in _build_walls) or (x-_x == _room_size-1 and 'east' in _build_walls) or (y-_y == _room_size-1 and 'south' in _build_walls)):
						_weight_map[y][x] = _tile['w']
						_tile_map[y][x] = tiles.wooden_fence(x, y)
						_solids.add((x, y))

					else:
						_tile_map[y][x] = buildinggen.ROOM_TYPES[room['type']]['tiles'](x, y)
						_building_space.add((x, y))

			for y in range(_y, _y+_room_size):
				for x in range(_x-1, _x+_room_size+1):
					if (x-_x in [-1, 0] and 'west' in _build_doors and (y-_y<=2 or y-_y>=_room_size-3)) or (x-_x in [_room_size, _room_size+1] and 'east' in _build_doors and (y-_y<=2 or y-_y>=_room_size-3)):
						_weight_map[y][x] = _tile['w']
						_tile_map[y][x] = tiles.wooden_fence(x, y)

						_solids.add((x, y))

			for y in range(_y-1, _y+_room_size+1):
				for x in range(_x, _x+_room_size):
					if (y-_y in [-1, 0] and 'north' in _build_doors and (x-_x<=2 or x-_x>=_room_size-3)) or (y-_y in [_room_size, _room_size+1] and 'south' in _build_doors and (x-_x<=2 or x-_x>=_room_size-3)):
						_weight_map[y][x] = _tile['w']
						_tile_map[y][x] = tiles.wooden_fence(x, y)
						_solids.add((x, y))

			_last_plot_x, _last_plot_y = plot_x, plot_y

	#TODO: Make this into a function?
	_min_x, _max_x = (width, 0)
	_min_y, _max_y = (height, 0)

	for x, y in _building:
		_x, _y = (_s_x + (x*_room_size)), (_s_y + (y*_room_size))

		if _x > _max_x:
			_max_x = _x

		if _x < _min_x:
			_min_x = _x

		if _y > _max_y:
			_max_y = _y

		if _y < _min_y:
			_min_y = _y"""

	_plot_pole_x, _plot_pole_y = _s_x, _s_y
	_tree_plots = _possible_trees - _solids
	_tree_plots = list(_tree_plots - _building_space)
	_trees = {}
	_used_trees = random.sample(_tree_plots, numbers.clip(int(round((width * height) * .001)), 0, len(_tree_plots)))
	_bush_plots = set(_tree_plots) - set(_used_trees)
	_used_bush = random.sample(_bush_plots, numbers.clip(int(round((width * height) * .003)), 0, len(_bush_plots)))
	_swamp_plots = set(_tree_plots) - set(_used_bush)
	_used_swamp = random.sample(_swamp_plots, numbers.clip(int(round((width * height) * .003)), 0, len(_swamp_plots)))
	
	for x, y in _used_trees:
		_size = random.randint(7, 12)
		_trees[x, y] = _size
		
		for w in range(random.randint(1, 2)):
			_walker_x = x
			_walker_y = y
			_walker_direction = random.randint(0, 359)
			
			for i in range(random.randint(_size/4, _size/2)):
				_actual_x, _actual_y = int(round(_walker_x)), int(round(_walker_y))
				
				if _actual_x < 0 or _actual_y < 0 or _actual_x >= width or _actual_y >= height or (_actual_x, _actual_y) in _solids:
					break
				
				_center_mod = numbers.float_distance((_actual_x, _actual_y), (x, y)) / float(_size)
				_tile = tiles.tree(_actual_x, _actual_y)
				_weight_map[_actual_y][_actual_x] = _tile['w']
				_tile_map[_actual_y][_actual_x] = _tile
				
				if random.randint(0, 3):
					_trees[_actual_x, _actual_y] = random.randint(1, _size)
				
				_solids.add((_actual_x, _actual_y))
				_walker_direction += random.randint(-45, 45)
				_n_x, _n_y = numbers.velocity(_walker_direction, 1)
				
				_walker_x += _n_x
				_walker_y += _n_y
	
	for x, y in _used_bush:
		_center_mod = numbers.float_distance((x, y), (_plot_pole_x, _plot_pole_y)) / 60.0
		_walker_x = x
		_walker_y = y
		
		for i in range(int(round(random.randint(44, 55) * _center_mod))):
			_tile = tiles.swamp_water(_walker_x, _walker_y)
			_weight_map[_walker_y][_walker_x] = _tile['w']
			_tile_map[_walker_y][_walker_x] =_tile
			
			_walker_x += random.randint(-1, 1)
			_walker_y += random.randint(-1, 1)
			
			if _walker_x < 0 or _walker_y < 0 or _walker_x >= width or _walker_y >= height or (_walker_x, _walker_y) in _solids:
				break
	
	for x, y in _used_swamp:
		_center_mod = numbers.float_distance((x, y), (_plot_pole_x, _plot_pole_y)) / 120.0
		_walker_x = x
		_walker_y = y
		
		for i in range(int(round(random.randint(44, 55) * (1-_center_mod)))):
			_tile = tiles.swamp(_walker_x, _walker_y)
			_weight_map[_walker_y][_walker_x] = _tile['w']
			_tile_map[_walker_y][_walker_x] =_tile
			
			_walker_x += random.randint(-1, 1)
			_walker_y += random.randint(-1, 1)
			
			if _walker_x < 0 or _walker_y < 0 or _walker_x >= width or _walker_y >= height or (_walker_x, _walker_y) in _solids:
				break

	mapgen.build_node_grid(_node_grid, _solids)
	mapgen.add_plot_pole(_plot_pole_x, _plot_pole_y, 40, _solids)
	
	_fsl = {'Terrorists': {'bases': 1, 'squads': 0, 'trader': True, 'type': life.human_runner},
	        'Militia': {'bases': 0, 'squads': 1, 'trader': False, 'type': life.human_bandit}}
	#'Wild Dogs': {'bases': 0, 'squads': 1, 'trader': False, 'type': life.wild_dog}}
	
	return width, height, _node_grid, mapgen.NODE_SETS.copy(), _weight_map, _tile_map, _solids, _fsl, _trees, _building_space - _walls
Beispiel #40
0
    def create(self):
        w = self.width = cfg.OW_WIDTH
        h = self.height = cfg.OW_HEIGHT
        th = cfg.OW_TREE_THRES

        self.level = [[OverworldTile(j, i) for i in xrange(h)]
                      for j in xrange(w)]
        self.console = libtcod.console_new(w, h)

        backColor = libtcod.Color(0, 0, 0)

        noise2d = libtcod.noise_new(2)

        for x in xrange(w):
            for y in xrange(h):
                zoom = 0.09
                f = [zoom * x, zoom * y]
                val = libtcod.noise_get(noise2d, f)
                c1 = int((((val * -1) + 1) / 2) * 30)
                c2 = 10 + int(((val + 1) / 2) * 20)

                if val > th:
                    self.level[x][y].setChar(23)
                    self.level[x][y].setColors(libtcod.Color(0, 200, 0),
                                               libtcod.Color(0, 0, 0))
                    self.level[x][y].setBlocked(True)
                else:
                    self.level[x][y].setChar(176)
                    self.level[x][y].setColors(libtcod.Color(0, c1, 0),
                                               libtcod.Color(0, c2, 0))

        while len(self.pathable) < 400:
            self.findPathable()
        self.clearUnpathableAreas()
        #self.findPathable() # Now a final scan for the full area

        # Place town

        town_pos = random.choice(self.pathable)
        town = OverworldTileEntity(town_pos[0], town_pos[1])
        town.setColors(libtcod.Color(0, 100, 150), libtcod.Color(40, 40, 0))
        self.tile_entity.append(town)
        self.town = town

        # Place dungeons

        for i in xrange(cfg.DUNGEONS):

            validLocation = False
            pos = None
            while not validLocation:
                validLocation = True
                pos = random.choice(self.pathable)
                for entity in self.tile_entity:
                    if entity.position() == pos:
                        validLocation = False

            dungeon = OverworldTileEntity(pos[0], pos[1])
            dungeon.setColors(libtcod.Color(200, 0, 0),
                              libtcod.Color(40, 0, 0))
            self.tile_entity.append(dungeon)

        self.buildBlockedMap()
Beispiel #41
0
def generate(width, height):
	_weight_map, _tile_map, _solids, _node_grid = mapgen.create_map(width, height)
	_zoom = .95
	_noise = tcod.noise_new(3)
	_low_grass = 25
	_fsl = {}
	_building_space = set()
	_walls = set()
	_possible_trees = set()
	_river_start_x = random.randint(int(round(width * .35)), int(round(width * .65)))
	_river_start_y = 0#random.randint(int(round(height * .15)), int(round(height * .85)))
	_x = _river_start_x
	_y = _river_start_y
	_px, _py = _river_start_x, _river_start_y
	_river_direction = 270
	_turn_rate = random.randint(-1, 1)
	_river_tiles = set()
	_river_size = random.randint(7, 10)
	_ground_tiles = set()
	_possible_camps = set()
	
	while 1:
		for i in range(4, 10):
			for __x, __y in shapes.circle(_x, _y, _river_size):
				if __x < 0 or __y < 0 or __x >= width or __y >= height or (__x, __y) in _solids:
					continue
				
				_river_tiles.add((__x, __y))
				_tile = tiles.swamp_water(__x, __y)
				_tile_map[__y][__x] = _tile
				_weight_map[__y][__x] = _tile['w']
			
			_river_direction += _turn_rate
			_xv, _yv = numbers.velocity(_river_direction, 1)
			_px += _xv
			_py += _yv
			_x = int(round(_px))
			_y = int(round(_py))
			
			if _x < 0 or _y < 0 or _x >= width or _y >= height or (_x, _y) in _solids:
				break
		
		if _x < 0 or _y < 0 or _x >= width or _y >= height:
			break
		
		_turn_rate = random.uniform(-2.5, 2.5)
		_river_size = numbers.clip(_river_size + random.randint(-1, 1), 7, 10)
	
	for y in range(height):
		for x in range(width):
			if (x, y) in _river_tiles:
				continue
			
			_tile = tiles.grass(x, y)
			_tile_map[y][x] = _tile
			_weight_map[y][x] = _tile['w']
			
			_ground_tiles.add((x, y))
	
	tcod.noise_set_type(_noise, tcod.NOISE_WAVELET)
	
	for y in range(height):
		for x in range(width):
			if (x, y) in _river_tiles:
				continue
			
			_noise_values = [(_zoom * x / (constants.MAP_VIEW_WIDTH)),
					         (_zoom * y / (constants.MAP_VIEW_HEIGHT))]
			_noise_value = 100 * tcod.noise_get_turbulence(_noise, _noise_values, tcod.NOISE_WAVELET)
			
			if _low_grass <= _noise_value <= 100:
				_tile = tiles.tall_grass(x, y)
				
				if _noise_value >= 40:
					if not x < width * .15 and not x > width * .85 and not y < height * .15 and not y > height * .85:
						_possible_camps.add((x, y))
				
				if random.uniform(0, 1) > .5:
					_possible_trees.add((x, y))
			
			elif _noise_value >= _low_grass - 10 and 10 * random.uniform(0, 1) > _low_grass-_noise_value:
				_tile = tiles.grass(x, y)
			
			else:
				_tile = tiles.rock(x, y)
				_solids.add((x, y))
			
			_tile_map[y][x] = _tile
			_weight_map[y][x] = _tile['w']
	
	_trees = {}
	_tree_plots = _possible_trees - _solids - _river_tiles
	_used_trees = random.sample(_tree_plots, numbers.clip(int(round((width * height) * .002)), 0, len(_tree_plots)))
	
	for x, y in _used_trees:
		_size = random.randint(1, 3)
		
		for _x, _y in shapes.circle(x, y, _size):
			if _x < 0 or _y < 0 or _x >= width or _y >= height or (_x, _y) in _solids:
				break
			
			_tile = tiles.tree(_x, _y)
			_weight_map[_y][_x] = _tile['w']
			_tile_map[_y][_x] = _tile
			_trees[_x, _y] = random.uniform(2, 3.5) * _size
			
			_solids.add((_x, _y))
	
	_ground_tiles = _ground_tiles - _solids
	_plot_pole_x, _plot_pole_y = width/2, height/2
	_bushes = random.sample(_ground_tiles, numbers.clip(int(round((width * height) * .0003)), 0, len(_ground_tiles)))
	_camps = set()
	
	while len(_possible_camps):
		_camp_1 = random.choice(list(_possible_camps))
		_possible_camps.remove(_camp_1)
		_camps.add(_camp_1)
		
		for camp_2 in _possible_camps.copy():
			_dist = numbers.distance(_camp_1, camp_2)
			
			if _dist <= 250:
				_possible_camps.remove(camp_2)
	
	for x, y in _bushes:
		_walker_x = x
		_walker_y = y
		_last_dir = -2, -2
		
		for i in range(random.randint(10, 15)):
			_tile = tiles.tree(_walker_x, _walker_y)
			_weight_map[_walker_y][_walker_x] = _tile['w']
			_tile_map[_walker_y][_walker_x] =_tile
			
			_dir = random.randint(-1, 1), random.randint(-1, 1)
			_n_x = _walker_x + _dir[0]
			_n_y = _walker_y + _dir[1]

			if _n_x < 0 or _n_y < 0 or _n_x >= width or _n_y >= height or (_n_x, _n_y) in _solids:
				break
			
			_last_dir = _dir[0] * -1, _dir[0] * -1
			_walker_x = _n_x
			_walker_y = _n_y
	
	_camp_info = {}
	
	for c_x, c_y in _camps:
		_building_walls = random.sample(['north', 'south', 'east', 'west'], random.randint(2, 3))
		_broken_walls = random.sample(_building_walls, numbers.clip(random.randint(0, 3), 0, len(_building_walls)))
		_camp = {'center': (c_x, c_y)}
		_camp_ground = []
		
		for y in range(-10, 10+1):
			for x in range(-10, 10+1):
				_x = x + c_x
				_y = y + c_y
				
				if (_x, _y) in _solids or (_x, _y) in _river_tiles:
					continue
				
				if (x == -10 and 'west' in _building_walls) or (y == -10 and 'north' in _building_walls) or (x == 10 and 'east' in _building_walls) or (y == 10 and 'south' in _building_walls):
					if x == -10 and 'west' in _building_walls and 'west' in _broken_walls and random.uniform(0, 1) > .75:
						continue
					
					if x == 10 and 'east' in _building_walls and 'east' in _broken_walls and random.uniform(0, 1) > .75:
						continue
					
					if y == -10 and 'north' in _building_walls and 'north' in _broken_walls and random.uniform(0, 1) > .75:
						continue
					
					if y == 10 and 'south' in _building_walls and 'south' in _broken_walls and random.uniform(0, 1) > .75:
						continue
					
					_tile = tiles.wooden_fence(_x, _y)
					_weight_map[_y][_x] = _tile['w']
					_tile_map[_y][_x] = _tile
					_solids.add((_x, _y))
				
				elif (x > -10 and x <= 10) and (y > -10 and y <= 10):
					_camp_ground.append((_x, _y))
		
		_camp['ground'] = _camp_ground[:]
		_camp_info[c_x, c_y] = _camp
	
	mapgen.build_node_grid(_node_grid, _solids)
	
	for c_x, c_y in _camps:
		mapgen.add_plot_pole(c_x, c_y, 40, _solids)
	
	_fsl = {'Terrorists': {'bases': 1, 'squads': 0, 'trader': False, 'type': life.human_runner}}
	#        #'Militia': {'bases': 0, 'squads': 1, 'trader': False, 'type': life.human_bandit},
	#        'Wild Dogs': {'bases': 0, 'squads': 1, 'trader': False, 'type': life.wild_dog}}
	
	return width, height, _node_grid, mapgen.NODE_SETS.copy(), _weight_map, _tile_map, _solids, _fsl, _trees, _building_space - _walls
Beispiel #42
0
def area_cell_create(width, height, p_blocked, p_unblocked, nudge, steps, border=True, exits=0, connect=True, seed=lt.random_get_instance()):
    """
    :param width:
    :param height:
    :param p_blocked: - At least what percent of a valid area must be unblocked spaces.
    :param p_unblocked: - At least what percent of a valid area must be blocked spaces.
    :param nudge: - Higher number means more blocked space.
    :param steps: - How many steps to run the automata.
    :param border: - Requires a solid border?
    :param exits: - If there's a solid border, how many exits should there be?
    :return:
    """
    print "---"
    area = [[True for row in xrange(width)] for col in xrange(height)]
    # Create noise
    print "Generating noise..."
    area_noise = lt.noise_new(2, random=seed)
    for col in xrange(height):
        for row in xrange(width):
            if border:
                if row < 3 or row > width - 3:
                    area[col][row] = 1
                elif col < 3 or col > height - 3:
                    area[col][row] = 1
                else:
                    coords = (col, row)
                    n = lt.noise_get(area_noise, coords)
                    area[col][row] = int(round(abs(n) + nudge, 0))
            else:
                coords = (col, row)
                n = lt.noise_get(area_noise, coords)
                area[col][row] = int(round(abs(n) + nudge, 0))
    visualize(area)

    # Add in exits.
    print "Adding exits..."
    if exits > 0:
        exitcoords = []
        for direction in xrange(exits):
            row_size = random.randint(4, 10)
            col_size = random.randint(4, 10)
            if direction == 0:
                row_loc = random.randint(width/2 - width/4, width/2 + width/4)
                col_loc = height - col_size
                for col in xrange(col_size):
                    for row in xrange(row_size):
                        area[col_loc+col][row_loc+row] = 0
                for row in xrange(row_size):
                    coords = (height - 2, row_loc + row)
                    area[coords[0] + 1][coords[1]] = -1
                    exitcoords.append(coords)


    visualize(area)

    # Begin cellular automata
    print "Running automata..."
    for i in xrange(steps):
        next_step = area
        for col in xrange(height):
            for row in xrange(width):
                neighbors = count_neighbors(col, row, area)

                # Check births and survivals.
                # Current rules are: B5678 / S45678. May want to add the ability to affect that too.
                if area[col][row] == 1 and neighbors < 4:
                    next_step[col][row] = 0
                elif area[col][row] == 0 and neighbors > 4:
                    next_step[col][row] = 1
        area = next_step
        visualize(area)

    # Mark as ground only those ground tiles which can be reached from an arbitrary point near the center OR an exit.
    print "Counting reach..."
    while True:
        if exits == 0:
            row = random.randint(width/2 - 10, width/2 + 10)
            col = random.randint(height/2 - 10, height/2 + 10)
        elif exits > 0:
             col, row = exitcoords.pop()
        if area[col][row] == 0:
            reachable(col, row, area, 1)
            break
    # Replace 0's (unreachable sections) with 1 (blocked). and 2's (reachable sections)
    # with 0 (unblocked), while counting how many there are.
    unblocked_n = 0.
    blocked_n = 0.
    for col in xrange(height):
        for row in xrange(width):
            if area[col][row] == 1 or (area[col][row] == 0 and connect):
                area[col][row] = 1
                blocked_n += 1
            elif area[col][row] > 1 or (area[col][row] == 0 and not connect):
                if col == 0 or col == height - 1 or row == 0 or row == width - 1:
                    area[col][row] = -1
                unblocked_n += 1

    # Ensure the map fits our parameters.
    print "Testing parameters..."
    visualize(area)
    if unblocked_n <= width * height * p_unblocked:
        print "Not enough unblocked: ", unblocked_n, "<", width * height * p_unblocked
        if blocked_n <= width * height * p_blocked:
            print "Not enough blocked.", blocked_n, "<", width * height * p_blocked
        return False
    print "Area generated."
    return area
Beispiel #43
0
 def multiply_noise(self):
     self.noise = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST,
                                    libtcod.NOISE_DEFAULT_LACUNARITY)
     libtcod.noise_set_type(self.noise, libtcod.NOISE_PERLIN)
     libtcod.heightmap_scale_fbm(self.hm, self.noise, 1, 1, 1, 1, 16, 0.5,
                                 0.5)
Beispiel #44
0
def generate(width, height):
    _weight_map, _tile_map, _solids, _node_grid = mapgen.create_map(
        width, height)
    _zoom = .95
    _noise = tcod.noise_new(3)
    _low_grass = 25
    _fsl = {}
    _building_space = set()
    _walls = set()
    _possible_trees = set()
    _river_direction = 270
    _turn_rate = random.randint(-1, 1)
    _river_tiles = set()
    _river_size = random.randint(7, 10)
    _ground_tiles = set()
    _possible_camps = set()
    _trees = {}
    _blueprint = sculpted.create_blueprint(sculpted.ROOMS)
    _room_size = 17
    _door_width = 1
    _place_x, _place_y = 5, 10
    _floor = set()
    _lights = []
    _spawns = {'defending': set(), 'attacking': set()}
    #_room_bitmask_maps = {}

    _min_door_pos = (_room_size / 2) - _door_width
    _max_door_pos = (_room_size / 2) + _door_width

    for y in range(_blueprint['height']):
        for x in range(_blueprint['width']):
            _o_bitmask = _blueprint['bitmask_map'][y, x]
            _bitmask = _blueprint['bitmask_map'][y, x]
            _door_bitmask = _blueprint['bitmask_door_map'][y, x]

            if not _bitmask:
                continue

            if _bitmask < 100:
                _bitmask += 100

            else:
                _room_name = _blueprint['room_lookup'][_blueprint['room_map'][
                    y, x]]
                _wall_offset = 0  #Don't even think about touching this...
                _wall_padding = range(
                    _blueprint['rooms'][_room_name]['wall_padding'] + 1)
                _wall_padding_actual = range(
                    _wall_offset,
                    _blueprint['rooms'][_room_name]['wall_padding'] + 1)
                _wall_padding_2_actual = [(_room_size - 1) - i for i in range(
                    _wall_offset,
                    _blueprint['rooms'][_room_name]['wall_padding'] + 1)]
                _wall_padding_2 = [(_room_size - 1) - i for i in range(
                    _blueprint['rooms'][_room_name]['wall_padding'] + 1)]
                _wall_padding_3 = range(
                    _blueprint['rooms'][_room_name]['doorway_padding'] + 1)
                _wall_padding_3_actual = range(
                    _wall_offset,
                    _blueprint['rooms'][_room_name]['doorway_padding'] + 1)
                _wall_padding_4 = [(_room_size - 1) - i for i in range(
                    _blueprint['rooms'][_room_name]['doorway_padding'] + 1)]
                _wall_padding_4_actual = [(_room_size - 1) - i for i in range(
                    _wall_offset,
                    _blueprint['rooms'][_room_name]['doorway_padding'] + 1)]
                _wall_bitmask = 0

                logging.debug('Building: %s' % _room_name)

                if _o_bitmask > 100 and _o_bitmask < 200:
                    _wall_bitmask = _o_bitmask

            for y1 in range(_room_size):
                for x1 in range(_room_size):
                    _placed = False
                    _p_x, _p_y = (x * _room_size) + x1, (y * _room_size) + y1

                    if _o_bitmask > 100 and _o_bitmask < 200:
                        if y1 in _wall_padding and not _bitmask in [
                                101, 103, 105, 107, 109, 111, 113, 115
                        ]:
                            if y1 in _wall_padding_actual:
                                _solids.add((_place_x + _p_x, _place_y + _p_y))

                            _placed = True

                        elif y1 in _wall_padding_2 and not _bitmask in [
                                104, 105, 106, 107, 112, 113, 114, 115
                        ]:
                            if y1 in _wall_padding_2_actual:
                                _solids.add((_place_x + _p_x, _place_y + _p_y))

                            _placed = True

                        if x1 in _wall_padding_2 and not _bitmask in [
                                102, 103, 106, 107, 110, 111, 114, 115
                        ]:
                            if x1 in _wall_padding_2_actual:
                                _solids.add((_place_x + _p_x, _place_y + _p_y))

                            _placed = True

                        elif x1 in _wall_padding and not _bitmask in [
                                108, 109, 110, 111, 112, 113, 114, 115
                        ]:
                            if x1 in _wall_padding_actual:
                                _solids.add((_place_x + _p_x, _place_y + _p_y))

                            _placed = True

                    else:
                        if y1 == 0 and _bitmask in [
                                101, 103, 105, 107, 109, 111, 113, 115
                        ]:
                            _solids.add((_place_x + _p_x, _place_y + _p_y))
                            _placed = True

                        elif y1 == _room_size - 1 and _bitmask in [
                                104, 105, 106, 107, 112, 113, 114, 115
                        ]:
                            _solids.add((_place_x + _p_x, _place_y + _p_y))
                            _placed = True

                        if x1 == _room_size - 1 and _bitmask in [
                                102, 103, 106, 107, 110, 111, 114, 115
                        ]:
                            _solids.add((_place_x + _p_x, _place_y + _p_y))
                            _placed = True

                        elif x1 == 0 and _bitmask in [
                                108, 109, 110, 111, 112, 113, 114, 115
                        ]:
                            _solids.add((_place_x + _p_x, _place_y + _p_y))
                            _placed = True

                    if not _placed and _o_bitmask > 100 and not _door_bitmask:
                        _floor.add(
                            (_place_x + _p_x, _place_y + _p_y, _room_name))

                    elif _door_bitmask:
                        _doorway_placed = False

                        if y1 in _wall_padding_3 and _door_bitmask in [
                                101, 103, 105, 107, 109, 111, 113, 115
                        ]:
                            if x1 < _min_door_pos or x1 > _max_door_pos:
                                #if x1 in _wall_padding_3_actual:
                                _solids.add((_place_x + _p_x, _place_y + _p_y))
                                _doorway_placed = True

                            elif (_place_x + _p_x, _place_y + _p_y) in _solids:
                                _solids.remove(
                                    (_place_x + _p_x, _place_y + _p_y))

                        elif y1 in _wall_padding_4 and _door_bitmask in [
                                104, 105, 106, 107, 112, 113, 114, 115
                        ]:
                            if x1 < _min_door_pos or x1 > _max_door_pos:
                                _solids.add((_place_x + _p_x, _place_y + _p_y))
                                _doorway_placed = True

                            elif (_place_x + _p_x, _place_y + _p_y) in _solids:
                                _solids.remove(
                                    (_place_x + _p_x, _place_y + _p_y))

                        if x1 in _wall_padding_4 and _door_bitmask in [
                                102, 103, 106, 107, 110, 111, 114, 115
                        ]:
                            if y1 < _min_door_pos or y1 > _max_door_pos:
                                _solids.add((_place_x + _p_x, _place_y + _p_y))
                                _doorway_placed = True

                            elif (_place_x + _p_x, _place_y + _p_y) in _solids:
                                _solids.remove(
                                    (_place_x + _p_x, _place_y + _p_y))

                        elif x1 in _wall_padding_3 and _door_bitmask in [
                                108, 109, 110, 111, 112, 113, 114, 115
                        ]:
                            if y1 < _min_door_pos or y1 > _max_door_pos:
                                _solids.add((_place_x + _p_x, _place_y + _p_y))
                                _doorway_placed = True

                            elif (_place_x + _p_x, _place_y + _p_y) in _solids:
                                _solids.remove(
                                    (_place_x + _p_x, _place_y + _p_y))

                        if not _doorway_placed and not _placed:
                            _floor.add(
                                (_place_x + _p_x, _place_y + _p_y, _room_name))

    _lookup = {(0, -1): 1, (1, 0): 2, (0, 1): 4, (-1, 0): 8}

    _new_floors, _new_solids, _windows, _new_lights, _new_spawns = roomgen.spawn_items(
        _blueprint['rooms'], _blueprint['bitmask_map'],
        _blueprint['bitmask_door_map'], _floor, _solids, _room_size,
        _room_size, (_place_x, _place_y), _tile_map, _weight_map)
    _floor_new = set()

    for x, y, room_name in _floor.copy():
        _floor_new.add((x, y))

    _spawns['defending'].update(_new_spawns)
    _spawns['attacking'].add((70, 5))
    _floor = _floor_new
    _floor.update(_new_floors)
    _solids.update(_new_solids)
    _remove_solids = set()
    _solids = _solids - _windows
    _lights.extend(_new_lights)

    for x, y in _solids:
        #_count = 0
        _delete = True

        for x1, y1 in [(0, -1), (1, 0), (0, 1), (-1, 0), (-1, -1), (1, -1),
                       (-1, 1), (1, 1)]:
            _x = x + x1
            _y = y + y1

            if (_x, _y) in _floor:
                _delete = False
                #_count += 1

        if _delete:
            _remove_solids.add((x, y))
            _ground_tiles.add((x, y))

    _solids = _solids - _remove_solids

    for x in range(width):
        for y in range(height):
            if (x, y) in _solids:
                continue

            _ground_tiles.add((x, y))

    #This generates the outside walls
    for pos in _solids:
        _tile = tiles.wooden_fence(pos[0], pos[1])
        _tile_map[pos[1]][pos[0]] = _tile
        _weight_map[pos[1]][pos[0]] = _tile['w']

    _ground_tiles = _ground_tiles - _windows

    for x, y in _ground_tiles - _floor:
        _tile = tiles.grass(x, y)
        _tile_map[y][x] = _tile
        _weight_map[y][x] = _tile['w']

    mapgen.build_node_grid(_node_grid, _solids)
    _floor.update(_windows)

    return width, height, _node_grid, mapgen.NODE_SETS.copy(
    ), _weight_map, _tile_map, _solids, {}, _trees, _floor, _lights, _spawns
Beispiel #45
0
import libtcodpy as libtcod
import math
import textwrap
import game_settings as opt
import shelve



color_noise = libtcod.noise_new(2)

color_dark_wall = libtcod.Color(31, 31, 39)
bgcolor_dark_wall = libtcod.Color(31, 31, 39)
color_light_wall = libtcod.Color(80,80,77)
bgcolor_light_wall = libtcod.Color(50,50,48)
color_dark_ground = libtcod.Color(3, 3, 5)
bgcolor_dark_ground = libtcod.Color(20, 20, 26)
color_light_ground = libtcod.Color(80,80,77)
bgcolor_light_ground = libtcod.Color(32,32,29)

# TODO
# Generalize map code.
# Starting with Tile, I added four new options. default_fg, default_bg, default_char, and tile_name
# I will probably set something up so instead of setting tiles to blocked to determine if they're a wall,
# I'll instead just set the tile's tile_name to 'wall'
# When rendering, Instead of checking if it's blocked, I will just check for 'wall' or 'floor'
class Tile:
    # def __init__(self, blocked, block_sight = None):
    #     self.blocked = blocked
    #     self.explored = False
    def __init__(self, blocked, block_sight = None,
                 # light_fg=libtcod.red,
Beispiel #46
0
        self.x = x
        self.y = y
        self.con = libtcod.console_new(self.width,self.height)

SCREEN_WIDTH = 80
SCREEN_HEIGHT = 45

GAME_WIDTH = 55
GAME_HEIGHT = 30

MSG_WIDTH = GAME_WIDTH
MSG_HEIGHT = SCREEN_HEIGHT - GAME_HEIGHT - 1

LIMIT_FPS = 40

noise1d = libtcod.noise_new(1)

font = os.path.join('data', 'fonts', 'dejavu12x12_gs_tc.png')
libtcod.console_set_custom_font(font, libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

torchconst = 0.0

libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'Rogue Operative', False)
libtcod.sys_set_fps(LIMIT_FPS)
libtcod.sys_set_renderer(libtcod.RENDERER_SDL) # stick with SDL for now until other renderers are more stable

viewport = console(GAME_WIDTH,GAME_HEIGHT,0,0)
libtcod.console_set_default_foreground(viewport.con, libtcod.white)

message = console(MSG_WIDTH, MSG_HEIGHT,0,GAME_HEIGHT+1)
libtcod.console_set_default_foreground(message.con, libtcod.white)
################################################################################
# Map
################################################################################
MAP_WIDTH = 500
MAP_HEIGHT = 500

ROOM_MAX_SIZE = 20
ROOM_MIN_SIZE = 10
MAX_ROOMS = 450

MAX_ROOM_MONSTERS = 3
MAX_ROOM_ITEMS = 3

# Noise for generating terrain
height_map = libtcod.noise_new(2)

color_dark_wall = libtcod.Color(0, 0, 100)
color_light_wall = libtcod.Color(130, 110, 50)
color_dark_ground = libtcod.Color(50, 50, 150)
color_light_ground = libtcod.Color(200, 180, 50)

class Tile:
    #a tile of the map and its properties
    def __init__(self, blocked, data, block_sight = None, tile_type=None):
        self.blocked = blocked
        self.tile_type = tile_type
        self.data = data
 
        #by default, if a tile is blocked, it also blocks sight
        if block_sight is None: block_sight = blocked
Beispiel #48
0
def create_map():
	_grid = world_strategy.MAP['grid']
	_color_map = world_strategy.MAP['color_map']
	_ownable_plots = set()
	_banned_plots = set()
	
	#Mountains
	_noise = tcod.noise_new(3)
	_zoom = 1.25
	_c_pos = constants.STRAT_MAP_WIDTH/2, constants.STRAT_MAP_HEIGHT/2
	_solids = set()
	
	for y in range(0, constants.STRAT_MAP_HEIGHT):
		for x in range(0, constants.STRAT_MAP_WIDTH):
			_m_x = x / constants.MAP_CELL_SPACE
			_m_y = y / constants.MAP_CELL_SPACE
			
			_m_x = numbers.clip(_m_x, 1, (constants.STRAT_MAP_WIDTH/constants.MAP_CELL_SPACE) - 2)
			_m_y = numbers.clip(_m_y, 1, (constants.STRAT_MAP_HEIGHT/constants.MAP_CELL_SPACE) - 2)
			_c_mod = numbers.float_distance(_c_pos, (x, y))/max([constants.STRAT_MAP_WIDTH/2, constants.STRAT_MAP_HEIGHT/2])
			_noise_values = [(_zoom * x / (constants.STRAT_MAP_WIDTH)),
					         (_zoom * y / (constants.STRAT_MAP_HEIGHT))]
			_height = tcod.noise_get_turbulence(_noise, _noise_values, tcod.NOISE_SIMPLEX) * _c_mod
			_char = ' '
			
			#Mountain
			if _height > .55:
				_color_map[x, y] = random.choice([constants.DARKER_GRAY_1,
				                                  constants.DARKER_GRAY_2,
				                                  constants.DARKER_GRAY_3])
				
				_grid[_m_x, _m_y]['is_ownable'] = False
				_banned_plots.add((_m_x, _m_y))
				
				_c_1 = int(round(_color_map[x, y][0] * (1.8 * _height)))
				_c_2 = int(round(_color_map[x, y][1] * (1.8 * _height)))
				_c_3 = int(round(_color_map[x, y][2] * (1.8 * _height)))
			
			else:
				_color_map[x, y] = random.choice([constants.FOREST_GREEN_1,
				                                  constants.FOREST_GREEN_2,
				                                  constants.FOREST_GREEN_3])
				
				_ownable_plots.add((_m_x, _m_y))

				if _height <= .2:
					_char = random.choice([',', '.', '\'', ' ' * (1 + (20 * int(round(_height))))])
				
				_height -= .1

				_c_1 = int(round(_color_map[x, y][0] * (.7 + _height * 2.8)))
				_c_2 = int(round(_color_map[x, y][1] * (1.0 + _height * .9)))
				_c_3 = int(round(_color_map[x, y][2] * (.75 + _height * 1.2)))
			
			display._set_char('map', x, y, _char, (int(round(_c_1 * .8)), int(round(_c_2 * .8)), int(round(_c_3 * .8))), (_c_1, _c_2, _c_3))
	
	_solids = [(x, y) for x, y in list(_banned_plots)]
	
	world_strategy.MAP['astar_map'] = pathfinding.setup(constants.STRAT_MAP_WIDTH/constants.MAP_CELL_SPACE,
	                                                    constants.STRAT_MAP_HEIGHT/constants.MAP_CELL_SPACE,
	                                                    _solids)
	
	return list(_ownable_plots - _banned_plots)
Beispiel #49
0
MAP_WIDTH = 80
MAP_HEIGHT = 45

# parameters for dungeon generator
ROOM_MAX_SIZE = 10
ROOM_MIN_SIZE = 6
MAX_ROOMS = 30


FOV_ALGO = 0  # default FOV algorithm
FOV_LIGHT_WALLS = True  # light walls or not
FOV_TORCH = True  # Set torch FX
FOV_TORCHX = 0.0
FOV_NOISE = None
TORCH_RADIUS = 10
noise = libtcod.noise_new(2)

LIMIT_FPS = 20  # 20 frames-per-second maximum

color_dark_ground = libtcod.Color(53, 53, 53)
color_dark_wall = libtcod.Color(25, 25, 25)
color_light_wall = libtcod.Color(153, 153, 102)
color_light_ground = libtcod.Color(102, 102, 102)


class Tile:
    # a tile of the map and its properties
    def __init__(self, blocked, block_sight=None):
        self.blocked = blocked

        # all tiles start unexplored
Beispiel #50
0
def activate(zone_id):
    global ACTIVE_ZONE

    ACTIVE_ZONE = zone_id

    _zone = ZONES[zone_id]
    _noise = tcod.noise_new(2)

    logging.info('Bringing zone \'%s\' online...' % _zone['name'])

    _zone['astar_map'] = pathfinding.setup(_zone['width'], _zone['height'],
                                           _zone['solids'])
    _zone['los_map'] = mapgen.generate_los_map(_zone['width'], _zone['height'],
                                               _zone['solids'])

    display.create_surface('tiles',
                           width=_zone['width'],
                           height=_zone['height'])

    maps.render_map(_zone['tile_map'], _zone['width'], _zone['height'])

    post_processing.start()

    events.register_event('logic', post_processing.tick_sun)

    _static_lighting = display.create_shader(_zone['width'],
                                             _zone['height'],
                                             start_offset=1)
    _zone['shaders'].append(
        post_processing.generate_shadow_map(_zone['width'], _zone['height'],
                                            _zone['solids'], _zone['trees'],
                                            _zone['inside']))
    _zone['shaders'].append(
        post_processing.generate_light_map(_zone['width'], _zone['height'],
                                           _zone['solids'], _zone['trees']))
    _zone['light_maps']['static_lighting'] = _static_lighting
    _zone['shaders'].append(_static_lighting)

    _noise = tcod.noise_new(3)
    _zoom = 2.0
    _zone['fader'] = display.create_shader(_zone['width'], _zone['height'])
    _shader = display.create_shader(_zone['width'], _zone['height'])

    for y in range(0, _zone['height']):
        for x in range(0, _zone['width']):
            if (x, y) in _zone['inside']:
                _height = .75
            else:
                _noise_values = [(_zoom * x / _zone['width']),
                                 (_zoom * y / _zone['height'])]
                _height = .35 + numbers.clip(
                    tcod.noise_get_turbulence(_noise, _noise_values,
                                              tcod.NOISE_SIMPLEX), .35, 1)

            _shader[0][y, x] = 1.3 * _height
            _shader[1][y, x] = 1.3 * _height
            _shader[2][y, x] = 1.1 * _height

    _zone['shaders'].append(_shader)

    for light in _zone['lights']:
        effects.light(light[0],
                      light[1],
                      light[2],
                      r=light[3],
                      g=light[4],
                      b=light[5],
                      light_map='static_lighting')

    #if not '--no-fx' in sys.argv:
    #	post_processing.run(time=8,
    #		                repeat=-1,
    #		                repeat_callback=lambda _: post_processing.post_process_clouds(constants.MAP_VIEW_WIDTH,
    #		                                                                              constants.MAP_VIEW_HEIGHT,
    #		                                                                              8,
    #		                                                                              _noise,
    #		                                                                              _zone['inside']))
    post_processing.run(
        time=0,
        repeat=-1,
        repeat_callback=lambda _: post_processing.post_process_lights())
    #post_processing.run(time=0,
    #                    repeat=-1,
    #                    repeat_callback=lambda _: post_processing.sunlight())

    camera.set_limits(0, 0, _zone['width'] - constants.MAP_VIEW_WIDTH,
                      _zone['height'] - constants.MAP_VIEW_HEIGHT)

    logging.info('Zone \'%s\' is online' % _zone['name'])
Beispiel #51
0
def create():
    display.create_surface('background')
    display.create_surface('text')
    display.blit_background('background')

    roll()

    NOISE = tcod.noise_new(2,
                           h=tcod.NOISE_DEFAULT_HURST,
                           random=tcod.random_new())

    for y in range(0, constants.WINDOW_HEIGHT):
        for x in range(0, constants.WINDOW_WIDTH):
            _noise_values = [(ZOOM * x / (constants.WINDOW_WIDTH)),
                             (ZOOM * y / (constants.WINDOW_HEIGHT))]
            _height = 1 - tcod.noise_get_turbulence(NOISE, _noise_values,
                                                    tcod.NOISE_SIMPLEX)
            _dist_to_crosshair = 30
            _crosshair_mod = abs((_dist_to_crosshair - 1))

            if _height > .4:
                _height = (_height - .4) / .4
                _r, _g, _b = numbers.clip(30 * _height, 20,
                                          255), 50 * _height, numbers.clip(
                                              30 * _height, 30, 255)

            else:
                _r, _g, _b = 20, 0, 30

            _r += 30  # * _crosshair_mod

            if x < SIDEBAR_WIDTH:
                if y < 7:
                    _r = numbers.interp(_r, .0, .4)
                    _g = numbers.interp(_g, .0, .4)
                    _b = numbers.interp(_b, .0, .4)

                elif y < 43:
                    _r = numbers.interp(_r, .0, .6)
                    _g = numbers.interp(_g, .0, .6)
                    _b = numbers.interp(_b, .0, .6)

                elif y < constants.WINDOW_HEIGHT:
                    _r = numbers.interp(_r, 1, .7)
                    _g = numbers.interp(_g, 1, .7)
                    _b = numbers.interp(_b, 1, .7)

                else:
                    _r = (int(round(_r * 1.0)))
                    _g = (int(round(_g * .2)))
                    _b = (int(round(_b * .2)))

            if x > SIDEBAR_WIDTH + 3 and x < constants.WINDOW_WIDTH - 6:
                if y > 18 and y < 36:
                    _r = numbers.interp(_r, 255, .1)
                    _g = numbers.interp(_g, 255, .1)
                    _b = numbers.interp(_b, 255, .1)

            if x > SIDEBAR_WIDTH + 3 and x < constants.WINDOW_WIDTH - 6:
                if y > 10 and y < 16:
                    _r = numbers.interp(_r, .0, .4)
                    _g = numbers.interp(_g, .0, .4)
                    _b = numbers.interp(_b, .0, .4)

            display._set_char('background', x, y, ' ', (0, 0, 0), (_r, _g, _b))
Beispiel #52
0
import libtcodpy as libtcod
import math
import textwrap
import game_settings as opt
import shelve

color_noise = libtcod.noise_new(2)

color_dark_wall = libtcod.Color(31, 31, 39)
bgcolor_dark_wall = libtcod.Color(31, 31, 39)
color_light_wall = libtcod.Color(80, 80, 77)
bgcolor_light_wall = libtcod.Color(50, 50, 48)
color_dark_ground = libtcod.Color(3, 3, 5)
bgcolor_dark_ground = libtcod.Color(20, 20, 26)
color_light_ground = libtcod.Color(80, 80, 77)
bgcolor_light_ground = libtcod.Color(32, 32, 29)


# TODO
# Generalize map code.
# Starting with Tile, I added four new options. default_fg, default_bg, default_char, and tile_name
# I will probably set something up so instead of setting tiles to blocked to determine if they're a wall,
# I'll instead just set the tile's tile_name to 'wall'
# When rendering, Instead of checking if it's blocked, I will just check for 'wall' or 'floor'
class Tile:
    # def __init__(self, blocked, block_sight = None):
    #     self.blocked = blocked
    #     self.explored = False
    def __init__(
            self,
            blocked,
Beispiel #53
0
#!/usr/bin/python
import math
import libtcodpy as libtcod
# size of the heightmap
HM_WIDTH=80
HM_HEIGHT=80
rnd=libtcod.random_new()
noise=libtcod.noise_new(2,libtcod.NOISE_DEFAULT_HURST,libtcod.NOISE_DEFAULT_LACUNARITY,rnd)
def addHill(hm,nbHill,baseRadius,radiusVar,height) :
    for i in range(nbHill) :
        hillMinRadius=baseRadius*(1.0-radiusVar)
        hillMaxRadius=baseRadius*(1.0+radiusVar)
        radius = libtcod.random_get_float(rnd,hillMinRadius, hillMaxRadius)
        theta = libtcod.random_get_float(rnd,0.0, 6.283185) # between 0 and 2Pi
        dist = libtcod.random_get_float(rnd,0.0, float(min(HM_WIDTH,HM_HEIGHT))/2 - radius)
        xh = int(HM_WIDTH/2 + math.cos(theta) * dist)
        yh = int(HM_HEIGHT/2 + math.sin(theta) * dist)
        libtcod.heightmap_add_hill(hm,float(xh),float(yh),radius,height)
# 3x3 kernel for smoothing operations
smoothKernelSize=9
smoothKernelDx=[-1,0,1,-1,0,1,-1,0,1]
smoothKernelDy=[-1,-1,-1,0,0,0,1,1,1]
smoothKernelWeight=[1.0,2.0,1.0,2.0,20.0,2.0,1.0,2.0,1.0]
# function building the heightmap
def buildMap(hm) :
    libtcod.heightmap_add_fbm(hm,noise,3.83,3.83,400,0,4.93,1,0.35)
    libtcod.heightmap_normalize(hm)

def head(l):
    if len(l) == 0:
        return None
Beispiel #54
0
def generate(width, height):
    _weight_map, _tile_map, _solids, _node_grid = mapgen.create_map(
        width, height)
    _zoom = .95
    _noise = tcod.noise_new(3)
    _low_grass = 25
    _fsl = {}
    _building_space = set()
    _walls = set()
    _possible_trees = set()
    _river_start_x = random.randint(int(round(width * .35)),
                                    int(round(width * .65)))
    _river_start_y = 0  #random.randint(int(round(height * .15)), int(round(height * .85)))
    _x = _river_start_x
    _y = _river_start_y
    _px, _py = _river_start_x, _river_start_y
    _river_direction = 270
    _turn_rate = random.randint(-1, 1)
    _river_tiles = set()
    _river_size = random.randint(7, 10)
    _ground_tiles = set()
    _possible_camps = set()

    while 1:
        for i in range(4, 10):
            for __x, __y in shapes.circle(_x, _y, _river_size):
                if __x < 0 or __y < 0 or __x >= width or __y >= height or (
                        __x, __y) in _solids:
                    continue

                _river_tiles.add((__x, __y))
                _tile = tiles.swamp_water(__x, __y)
                _tile_map[__y][__x] = _tile
                _weight_map[__y][__x] = _tile['w']

            _river_direction += _turn_rate
            _xv, _yv = numbers.velocity(_river_direction, 1)
            _px += _xv
            _py += _yv
            _x = int(round(_px))
            _y = int(round(_py))

            if _x < 0 or _y < 0 or _x >= width or _y >= height or (
                    _x, _y) in _solids:
                break

        if _x < 0 or _y < 0 or _x >= width or _y >= height:
            break

        _turn_rate = random.uniform(-2.5, 2.5)
        _river_size = numbers.clip(_river_size + random.randint(-1, 1), 7, 10)

    for y in range(height):
        for x in range(width):
            if (x, y) in _river_tiles:
                continue

            _tile = tiles.grass(x, y)
            _tile_map[y][x] = _tile
            _weight_map[y][x] = _tile['w']

            _ground_tiles.add((x, y))

    tcod.noise_set_type(_noise, tcod.NOISE_WAVELET)

    for y in range(height):
        for x in range(width):
            if (x, y) in _river_tiles:
                continue

            _noise_values = [(_zoom * x / (constants.MAP_VIEW_WIDTH)),
                             (_zoom * y / (constants.MAP_VIEW_HEIGHT))]
            _noise_value = 100 * tcod.noise_get_turbulence(
                _noise, _noise_values, tcod.NOISE_WAVELET)

            if _low_grass <= _noise_value <= 100:
                _tile = tiles.tall_grass(x, y)

                if _noise_value >= 40:
                    if not x < width * .15 and not x > width * .85 and not y < height * .15 and not y > height * .85:
                        _possible_camps.add((x, y))

                if random.uniform(0, 1) > .5:
                    _possible_trees.add((x, y))

            elif _noise_value >= _low_grass - 10 and 10 * random.uniform(
                    0, 1) > _low_grass - _noise_value:
                _tile = tiles.grass(x, y)

            else:
                _tile = tiles.rock(x, y)
                _solids.add((x, y))

            _tile_map[y][x] = _tile
            _weight_map[y][x] = _tile['w']

    _trees = {}
    _tree_plots = _possible_trees - _solids - _river_tiles
    _used_trees = random.sample(
        _tree_plots,
        numbers.clip(int(round((width * height) * .002)), 0, len(_tree_plots)))

    for x, y in _used_trees:
        _size = random.randint(1, 3)

        for _x, _y in shapes.circle(x, y, _size):
            if _x < 0 or _y < 0 or _x >= width or _y >= height or (
                    _x, _y) in _solids:
                break

            _tile = tiles.tree(_x, _y)
            _weight_map[_y][_x] = _tile['w']
            _tile_map[_y][_x] = _tile
            _trees[_x, _y] = random.uniform(2, 3.5) * _size

            _solids.add((_x, _y))

    _ground_tiles = _ground_tiles - _solids
    _plot_pole_x, _plot_pole_y = width / 2, height / 2
    _bushes = random.sample(
        _ground_tiles,
        numbers.clip(int(round((width * height) * .0003)), 0,
                     len(_ground_tiles)))
    _camps = set()

    while len(_possible_camps):
        _camp_1 = random.choice(list(_possible_camps))
        _possible_camps.remove(_camp_1)
        _camps.add(_camp_1)

        for camp_2 in _possible_camps.copy():
            _dist = numbers.distance(_camp_1, camp_2)

            if _dist <= 250:
                _possible_camps.remove(camp_2)

    for x, y in _bushes:
        _walker_x = x
        _walker_y = y
        _last_dir = -2, -2

        for i in range(random.randint(10, 15)):
            _tile = tiles.tree(_walker_x, _walker_y)
            _weight_map[_walker_y][_walker_x] = _tile['w']
            _tile_map[_walker_y][_walker_x] = _tile

            _dir = random.randint(-1, 1), random.randint(-1, 1)
            _n_x = _walker_x + _dir[0]
            _n_y = _walker_y + _dir[1]

            if _n_x < 0 or _n_y < 0 or _n_x >= width or _n_y >= height or (
                    _n_x, _n_y) in _solids:
                break

            _last_dir = _dir[0] * -1, _dir[0] * -1
            _walker_x = _n_x
            _walker_y = _n_y

    _camp_info = {}

    for c_x, c_y in _camps:
        _building_walls = random.sample(['north', 'south', 'east', 'west'],
                                        random.randint(2, 3))
        _broken_walls = random.sample(
            _building_walls,
            numbers.clip(random.randint(0, 3), 0, len(_building_walls)))
        _camp = {'center': (c_x, c_y)}
        _camp_ground = []

        for y in range(-10, 10 + 1):
            for x in range(-10, 10 + 1):
                _x = x + c_x
                _y = y + c_y

                if (_x, _y) in _solids or (_x, _y) in _river_tiles:
                    continue

                if (x == -10 and 'west' in _building_walls) or (
                        y == -10 and 'north' in _building_walls) or (
                            x == 10 and 'east' in _building_walls) or (
                                y == 10 and 'south' in _building_walls):
                    if x == -10 and 'west' in _building_walls and 'west' in _broken_walls and random.uniform(
                            0, 1) > .75:
                        continue

                    if x == 10 and 'east' in _building_walls and 'east' in _broken_walls and random.uniform(
                            0, 1) > .75:
                        continue

                    if y == -10 and 'north' in _building_walls and 'north' in _broken_walls and random.uniform(
                            0, 1) > .75:
                        continue

                    if y == 10 and 'south' in _building_walls and 'south' in _broken_walls and random.uniform(
                            0, 1) > .75:
                        continue

                    _tile = tiles.wooden_fence(_x, _y)
                    _weight_map[_y][_x] = _tile['w']
                    _tile_map[_y][_x] = _tile
                    _solids.add((_x, _y))

                elif (x > -10 and x <= 10) and (y > -10 and y <= 10):
                    _camp_ground.append((_x, _y))

        _camp['ground'] = _camp_ground[:]
        _camp_info[c_x, c_y] = _camp

    mapgen.build_node_grid(_node_grid, _solids)

    for c_x, c_y in _camps:
        mapgen.add_plot_pole(c_x, c_y, 40, _solids)

    _fsl = {
        'Terrorists': {
            'bases': 1,
            'squads': 0,
            'trader': False,
            'type': life.human_runner
        }
    }
    #        #'Militia': {'bases': 0, 'squads': 1, 'trader': False, 'type': life.human_bandit},
    #        'Wild Dogs': {'bases': 0, 'squads': 1, 'trader': False, 'type': life.wild_dog}}

    return width, height, _node_grid, mapgen.NODE_SETS.copy(
    ), _weight_map, _tile_map, _solids, _fsl, _trees, _building_space - _walls
Beispiel #55
0
def MasterWorldGen(
):  #------------------------------------------------------- * MASTER GEN * -------------------------------------------------------------

    print ' * World Gen START * '
    starttime = time.time()

    #Heightmap
    hm = libtcod.heightmap_new(WORLD_WIDTH, WORLD_HEIGHT)

    for i in range(50):
        libtcod.heightmap_add_hill(
            hm, randint(WORLD_WIDTH / 10, WORLD_WIDTH - WORLD_WIDTH / 10),
            randint(WORLD_HEIGHT / 10, WORLD_HEIGHT - WORLD_HEIGHT / 10),
            randint(12, 16), randint(6, 10))
    print '- Main Hills -'

    for i in range(200):
        libtcod.heightmap_add_hill(
            hm, randint(WORLD_WIDTH / 10, WORLD_WIDTH - WORLD_WIDTH / 10),
            randint(WORLD_HEIGHT / 10, WORLD_HEIGHT - WORLD_HEIGHT / 10),
            randint(2, 4), randint(6, 10))
    print '- Small Hills -'

    libtcod.heightmap_normalize(hm, 0.0, 1.0)

    noisehm = libtcod.heightmap_new(WORLD_WIDTH, WORLD_HEIGHT)
    noise2d = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST,
                                libtcod.NOISE_DEFAULT_LACUNARITY)
    libtcod.heightmap_add_fbm(noisehm, noise2d, 4, 4, 0, 0, 32, 1, 1)
    libtcod.heightmap_normalize(noisehm, 0.0, 1.0)
    libtcod.heightmap_multiply_hm(hm, noisehm, hm)
    print '- Apply Simplex -'

    PoleGen(hm, 0)
    print '- South Pole -'

    PoleGen(hm, 1)
    print '- North Pole -'

    TectonicGen(hm, 0)
    TectonicGen(hm, 1)
    print '- Tectonic Gen -'

    libtcod.heightmap_rain_erosion(hm, WORLD_WIDTH * WORLD_HEIGHT, 0.07, 0, 0)
    print '- Erosion -'

    libtcod.heightmap_clamp(hm, 0.0, 1.0)

    #Temperature
    temp = libtcod.heightmap_new(WORLD_WIDTH, WORLD_HEIGHT)
    Temperature(temp, hm)
    libtcod.heightmap_normalize(temp, 0.0, 0.8)
    print '- Temperature Calculation -'

    #Precipitation

    preciphm = libtcod.heightmap_new(WORLD_WIDTH, WORLD_HEIGHT)
    Percipitaion(preciphm, temp)
    libtcod.heightmap_normalize(preciphm, 0.0, 0.8)
    print '- Percipitaion Calculation -'

    #Drainage

    drainhm = libtcod.heightmap_new(WORLD_WIDTH, WORLD_HEIGHT)
    drain = libtcod.noise_new(2, libtcod.NOISE_DEFAULT_HURST,
                              libtcod.NOISE_DEFAULT_LACUNARITY)
    libtcod.heightmap_add_fbm(drainhm, drain, 2, 2, 0, 0, 32, 1, 1)
    libtcod.heightmap_normalize(drainhm, 0.0, 0.8)
    print '- Drainage Calculation -'

    # VOLCANISM - RARE AT SEA FOR NEW ISLANDS (?) RARE AT MOUNTAINS > 0.9 (?) RARE AT TECTONIC BORDERS (?)

    elapsed_time = time.time() - starttime
    print ' * World Gen DONE *    in: ', elapsed_time, ' seconds'

    #Initialize Tiles with Map values
    World = [[0 for y in range(WORLD_HEIGHT)]
             for x in range(WORLD_WIDTH)]  #100x100 array
    for x in xrange(WORLD_WIDTH):
        for y in xrange(WORLD_HEIGHT):
            World[x][y] = Tile(libtcod.heightmap_get_value(hm, x, y),
                               libtcod.heightmap_get_value(temp, x, y),
                               libtcod.heightmap_get_value(preciphm, x, y),
                               libtcod.heightmap_get_value(drainhm, x, y), 0)

    print '- Tiles Initialized -'

    #Prosperity

    Prosperity(World)
    print '- Prosperity Calculation -'

    #Biome info to Tile

    for x in xrange(WORLD_WIDTH):
        for y in xrange(WORLD_HEIGHT):

            if World[x][y].height > 0.2:
                World[x][y].biomeID = 3
                if randint(1, 10) < 3:
                    World[x][y].biomeID = 5
            if World[x][y].height > 0.4:
                World[x][y].biomeID = 14
                if randint(1, 10) < 3:
                    World[x][y].biomeID = 5
            if World[x][y].height > 0.5:
                World[x][y].biomeID = 8
                if randint(1, 10) < 3:
                    World[x][y].biomeID = 14

            if World[x][y].temp <= 0.5 and World[x][y].precip >= 0.5:
                World[x][y].biomeID = 5
                if randint(1, 10) < 3:
                    World[x][y].biomeID = 14
            if World[x][y].temp >= 0.5 and World[x][y].precip >= 0.7:
                World[x][y].biomeID = 6

            if World[x][y].precip >= 0.7 and World[x][
                    y].height > 0.2 and World[x][y].height <= 0.4:
                World[x][y].biomeID = 2

            if World[x][y].temp > 0.75 and World[x][y].precip < 0.35:
                World[x][y].biomeID = 4

            if World[x][y].temp <= 0.22 and World[x][y].height > 0.2:
                World[x][y].biomeID = randint(11, 13)
            if World[x][y].temp <= 0.3 and World[x][y].temp > 0.2 and World[x][
                    y].height > 0.2 and World[x][y].precip >= 0.6:
                World[x][y].biomeID = 7

            if World[x][y].height > 0.75:
                World[x][y].biomeID = 9
            if World[x][y].height > 0.999:
                World[x][y].biomeID = 10
            if World[x][y].height <= 0.2:
                World[x][y].biomeID = 0
            if World[x][y].height <= 0.1:
                World[x][y].biomeID = 0

    print '- BiomeIDs Atributed -'

    #River Gen

    for x in range(5):
        RiverGen(World)
    print '- River Gen -'

    #Free Heightmaps
    libtcod.heightmap_delete(hm)
    libtcod.heightmap_delete(temp)
    libtcod.heightmap_delete(noisehm)

    print ' * Biomes/Rivers Sorted *'

    return World
################################################################################
# Map
################################################################################
MAP_WIDTH = 500
MAP_HEIGHT = 500

ROOM_MAX_SIZE = 20
ROOM_MIN_SIZE = 10
MAX_ROOMS = 450

MAX_ROOM_MONSTERS = 3
MAX_ROOM_ITEMS = 3

# Noise for generating terrain
height_map = libtcod.noise_new(2)

color_dark_wall = libtcod.Color(0, 0, 100)
color_light_wall = libtcod.Color(130, 110, 50)
color_dark_ground = libtcod.Color(50, 50, 150)
color_light_ground = libtcod.Color(200, 180, 50)


class Tile:
    #a tile of the map and its properties
    def __init__(self, blocked, data, block_sight=None, tile_type=None):
        self.blocked = blocked
        self.tile_type = tile_type
        self.data = data

        #by default, if a tile is blocked, it also blocks sight