繁体   English   中英

对于 ant 模拟,如何更有效地存储和使用值?

[英]How can i store and use values more efficiently for a ant simulation?

我正在制作 ant 模拟,我需要存储所有信息素(int 值)。

下面是它的工作原理:

  • 当一个 ant go 某处它存放 10 信息素。(已经完成)
  • 每滴答一次,信息素值就会减少 1 并且不能低于 0。

我需要一些东西来稍微有效地做最后一件事。
这是我的代码:

# world is the map on a 1000x1000 array of 0 at the start
def evaporate():
    for x in range(len(world)):
        for y in range(len(world[0])):
            if world[x][y] > 0:
                world[x][y] -= 1

我认为有更好的方法来存储 map 值,但我找不到一种有效的方法。
如果你不能使用更好的库,因为我想看看我的程序做了什么,但如果它更有效或更容易,那没关系!

如果有任何错别字告诉我,我会更正。 (英语不是我的主要语言)
谢谢你的时间。

一个 1000 x 1000 的世界有 1.000.000 个图块。 一个是你的基地,几个是蚂蚁,有些是信息素。

与其存储完整的 map,不如仅存储存在数据的位置。 您可以使用以 (x,y) 作为键的字典。

由于信息素级别 10 代表 ant,您可以这样做:

class ant():
    import random
    # movement delta in 8 directions
    _delta_move = [(dx,dy) for dx in range(-1,2) for dy in range(-1,2)]

    def __init__(self, x, y, maxage = 5):
        self.__x = x
        self.__y = y
        self.age = maxage

    def getPos(self):
        return (self.__x, self.__y)

    def kill(self):
        self.age = 0

    def random_move(self):
        # every move reduces ants age, when 0 it dies
        self.age -= 1
        if self.age > 0:
            d = random.choice(ant._delta_move)
            self.__x += d[0]
            self.__y += d[1]
            return self.getPos()
        return None # dead

创建一个蚂蚁列表和一个 map 并传播运动:

mapsize = 10

# helper 
def print_map(m):
    """prints the map, if a pheromon level is 10 the ant is in this field"""
    for y in range(mapsize):
        print("  #",end="")
        for x in range(mapsize):
            value = m.get( (x,y), " ")
            if value == 10:
                value = "a"
            elif value == 0:
                value = " "
            print(value, end="")
        print()


# list of ants
ants = [ ant(5, 5, 6) for _ in range(5 )]

# initial map, 10 pheromones is max per field
ant_map = { a.getPos():10 for a in ants}

while (ants):
    print_map(ant_map)
    input("Enter for next round")

    # decay pheromones
    done = [] # store keys to delete, avoid changing dict while iterating
    for key,value in ant_map.items():
        if value > 0:
            ant_map[key] -= 1
        else:
            done.append(key)
    for k in done:
         del ant_map[k]

    # remove dead ants
    ants = [a for a in ants if a.age > 0]

    # move ants and add new pheromones
    for a in ants:
        # move ant
        new_pos = a.random_move()
        if new_pos and 0 <= new_pos[0] < mapsize and 0 <= new_pos[1] < mapsize:
            ant_map[new_pos] = 10
        else:
            a.kill()

print_map(ant_map)

Output:

  #          
  #          
  #          
  #          
  #          
  #     a    
  #          
  #          
  #          
  #          
Enter for next round 
  #          
  #          
  #          
  #          
  #    a a   
  #     aa   
  #          
  #          
  #          
  #          
Enter for next round
  #          
  #          
  #          
  #    a     
  #    a 9a  
  #     9a   
  #      a   
  #          
  #          
  #          
Enter for next round 
  #          
  #          
  #          
  #    9aa   
  #   a9a89  
  #     89   
  #     a9   
  #          
  #          
  #          
Enter for next round 
  #          
  #          
  #    a a   
  #    8a9   
  #   a8978  
  #     7a   
  #     98   
  #          
  #          
  #          
Enter for next round 
  #          
  #          
  #    9a9   
  #  a 7a8   
  #   97a67  
  #     6a   
  #     87   
  #          
  #          
  #          
Enter for next round 
  #          
  #          
  #    898   
  #  9 697   
  #   86956  
  #     59   
  #     76   
  #          
  #          
  #          
Enter for next round 
  #          
  #          
  #    787   
  #  8 586   
  #   75845  
  #     48   
  #     65   
  #          
  #          
  #          
Enter for next round
  #          
  #          
  #    676   
  #  7 475   
  #   64734  
  #     37   
  #     54   
  #          
  #          
  #          
Enter for next round
  #          
  #          
  #    565   
  #  6 364   
  #   53623  
  #     26   
  #     43   
  #          
  #          
  #          
Enter for next round 
  #          
  #          
  #    454   
  #  5 253   
  #   42512  
  #     15   
  #     32   
  #          
  #          
  #          
Enter for next round  
  #          
  #          
  #    343   
  #  4 142   
  #   314 1  
  #      4   
  #     21   
  #          
  #          
  #          
Enter for next round  
  #          
  #          
  #    232   
  #  3  31   
  #   2 3    
  #      3   
  #     1    
  #          
  #          
  #          
Enter for next round 
  #          
  #          
  #    121   
  #  2  2    
  #   1 2    
  #      2   
  #          
  #          
  #          
  #          
Enter for next round
  #          
  #          
  #     1    
  #  1  1    
  #     1    
  #      1   
  #          
  #          
  #          
  #          
 

尝试这个:

import numpy as np  # <-- for efficient storage
import matplotlib.pyplot as plt # <-- for visualization

# Initialize a random map with values from 0 to 10.
pheromone_map = np.random.randint(low=0, high=11, size=(1000, 1000))

# Visualize the pheromones disappearing
for i in range(10):
    # clip removes any negative value from the array that had 1 subtracted from it
    pheromone_map = np.clip(pheromone_map - 1, a_min=0, a_max=11)
    # Shows how the pheromones disappear
    fig, ax = plt.subplots()
    ax.imshow(pheromone_map)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM