Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.86 KB | None | 0 0
  1. class blob:
  2.     ## Добавить атрибут имя))0
  3.     def __init__(self, moves, size, flee, lastmove, food, x, y):
  4.         global count
  5.         self.id = count
  6.         self.moves = moves
  7.         self.size = size
  8.         self.flee = flee
  9.         self.lastmove = lastmove
  10.         self.mademoves = 0
  11.         self.food = food
  12.         self.x = x ## Начальную координату рандомом зададим есчто, проверить, что в этом месте ничего нет
  13.         self.y = y
  14.        
  15.     def show_id(self):
  16.         return self.id
  17.    
  18.     def addfood(self):
  19.         self.food+=1 ## Когда покушал
  20.        
  21.     def reset_mm(self):
  22.         self.mademoves = 0
  23.        
  24.     def addmove(self):
  25.         self.mademoves += 1 ## Сделанные за день движения
  26.        
  27.     def setlastmove(self, move):
  28.         self.lastmove = int(move) ## Сделанные за день движения
  29.        
  30.     def blobx(self):
  31.         return self.x ## blobx и bloby возвращают координаты
  32.    
  33.     def bloby(self):
  34.         return self.y
  35.    
  36.     def changex(self, x): ## Изменить координаты
  37.         self.x = x
  38.        
  39.     def changey(self, y):
  40.         self.y = y
  41.        
  42.     def moves(self):
  43.         return self.moves
  44.    
  45.     def size(self):
  46.         return self.size
  47.    
  48.     def flee(self):
  49.         return self.flee
  50.    
  51.     def lastmove(self):
  52.         return self.lastmove
  53.    
  54.     def mademoves(self):
  55.         return self.mademoves
  56.    
  57.     def food(self):
  58.         return self.food
  59.    
  60.     def movecost(self):
  61.         return int(1) #round(self.size / 0.2 - 5) ## Вот это тоже со скобочками
  62.    
  63.     def energy(self):
  64.         if self.moves <= 10: ## starting moves = 10
  65.             consume = 0.8
  66.         else:
  67.             consume = self.moves // 20 ### ПОТОМ УБРАТЬ
  68.         energy = self.food - consume
  69.         return energy
  70.  
  71. ## Добавить больше на 20%    
  72.    
  73.     def __gt__(self, other): ## greater than
  74.         return self.size > other.size
  75.    
  76.     def __lt__(self, other): ## less than
  77.         return self.size < other.size
  78.    
  79.     def __ge__(self, other): ## greater or equal
  80.         return self.size >= other.size
  81.    
  82.     def __le__(self, other): ## less or equal
  83.         return self.size <= other.size
  84.    
  85.     def __eq__(self, other): ## equal
  86.         return self.size == other.size
  87.    
  88.     def __ne__(self, other):
  89.         return self.size != other.size  
  90.    
  91.     def __str__(self):
  92.         return 'A'
  93.    
  94.     def replicate(self):
  95.        
  96.         global community, escapists, count
  97.         baby_flee = self.flee
  98.         baby_moves = self.moves
  99.         baby_size = self.size
  100.        
  101.         chance = 0.5    # can be adjusted later; шанс мутации при перерождении
  102.         if random() < chance:
  103.             temp = randint(1, 2)
  104.             if temp == 1:
  105.                 baby_moves = self.moves + 1
  106.             elif (temp == 2) and (self.moves > 1): ## мувз должны быть больше 1
  107.                 baby_moves = self.moves + 1 ## Есть шанс стать хуже или лучше бати по подвижности
  108.    
  109.         if random() < chance:
  110.             temp = randint(1, 2)
  111.             if temp == 1:
  112.                 baby_size = self.size + 0.1
  113.             elif (temp == 2) and (self.size > 0.1):
  114.                 baby_size = self.size - 0.1
  115.                
  116.         if random() < chance:
  117.             temp = randint(1, 2)
  118.             if temp == 1:
  119.                 baby_flee = self.flee + 0.1
  120.             elif (temp == 2) and (self.flee > 0.1):
  121.                 baby_flee = self.flee - 0.1
  122.         count += 1
  123.         baby_blob = blob(baby_moves, baby_size, baby_flee, 0, 0, 1, 1)
  124.         community.add(baby_blob)
  125.         escapists.append(baby_blob)
  126.  
  127.        
  128.        
  129.     def test_blob(self):
  130.        
  131.         temp = self.moves - self.movecost() - self.mademoves
  132.         if temp > 0:
  133.             return True
  134.         else:
  135.             return False
  136.  
  137. class food:
  138.    
  139.     def __init__(self):
  140.         self.name = 'F'
  141.    
  142.     def __repr__(self):
  143.         return self.name
  144.    
  145.     def __str__(self):
  146.         return self.name
  147.  
  148. from random import randint, random
  149. from math import log
  150.  
  151. #escapists = []    # FUCKIN AWOLS WHAT THE FUCK
  152.  
  153. class field:
  154.    
  155.     def __init__(self, side):
  156.        
  157.         self.field = [[0 for x in range(side)] for y in range(side)]
  158.         self.side = side
  159.  
  160.         for i in range(side):
  161.             for j in range(side):
  162.                 if i == 0 or j == 0 or i == side-1 or j == side-1:
  163.                     self.field[i][j] = 'x'
  164.    
  165.     def clear(self, y, x):
  166.         self.field[y][x] = 0
  167.        
  168.     def new_print(self):
  169.         for i in range(self.side):
  170.             for j in range(self.side):
  171.                 print(str(self.field[i][j]), end = ' ')
  172.             print()
  173.            
  174.     def spawn_food(self, foodnumber):
  175.    
  176.         count = foodnumber
  177.         erf = foodnumber * 3 ## Это нереальный костыль, но пока пусть будет
  178.        
  179.         while (count > 0) and (erf > 0):
  180.             erf -= 1
  181.             x = randint(1, self.side-2)
  182.             y = randint(1, self.side-2)
  183.             if type(self.field[x][y]) == int:
  184.                 if self.field[x][y] == 0:
  185.                     self.field[x][y] = food()
  186.                     count -= 1
  187.                
  188.     def clear_food(self):
  189.  
  190.         for i in range(1, self.side-1):
  191.             for j in range(1, self.side-1):
  192.                 if type(self.field[i][j]) == food:
  193.                     self.field[i][j] = 0
  194.                    
  195.     def isfood(self,y,x):
  196.        
  197.         return type(self.field[y][x]) == food
  198.    
  199.     def isblob(self,y,x):
  200.        
  201.         return type(self.field[y][x]) == blob
  202.    
  203.     def spawn_escapists(self):
  204.        
  205.         global escapists
  206.         #print(escapists)
  207.         count = len(escapists)
  208.         erf = count * 5 ## Костыль
  209.         while (count > 0) and (erf > 0):
  210.             erf -= 1
  211.             x = randint(1, self.side-1)
  212.             y = randint(1, self.side-1)
  213.             if type(self.field[x][y]) == int:
  214.                 my_blob = escapists.pop()
  215.                 my_blob.changex(y)
  216.                 my_blob.changey(x)
  217.                 self.field[x][y] = my_blob ## Мы спауним на пустые места эскейпистов
  218.                 count -= 1
  219.         #print(escapists)
  220.                
  221.     def observe(self, my_blob):
  222.        
  223.         global escapists
  224.        
  225.         x = my_blob.blobx()
  226.         y = my_blob.bloby()
  227.        
  228.         for i,j in [(1,0),(-1,0),(0,1),(0,-1)]:
  229.            
  230.             if self.isfood(y+j,x+i):
  231.                 my_blob.addfood()
  232.                 self.field[y+j][x+i] = 0 ## Обнулили где сожрали
  233.                
  234.             elif self.isblob(y+j,x+i):
  235.                
  236.                 bad_blob = self.field[y+j][x+i]
  237.                
  238.                 if my_blob < bad_blob:
  239.                     chance = 0.1 * (log(my_blob.flee) + 1)
  240.                     destiny = random()
  241.                     if destiny < chance: ## Мы сбежали
  242.                         escapists.append(my_blob)
  243.                         self.field[y][x] = 0
  244.                         my_blob.reset_mm()
  245.                     else: ## Нас съели
  246.                         self.field[y][x] = 0
  247.                         self.field[y+j][x+i].addfood() ## bad_blob.addfood()
  248.                         #Из массива блобов надо удалить съеденного
  249.                        
  250.                 elif my_blob > bad_blob:
  251.                     chance = 0.1 * (log(bad_blob.flee) + 1)
  252.                     destiny = random()  
  253.                     if destiny < chance: ## От нас сбежали
  254.                         escapists.append(bad_blob)
  255.                         self.field[y+j][x+i] = 0
  256.                         bad_blob.reset_mm()
  257.                     else: ## Мы съели
  258.                         self.field[y+j][x+i] = 0
  259.                         my_blob.addfood()
  260.                         #Из массива блобов надо удалить съеденного
  261.                        
  262.     def move(self, my_blob, n):
  263.         ## На рекурсии удобно, просто будем запускать с n=4
  264.         if n == 0:
  265.             pass #че если 0, то мы заканчиваем, типа мы чекаем 4 раза, чтобы матожидание было норм
  266.         else:
  267.             direction = randint(1,4)
  268.             x = my_blob.blobx()
  269.             y = my_blob.bloby()
  270.        
  271.             if (direction == 1) and (my_blob.lastmove != 3) and (isinstance(self.field[y-1][x], int)):
  272.                 self.up(my_blob)
  273.             elif (direction == 2) and (my_blob.lastmove != 4) and (isinstance(self.field[y][x+1], int)):
  274.                 self.right(my_blob)
  275.             elif (direction == 3) and (my_blob.lastmove != 1) and (isinstance(self.field[y+1][x], int)):
  276.                 self.down(my_blob)
  277.             elif (direction == 4) and (my_blob.lastmove != 2) and (isinstance(self.field[y][x-1], int)):
  278.                 self.left(my_blob)
  279.             else:
  280.                 self.move(my_blob, n-1)
  281.    
  282.     def up(self, my_blob):
  283.        
  284.         x = my_blob.blobx()
  285.         y = my_blob.bloby()
  286.        
  287.         my_blob.addmove()
  288.         self.field[y-1][x] = my_blob
  289.         self.field[y][x] = 0
  290.         my_blob.changey(y-1)
  291.         my_blob.setlastmove(1)
  292.        
  293.        
  294.     def right(self, my_blob):
  295.        
  296.         x = my_blob.blobx()
  297.         y = my_blob.bloby()
  298.        
  299.         my_blob.addmove()
  300.         self.field[y][x+1] = my_blob
  301.         self.field[y][x] = 0
  302.         my_blob.changex(x+1)
  303.         my_blob.setlastmove(2)
  304.        
  305.     def down(self, my_blob):
  306.        
  307.         x = my_blob.blobx()
  308.         y = my_blob.bloby()
  309.        
  310.         my_blob.addmove()
  311.         self.field[y+1][x] = my_blob
  312.         self.field[y][x] = 0
  313.         my_blob.changey(y+1)
  314.         my_blob.setlastmove(3)
  315.        
  316.     def left(self, my_blob):
  317.        
  318.         x = my_blob.blobx()
  319.         y = my_blob.bloby()
  320.        
  321.         my_blob.addmove()
  322.         self.field[y][x-1] = my_blob
  323.         self.field[y][x] = 0
  324.         my_blob.changex(x-1)
  325.         my_blob.setlastmove(4)
  326.  
  327. import pandas as pd
  328.  
  329. class bloblist:
  330.    
  331.     def __init__(self):
  332.         ## Лист и длина листа
  333.         self.enlist = []
  334.         self.population = 0
  335.        
  336.     def population(self):
  337.         return self.population
  338.    
  339.     def enlist(self):
  340.         return self.enlist
  341.    
  342.     def add(self, unit):
  343.         ## Добавить очередное хуило
  344.         self.enlist.append(unit)
  345.         self.population+=1
  346.         #print(self.population)
  347.        
  348.     def choose(self, index):
  349.         ## Обращение по индексу
  350.         res = self.enlist[index]
  351.         return res
  352.        
  353.     def all_moves(self):
  354.        
  355.         res = []
  356.         for i in range(self.population):
  357.             temp = self.choose(i).moves
  358.             res.append(temp)
  359.            
  360.         res.sort()
  361.         return res
  362.    
  363.     def all_size(self):
  364.        
  365.         res = []
  366.         for i in range(self.population):
  367.             temp = self.choose(i).size
  368.             res.append(temp)
  369.            
  370.         res.sort()
  371.         return res
  372.    
  373.     def all_flee(self):
  374.        
  375.         res = []
  376.         for i in range(self.population):
  377.             temp = self.choose(i).flee
  378.             res.append(temp)
  379.            
  380.         res.sort()    
  381.         return res                
  382.        
  383.     def delete(self, my_blob):
  384.         if my_blob in self.enlist:
  385.             del self.enlist[self.enlist.index(my_blob)]
  386.             self.population -= 1
  387.             ## Тут надо вписать смерть блобчика
  388.            
  389.     def test_all(self):
  390.        
  391.         res = False
  392.         for i in self.enlist:
  393.             if i.test_blob() == True:
  394.                 res = True
  395.                 break
  396.                
  397.         return res
  398.        
  399.     def __str__(self):
  400.         return str(self.enlist)
  401.    
  402.     def show_stats(self):
  403.         local_count = 0
  404.         columns = ['id','size', 'flee', 'moves']
  405.         df = pd.DataFrame(columns = columns)
  406.         for i in self.enlist:
  407.             df.loc[local_count] = [int(i.show_id()),i.size, i.flee, i.moves]
  408.             local_count+=1
  409.            
  410.         df['id'] = df['id'].astype(int).round(decimals = 0)
  411.        
  412.         return df    
  413.        
  414. community = bloblist() # global
  415. escapists = []
  416. count = 0
  417.  
  418. def end(my_field):
  419.    
  420.     global community, escapists
  421.     ## Это будет массив блобов всех
  422.    
  423.     for i in community.enlist:
  424.         E = i.energy()
  425.         x = i.blobx()
  426.         y = i.bloby()
  427.         #print('Energy is:' + str(E))
  428.         if E < 0: ## Короче хуйня надо подобрать параметры энергии
  429.             my_field.clear(y,x)
  430.             community.delete(i)
  431.            
  432.         elif E > 1:
  433.             i.replicate()
  434.            
  435.         i.reset_mm()
  436.  
  437. # Константы и переменные
  438. DAYS = 7         # Количество дней симуляции
  439. SIDE = 20       # Сторона поля
  440. FOODNUMBER = 50   # Количество хавки на полу
  441. my_field = field(SIDE)
  442. lil_pump = blob(10, 1, 1, 0, 1, 1, 1)    # Маленький насос спавнится в верхнем левом углу
  443. community.add(lil_pump)               # Маленький насос становится членом коммуны
  444. escapists.append(lil_pump)              # Маленький насос сбежал вот блин
  445.  
  446. daycount = 0
  447. df_dict = {}
  448. for day in range(DAYS):
  449.    
  450.     if community.population == 0:
  451.         break
  452.        
  453.     my_field.clear_food()
  454.     my_field.spawn_escapists()
  455.     my_field.spawn_food(FOODNUMBER)
  456.     while community.test_all():
  457.         for unit in community.enlist:
  458.             my_field.observe(unit)
  459.             if unit.test_blob(): ## Вот тут хуйня какая-то го чекать
  460.                 my_field.move(unit, 4)
  461.     community.show_stats().head()
  462.     my_field.new_print()
  463.     #print('{}'.format(''))
  464.     print(community)          
  465.     end(my_field)
  466.    
  467.     daycount+=1
  468.     df_dict[daycount] = community.show_stats()
  469.  
  470. import matplotlib.pyplot as plt
  471.  
  472. def plot_all(df_dict):
  473.  
  474.     size_dict = {}
  475.     flee_dict = {}
  476.     moves_dict = {}
  477.  
  478.     for i in df_dict:
  479.         size_dict[i] = df_dict[i].copy()
  480.         flee_dict[i] = df_dict[i].copy()
  481.         moves_dict[i] = df_dict[i].copy()
  482.        
  483.     ############# Для size ################
  484.  
  485.  
  486.     for i in size_dict:
  487.         size_dict[i].drop('flee', axis = 1, inplace = True)
  488.         size_dict[i].drop('moves', axis = 1, inplace = True)
  489.    
  490.     grouped_size_dict = {}
  491.     size_count = 1
  492.  
  493.     for k in size_dict:
  494.         grouped_size_dict[size_count] = size_dict[k].groupby('size').count()
  495.         grouped_size_dict[size_count].reset_index(inplace=True)
  496.         size_count+=1
  497.    
  498.     a = []
  499.  
  500.     for k in grouped_size_dict:
  501.         b = grouped_size_dict[k]['size']
  502.         for i in range(len(b)):
  503.             a.append(b[i])
  504.        
  505.     unique_a = []
  506.  
  507.     for i in a:
  508.         if i not in unique_a:
  509.             unique_a.append(i)
  510.        
  511.     size_df_dict = {}
  512.  
  513.     for k in grouped_size_dict:
  514.    
  515.         bad_dict = pd.DataFrame.to_dict(grouped_size_dict[k])
  516.    
  517.         my_list = [int(0) for i in range(len(unique_a))]
  518.  
  519.         for i in bad_dict['size']:
  520.        
  521.             if bad_dict['size'][i] in unique_a:
  522.                 index = unique_a.index(bad_dict['size'][i])
  523.                 my_list[index] = bad_dict['id'][i]
  524.  
  525.         size_df_dict[k] = my_list
  526.    
  527.     size_df = pd.DataFrame.from_dict(size_df_dict, orient = 'index')
  528.     columns = unique_a
  529.     size_df.columns = columns
  530.    
  531.     ############# Для flee ################
  532.  
  533.     for i in flee_dict:
  534.         flee_dict[i].drop('size', axis = 1, inplace = True)
  535.         flee_dict[i].drop('moves', axis = 1, inplace = True)
  536.    
  537.     grouped_flee_dict = {}
  538.     flee_count = 1
  539.  
  540.     for k in flee_dict:
  541.         grouped_flee_dict[flee_count] = flee_dict[k].groupby('flee').count()
  542.         grouped_flee_dict[flee_count].reset_index(inplace=True)
  543.         flee_count+=1
  544.    
  545.     a = []
  546.  
  547.     for k in grouped_flee_dict:
  548.         b = grouped_flee_dict[k]['flee']
  549.         for i in range(len(b)):
  550.             a.append(b[i])
  551.        
  552.     unique_a = []
  553.  
  554.     for i in a:
  555.         if i not in unique_a:
  556.             unique_a.append(i)
  557.        
  558.     flee_df_dict = {}
  559.  
  560.     for k in grouped_flee_dict:
  561.    
  562.         bad_dict = pd.DataFrame.to_dict(grouped_flee_dict[k])
  563.    
  564.         my_list = [int(0) for i in range(len(unique_a))]
  565.  
  566.         for i in bad_dict['flee']:
  567.        
  568.             if bad_dict['flee'][i] in unique_a:
  569.                 index = unique_a.index(bad_dict['flee'][i])
  570.                 my_list[index] = bad_dict['id'][i]
  571.  
  572.         flee_df_dict[k] = my_list
  573.    
  574.     flee_df = pd.DataFrame.from_dict(flee_df_dict, orient = 'index')
  575.     columns = unique_a
  576.     flee_df.columns = columns
  577.    
  578.     ############# Для moves ################
  579.  
  580.     for i in moves_dict:
  581.         moves_dict[i].drop('size', axis = 1, inplace = True)
  582.         moves_dict[i].drop('flee', axis = 1, inplace = True)
  583.    
  584.     grouped_moves_dict = {}
  585.     moves_count = 1
  586.  
  587.     for k in moves_dict:
  588.         grouped_moves_dict[moves_count] = moves_dict[k].groupby('moves').count()
  589.         grouped_moves_dict[moves_count].reset_index(inplace=True)
  590.         moves_count+=1
  591.    
  592.     a = []
  593.  
  594.     for k in grouped_moves_dict:
  595.         b = grouped_moves_dict[k]['moves']
  596.         for i in range(len(b)):
  597.             a.append(b[i])
  598.        
  599.     unique_a = []
  600.  
  601.     for i in a:
  602.         if i not in unique_a:
  603.             unique_a.append(i)
  604.        
  605.     moves_df_dict = {}
  606.  
  607.     for k in grouped_moves_dict:
  608.    
  609.         bad_dict = pd.DataFrame.to_dict(grouped_moves_dict[k])
  610.    
  611.         my_list = [int(0) for i in range(len(unique_a))]
  612.  
  613.         for i in bad_dict['moves']:
  614.        
  615.             if bad_dict['moves'][i] in unique_a:
  616.                 index = unique_a.index(bad_dict['moves'][i])
  617.                 my_list[index] = bad_dict['id'][i]
  618.  
  619.         moves_df_dict[k] = my_list
  620.    
  621.     moves_df = pd.DataFrame.from_dict(moves_df_dict, orient = 'index')
  622.     columns = unique_a
  623.     moves_df.columns = columns
  624.  
  625.     size_df.plot(kind = 'bar', colors = ['k','b','c','g'], title = 'Size')
  626.     flee_df.plot(kind = 'bar', colors = ['k','b','c','g'], title = 'Flee')
  627.     moves_df.plot(kind = 'bar', colors = ['k','b','c','g'], title = 'Moves')
  628.  
  629. plot_all(df_dict)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement