Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class blob:
- ## Добавить атрибут имя))0
- def __init__(self, moves, size, flee, lastmove, food, x, y):
- global count
- self.id = count
- self.moves = moves
- self.size = size
- self.flee = flee
- self.lastmove = lastmove
- self.mademoves = 0
- self.food = food
- self.x = x ## Начальную координату рандомом зададим есчто, проверить, что в этом месте ничего нет
- self.y = y
- def show_id(self):
- return self.id
- def addfood(self):
- self.food+=1 ## Когда покушал
- def reset_mm(self):
- self.mademoves = 0
- def addmove(self):
- self.mademoves += 1 ## Сделанные за день движения
- def setlastmove(self, move):
- self.lastmove = int(move) ## Сделанные за день движения
- def blobx(self):
- return self.x ## blobx и bloby возвращают координаты
- def bloby(self):
- return self.y
- def changex(self, x): ## Изменить координаты
- self.x = x
- def changey(self, y):
- self.y = y
- def moves(self):
- return self.moves
- def size(self):
- return self.size
- def flee(self):
- return self.flee
- def lastmove(self):
- return self.lastmove
- def mademoves(self):
- return self.mademoves
- def food(self):
- return self.food
- def movecost(self):
- return int(1) #round(self.size / 0.2 - 5) ## Вот это тоже со скобочками
- def energy(self):
- if self.moves <= 10: ## starting moves = 10
- consume = 0.8
- else:
- consume = self.moves // 20 ### ПОТОМ УБРАТЬ
- energy = self.food - consume
- return energy
- ## Добавить больше на 20%
- def __gt__(self, other): ## greater than
- return self.size > other.size
- def __lt__(self, other): ## less than
- return self.size < other.size
- def __ge__(self, other): ## greater or equal
- return self.size >= other.size
- def __le__(self, other): ## less or equal
- return self.size <= other.size
- def __eq__(self, other): ## equal
- return self.size == other.size
- def __ne__(self, other):
- return self.size != other.size
- def __str__(self):
- return 'A'
- def replicate(self):
- global community, escapists, count
- baby_flee = self.flee
- baby_moves = self.moves
- baby_size = self.size
- chance = 0.5 # can be adjusted later; шанс мутации при перерождении
- if random() < chance:
- temp = randint(1, 2)
- if temp == 1:
- baby_moves = self.moves + 1
- elif (temp == 2) and (self.moves > 1): ## мувз должны быть больше 1
- baby_moves = self.moves + 1 ## Есть шанс стать хуже или лучше бати по подвижности
- if random() < chance:
- temp = randint(1, 2)
- if temp == 1:
- baby_size = self.size + 0.1
- elif (temp == 2) and (self.size > 0.1):
- baby_size = self.size - 0.1
- if random() < chance:
- temp = randint(1, 2)
- if temp == 1:
- baby_flee = self.flee + 0.1
- elif (temp == 2) and (self.flee > 0.1):
- baby_flee = self.flee - 0.1
- count += 1
- baby_blob = blob(baby_moves, baby_size, baby_flee, 0, 0, 1, 1)
- community.add(baby_blob)
- escapists.append(baby_blob)
- def test_blob(self):
- temp = self.moves - self.movecost() - self.mademoves
- if temp > 0:
- return True
- else:
- return False
- class food:
- def __init__(self):
- self.name = 'F'
- def __repr__(self):
- return self.name
- def __str__(self):
- return self.name
- from random import randint, random
- from math import log
- #escapists = [] # FUCKIN AWOLS WHAT THE FUCK
- class field:
- def __init__(self, side):
- self.field = [[0 for x in range(side)] for y in range(side)]
- self.side = side
- for i in range(side):
- for j in range(side):
- if i == 0 or j == 0 or i == side-1 or j == side-1:
- self.field[i][j] = 'x'
- def clear(self, y, x):
- self.field[y][x] = 0
- def new_print(self):
- for i in range(self.side):
- for j in range(self.side):
- print(str(self.field[i][j]), end = ' ')
- print()
- def spawn_food(self, foodnumber):
- count = foodnumber
- erf = foodnumber * 3 ## Это нереальный костыль, но пока пусть будет
- while (count > 0) and (erf > 0):
- erf -= 1
- x = randint(1, self.side-2)
- y = randint(1, self.side-2)
- if type(self.field[x][y]) == int:
- if self.field[x][y] == 0:
- self.field[x][y] = food()
- count -= 1
- def clear_food(self):
- for i in range(1, self.side-1):
- for j in range(1, self.side-1):
- if type(self.field[i][j]) == food:
- self.field[i][j] = 0
- def isfood(self,y,x):
- return type(self.field[y][x]) == food
- def isblob(self,y,x):
- return type(self.field[y][x]) == blob
- def spawn_escapists(self):
- global escapists
- #print(escapists)
- count = len(escapists)
- erf = count * 5 ## Костыль
- while (count > 0) and (erf > 0):
- erf -= 1
- x = randint(1, self.side-1)
- y = randint(1, self.side-1)
- if type(self.field[x][y]) == int:
- my_blob = escapists.pop()
- my_blob.changex(y)
- my_blob.changey(x)
- self.field[x][y] = my_blob ## Мы спауним на пустые места эскейпистов
- count -= 1
- #print(escapists)
- def observe(self, my_blob):
- global escapists
- x = my_blob.blobx()
- y = my_blob.bloby()
- for i,j in [(1,0),(-1,0),(0,1),(0,-1)]:
- if self.isfood(y+j,x+i):
- my_blob.addfood()
- self.field[y+j][x+i] = 0 ## Обнулили где сожрали
- elif self.isblob(y+j,x+i):
- bad_blob = self.field[y+j][x+i]
- if my_blob < bad_blob:
- chance = 0.1 * (log(my_blob.flee) + 1)
- destiny = random()
- if destiny < chance: ## Мы сбежали
- escapists.append(my_blob)
- self.field[y][x] = 0
- my_blob.reset_mm()
- else: ## Нас съели
- self.field[y][x] = 0
- self.field[y+j][x+i].addfood() ## bad_blob.addfood()
- #Из массива блобов надо удалить съеденного
- elif my_blob > bad_blob:
- chance = 0.1 * (log(bad_blob.flee) + 1)
- destiny = random()
- if destiny < chance: ## От нас сбежали
- escapists.append(bad_blob)
- self.field[y+j][x+i] = 0
- bad_blob.reset_mm()
- else: ## Мы съели
- self.field[y+j][x+i] = 0
- my_blob.addfood()
- #Из массива блобов надо удалить съеденного
- def move(self, my_blob, n):
- ## На рекурсии удобно, просто будем запускать с n=4
- if n == 0:
- pass #че если 0, то мы заканчиваем, типа мы чекаем 4 раза, чтобы матожидание было норм
- else:
- direction = randint(1,4)
- x = my_blob.blobx()
- y = my_blob.bloby()
- if (direction == 1) and (my_blob.lastmove != 3) and (isinstance(self.field[y-1][x], int)):
- self.up(my_blob)
- elif (direction == 2) and (my_blob.lastmove != 4) and (isinstance(self.field[y][x+1], int)):
- self.right(my_blob)
- elif (direction == 3) and (my_blob.lastmove != 1) and (isinstance(self.field[y+1][x], int)):
- self.down(my_blob)
- elif (direction == 4) and (my_blob.lastmove != 2) and (isinstance(self.field[y][x-1], int)):
- self.left(my_blob)
- else:
- self.move(my_blob, n-1)
- def up(self, my_blob):
- x = my_blob.blobx()
- y = my_blob.bloby()
- my_blob.addmove()
- self.field[y-1][x] = my_blob
- self.field[y][x] = 0
- my_blob.changey(y-1)
- my_blob.setlastmove(1)
- def right(self, my_blob):
- x = my_blob.blobx()
- y = my_blob.bloby()
- my_blob.addmove()
- self.field[y][x+1] = my_blob
- self.field[y][x] = 0
- my_blob.changex(x+1)
- my_blob.setlastmove(2)
- def down(self, my_blob):
- x = my_blob.blobx()
- y = my_blob.bloby()
- my_blob.addmove()
- self.field[y+1][x] = my_blob
- self.field[y][x] = 0
- my_blob.changey(y+1)
- my_blob.setlastmove(3)
- def left(self, my_blob):
- x = my_blob.blobx()
- y = my_blob.bloby()
- my_blob.addmove()
- self.field[y][x-1] = my_blob
- self.field[y][x] = 0
- my_blob.changex(x-1)
- my_blob.setlastmove(4)
- import pandas as pd
- class bloblist:
- def __init__(self):
- ## Лист и длина листа
- self.enlist = []
- self.population = 0
- def population(self):
- return self.population
- def enlist(self):
- return self.enlist
- def add(self, unit):
- ## Добавить очередное хуило
- self.enlist.append(unit)
- self.population+=1
- #print(self.population)
- def choose(self, index):
- ## Обращение по индексу
- res = self.enlist[index]
- return res
- def all_moves(self):
- res = []
- for i in range(self.population):
- temp = self.choose(i).moves
- res.append(temp)
- res.sort()
- return res
- def all_size(self):
- res = []
- for i in range(self.population):
- temp = self.choose(i).size
- res.append(temp)
- res.sort()
- return res
- def all_flee(self):
- res = []
- for i in range(self.population):
- temp = self.choose(i).flee
- res.append(temp)
- res.sort()
- return res
- def delete(self, my_blob):
- if my_blob in self.enlist:
- del self.enlist[self.enlist.index(my_blob)]
- self.population -= 1
- ## Тут надо вписать смерть блобчика
- def test_all(self):
- res = False
- for i in self.enlist:
- if i.test_blob() == True:
- res = True
- break
- return res
- def __str__(self):
- return str(self.enlist)
- def show_stats(self):
- local_count = 0
- columns = ['id','size', 'flee', 'moves']
- df = pd.DataFrame(columns = columns)
- for i in self.enlist:
- df.loc[local_count] = [int(i.show_id()),i.size, i.flee, i.moves]
- local_count+=1
- df['id'] = df['id'].astype(int).round(decimals = 0)
- return df
- community = bloblist() # global
- escapists = []
- count = 0
- def end(my_field):
- global community, escapists
- ## Это будет массив блобов всех
- for i in community.enlist:
- E = i.energy()
- x = i.blobx()
- y = i.bloby()
- #print('Energy is:' + str(E))
- if E < 0: ## Короче хуйня надо подобрать параметры энергии
- my_field.clear(y,x)
- community.delete(i)
- elif E > 1:
- i.replicate()
- i.reset_mm()
- # Константы и переменные
- DAYS = 7 # Количество дней симуляции
- SIDE = 20 # Сторона поля
- FOODNUMBER = 50 # Количество хавки на полу
- my_field = field(SIDE)
- lil_pump = blob(10, 1, 1, 0, 1, 1, 1) # Маленький насос спавнится в верхнем левом углу
- community.add(lil_pump) # Маленький насос становится членом коммуны
- escapists.append(lil_pump) # Маленький насос сбежал вот блин
- daycount = 0
- df_dict = {}
- for day in range(DAYS):
- if community.population == 0:
- break
- my_field.clear_food()
- my_field.spawn_escapists()
- my_field.spawn_food(FOODNUMBER)
- while community.test_all():
- for unit in community.enlist:
- my_field.observe(unit)
- if unit.test_blob(): ## Вот тут хуйня какая-то го чекать
- my_field.move(unit, 4)
- community.show_stats().head()
- my_field.new_print()
- #print('{}'.format(''))
- print(community)
- end(my_field)
- daycount+=1
- df_dict[daycount] = community.show_stats()
- import matplotlib.pyplot as plt
- def plot_all(df_dict):
- size_dict = {}
- flee_dict = {}
- moves_dict = {}
- for i in df_dict:
- size_dict[i] = df_dict[i].copy()
- flee_dict[i] = df_dict[i].copy()
- moves_dict[i] = df_dict[i].copy()
- ############# Для size ################
- for i in size_dict:
- size_dict[i].drop('flee', axis = 1, inplace = True)
- size_dict[i].drop('moves', axis = 1, inplace = True)
- grouped_size_dict = {}
- size_count = 1
- for k in size_dict:
- grouped_size_dict[size_count] = size_dict[k].groupby('size').count()
- grouped_size_dict[size_count].reset_index(inplace=True)
- size_count+=1
- a = []
- for k in grouped_size_dict:
- b = grouped_size_dict[k]['size']
- for i in range(len(b)):
- a.append(b[i])
- unique_a = []
- for i in a:
- if i not in unique_a:
- unique_a.append(i)
- size_df_dict = {}
- for k in grouped_size_dict:
- bad_dict = pd.DataFrame.to_dict(grouped_size_dict[k])
- my_list = [int(0) for i in range(len(unique_a))]
- for i in bad_dict['size']:
- if bad_dict['size'][i] in unique_a:
- index = unique_a.index(bad_dict['size'][i])
- my_list[index] = bad_dict['id'][i]
- size_df_dict[k] = my_list
- size_df = pd.DataFrame.from_dict(size_df_dict, orient = 'index')
- columns = unique_a
- size_df.columns = columns
- ############# Для flee ################
- for i in flee_dict:
- flee_dict[i].drop('size', axis = 1, inplace = True)
- flee_dict[i].drop('moves', axis = 1, inplace = True)
- grouped_flee_dict = {}
- flee_count = 1
- for k in flee_dict:
- grouped_flee_dict[flee_count] = flee_dict[k].groupby('flee').count()
- grouped_flee_dict[flee_count].reset_index(inplace=True)
- flee_count+=1
- a = []
- for k in grouped_flee_dict:
- b = grouped_flee_dict[k]['flee']
- for i in range(len(b)):
- a.append(b[i])
- unique_a = []
- for i in a:
- if i not in unique_a:
- unique_a.append(i)
- flee_df_dict = {}
- for k in grouped_flee_dict:
- bad_dict = pd.DataFrame.to_dict(grouped_flee_dict[k])
- my_list = [int(0) for i in range(len(unique_a))]
- for i in bad_dict['flee']:
- if bad_dict['flee'][i] in unique_a:
- index = unique_a.index(bad_dict['flee'][i])
- my_list[index] = bad_dict['id'][i]
- flee_df_dict[k] = my_list
- flee_df = pd.DataFrame.from_dict(flee_df_dict, orient = 'index')
- columns = unique_a
- flee_df.columns = columns
- ############# Для moves ################
- for i in moves_dict:
- moves_dict[i].drop('size', axis = 1, inplace = True)
- moves_dict[i].drop('flee', axis = 1, inplace = True)
- grouped_moves_dict = {}
- moves_count = 1
- for k in moves_dict:
- grouped_moves_dict[moves_count] = moves_dict[k].groupby('moves').count()
- grouped_moves_dict[moves_count].reset_index(inplace=True)
- moves_count+=1
- a = []
- for k in grouped_moves_dict:
- b = grouped_moves_dict[k]['moves']
- for i in range(len(b)):
- a.append(b[i])
- unique_a = []
- for i in a:
- if i not in unique_a:
- unique_a.append(i)
- moves_df_dict = {}
- for k in grouped_moves_dict:
- bad_dict = pd.DataFrame.to_dict(grouped_moves_dict[k])
- my_list = [int(0) for i in range(len(unique_a))]
- for i in bad_dict['moves']:
- if bad_dict['moves'][i] in unique_a:
- index = unique_a.index(bad_dict['moves'][i])
- my_list[index] = bad_dict['id'][i]
- moves_df_dict[k] = my_list
- moves_df = pd.DataFrame.from_dict(moves_df_dict, orient = 'index')
- columns = unique_a
- moves_df.columns = columns
- size_df.plot(kind = 'bar', colors = ['k','b','c','g'], title = 'Size')
- flee_df.plot(kind = 'bar', colors = ['k','b','c','g'], title = 'Flee')
- moves_df.plot(kind = 'bar', colors = ['k','b','c','g'], title = 'Moves')
- plot_all(df_dict)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement