Advertisement
Guest User

HW 13-14

a guest
Mar 21st, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.62 KB | None | 0 0
  1. # Copyright 2017, 2013, 2011 Pearson Education, Inc., W.F. Punch & R.J.Enbody
  2. """Predator-Prey Simulation
  3. four classes are defined: animal, predator, prey, and island
  4. where island is where the simulation is taking place,
  5. i.e. where the predator and prey interact (live).
  6. A list of predators and prey are instantiated, and
  7. then their breeding, eating, and dying are simulted.
  8. """
  9. import random
  10. import time
  11. import pylab
  12.  
  13. class Island (object):
  14. """Island
  15. n X n grid where zero value indicates not occupied."""
  16. def __init__(self, n, prey_count=0, predator_count=0):
  17. '''Initialize grid to all 0's, then fill with animals
  18. '''
  19. # print(n,prey_count,predator_count)
  20. self.grid_size = n
  21. self.grid = []
  22. for i in range(n):
  23. row = [0]*n # row is a list of n zeros
  24. self.grid.append(row)
  25. self.init_animals(prey_count,predator_count)
  26.  
  27. def init_animals(self,prey_count, predator_count):
  28. ''' Put some initial animals on the island
  29. '''
  30. count = 0
  31. # while loop continues until prey_count unoccupied positions are found
  32. while count < prey_count:
  33. x = random.randint(0,self.grid_size-1)
  34. y = random.randint(0,self.grid_size-1)
  35. if not self.animal(x,y):
  36. new_prey=Prey(island=self,x=x,y=y)
  37. count += 1
  38. self.register(new_prey)
  39. count = 0
  40. # same while loop but for predator_count
  41. while count < predator_count:
  42. x = random.randint(0,self.grid_size-1)
  43. y = random.randint(0,self.grid_size-1)
  44. if not self.animal(x,y):
  45. new_predator=Predator(island=self,x=x,y=y)
  46. count += 1
  47. self.register(new_predator)
  48.  
  49. def clear_all_moved_flags(self):
  50. ''' Animals have a moved flag to indicated they moved this turn.
  51. Clear that so we can do the next turn
  52. '''
  53. for x in range(self.grid_size):
  54. for y in range(self.grid_size):
  55. if self.grid[x][y]:
  56. self.grid[x][y].clear_moved_flag()
  57.  
  58. def size(self):
  59. '''Return size of the island: one dimension.
  60. '''
  61. return self.grid_size
  62.  
  63. def register(self,animal):
  64. '''Register animal with island, i.e. put it at the
  65. animal's coordinates
  66. '''
  67. x = animal.x
  68. y = animal.y
  69. self.grid[x][y] = animal
  70.  
  71. def remove(self,animal):
  72. '''Remove animal from island.'''
  73. x = animal.x
  74. y = animal.y
  75. self.grid[x][y] = 0
  76.  
  77. def animal(self,x,y):
  78. '''Return animal at location (x,y)'''
  79. if 0 <= x < self.grid_size and 0 <= y < self.grid_size:
  80. return self.grid[x][y]
  81. else:
  82. return -1 # outside island boundary
  83.  
  84. def __str__(self):
  85. '''String representation for printing.
  86. (0,0) will be in the lower left corner.
  87. '''
  88. s = ""
  89. for j in range(self.grid_size-1,-1,-1): # print row size-1 first
  90. for i in range(self.grid_size): # each row starts at 0
  91. if not self.grid[i][j]:
  92. # print a '.' for an empty space
  93. s+= "{:<2s}".format('.' + " ")
  94. else:
  95. s+= "{:<2s}".format((str(self.grid[i][j])) + " ")
  96. s+="\n"
  97. return s
  98.  
  99. def count_prey(self):
  100. ''' count all the prey on the island'''
  101. count = 0
  102. for x in range(self.grid_size):
  103. for y in range(self.grid_size):
  104. animal = self.animal(x,y)
  105. if animal:
  106. if isinstance(animal,Prey):
  107. count+=1
  108. return count
  109.  
  110. def count_predators(self):
  111. ''' count all the predators on the island'''
  112. count = 0
  113. for x in range(self.grid_size):
  114. for y in range(self.grid_size):
  115. animal = self.animal(x,y)
  116. if animal:
  117. if isinstance(animal,Predator):
  118. count+=1
  119. return count
  120.  
  121. class Animal(object):
  122. def __init__(self, island, x=0, y=0, s="A"):
  123. '''Initialize the animal's and their positions
  124. '''
  125. self.island = island
  126. self.name = s
  127. self.x = x
  128. self.y = y
  129. self.moved=False
  130.  
  131. def position(self):
  132. '''Return coordinates of current position.
  133. '''
  134. return self.x, self.y
  135.  
  136. def __str__(self):
  137. return self.name
  138.  
  139. def check_grid(self,type_looking_for=int):
  140. ''' Look in the 8 directions from the animal's location
  141. and return the first location that presently has an object
  142. of the specified type. Return 0 if no such location exists
  143. '''
  144. # neighbor offsets
  145. offset = [(-1,1),(0,1),(1,1),(-1,0),(1,0),(-1,-1),(0,-1),(1,-1)]
  146. result = 0
  147. for i in range(len(offset)):
  148. x = self.x + offset[i][0] # neighboring coordinates
  149. y = self.y + offset[i][1]
  150. if not 0 <= x < self.island.size() or \
  151. not 0 <= y < self.island.size():
  152. continue
  153. if type(self.island.animal(x,y))==type_looking_for:
  154. result=(x,y)
  155. break
  156. return result
  157.  
  158. def move(self):
  159. '''Move to an open, neighboring position '''
  160. if not self.moved:
  161. location = self.check_grid(int)
  162. if location:
  163. # print('Move, {}, from {},{} to {},{}'.format( \
  164. # type(self),self.x,self.y,location[0],location[1]))
  165. self.island.remove(self) # remove from current spot
  166. self.x = location[0] # new coordinates
  167. self.y = location[1]
  168. self.island.register(self) # register new coordinates
  169. self.moved=True
  170. def breed(self):
  171. ''' Breed a new Animal.If there is room in one of the 8 locations
  172. place the new Prey there. Otherwise you have to wait.
  173. '''
  174. if self.breed_clock <= 0:
  175. location = self.check_grid(int)
  176. if location:
  177. self.breed_clock = self.breed_time
  178. # print('Breeding Prey {},{}'.format(self.x,self.y))
  179. the_class = self.__class__
  180. new_animal = the_class(self.island,x=location[0],y=location[1])
  181. self.island.register(new_animal)
  182.  
  183. def clear_moved_flag(self):
  184. self.moved=False
  185.  
  186. class Prey(Animal):
  187. def __init__(self, island, x=0,y=0,s="O"):
  188. Animal.__init__(self,island,x,y,s)
  189. self.breed_clock = self.breed_time
  190. # print('Init Prey {},{}, breed:{}'.format(self.x, self.y,self.breed_clock))
  191.  
  192. def clock_tick(self):
  193. '''Prey only updates its local breed clock
  194. '''
  195. self.breed_clock -= 1
  196. # print('Tick Prey {},{}, breed:{}'.format(self.x,self.y,self.breed_clock))
  197.  
  198. class Predator(Animal):
  199. def __init__(self, island, x=0,y=0,s="X"):
  200. Animal.__init__(self,island,x,y,s)
  201. self.starve_clock = self.starve_time
  202. self.breed_clock = self.breed_time
  203. # print('Init Predator {},{}, starve:{}, breed:{}'.format( \
  204. # self.x,self.y,self.starve_clock,self.breed_clock))
  205.  
  206. def clock_tick(self):
  207. ''' Predator updates both breeding and starving
  208. '''
  209. self.breed_clock -= 1
  210. self.starve_clock -= 1
  211. # print('Tick, Predator at {},{} starve:{}, breed:{}'.format( \
  212. # self.x,self.y,self.starve_clock,self.breed_clock))
  213. if self.starve_clock <= 0:
  214. # print('Death, Predator at {},{}'.format(self.x,self.y))
  215. self.island.remove(self)
  216.  
  217. def eat(self):
  218. ''' Predator looks for one of the 8 locations with Prey. If found
  219. moves to that location, updates the starve clock, removes the Prey
  220. '''
  221. if not self.moved:
  222. location = self.check_grid(Prey)
  223. if location:
  224. # print('Eating: pred at {},{}, prey at {},{}'.format( \
  225. # self.x,self.y,location[0],location[1]))
  226. self.island.remove(self.island.animal(location[0],location[1]))
  227. self.island.remove(self)
  228. self.x=location[0]
  229. self.y=location[1]
  230. self.island.register(self)
  231. self.starve_clock=self.starve_time
  232. self.moved=True
  233.  
  234. ###########################################
  235. def main(predator_breed_time=6, predator_starve_time=3, initial_predators=10, prey_breed_time=3, initial_prey=50, \
  236. size=10, ticks=300):
  237. ''' main simulation. Sets defaults, runs event loop, plots at the end
  238. '''
  239. # initialization values
  240. Predator.breed_time = predator_breed_time
  241. Predator.starve_time = predator_starve_time
  242. Prey.breed_time = prey_breed_time
  243.  
  244. # for graphing
  245. predator_list=[]
  246. prey_list=[]
  247.  
  248. # make an island
  249. isle = Island(size,initial_prey, initial_predators)
  250. print(isle)
  251.  
  252. # event loop.
  253. # For all the ticks, for every x,y location.
  254. # If there is an animal there, try eat, move, breed and clock_tick
  255. for i in range(ticks):
  256. # important to clear all the moved flags!
  257. isle.clear_all_moved_flags()
  258. for x in range(size):
  259. for y in range(size):
  260. animal = isle.animal(x,y)
  261. if animal:
  262. if isinstance(animal,Predator):
  263. animal.eat()
  264. animal.move()
  265. animal.breed()
  266. animal.clock_tick()
  267.  
  268. # record info for display, plotting
  269. prey_count = isle.count_prey()
  270. predator_count = isle.count_predators()
  271. if prey_count == 0:
  272. print('Lost the Prey population. Quiting.')
  273. break
  274. if predator_count == 0:
  275. print('Lost the Predator population. Quitting.')
  276. break
  277. prey_list.append(prey_count)
  278. predator_list.append(predator_count)
  279. # print out every 10th cycle, see what's going on
  280. if not i%10:
  281. print(prey_count, predator_count)
  282. # print the island, hold at the end of each cycle to get a look
  283. # print('*'*20)
  284. # print(isle)
  285. # ans = input("Return to continue")
  286. pylab.plot(range(0,ticks), predator_list, label="Predators")
  287. pylab.plot(range(0,ticks), prey_list, label="Prey")
  288. pylab.legend(loc="best", shadow=True)
  289. pylab.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement