Principle of Computing (Python) Learning notes (5) BFS searching + Zombie Apocalypse

Source: Internet
Author: User

1 Generators
Generator and list comprehension are very similar
generators is a kind of iterator that is defined like functions.

http://www.codeskulptor.org/#examples_generators. py

Https://wiki.python.org/moin/Generators

The function body of generater functions must write yield, be able to write or not write return.

generators functions allow you to declare a function the behaves like an iterator, i.e. it can be used in a for loop.
Each time the next (), method was applied to the resulting generator, and the code is run until the next yield expression, a nd the yield expression ' s value is returned by-method call. Thus, the creation of the generator does not wait for all of their elements to be generator, and the generator could even re Present an infinite number of elements.

# a list comprehensionprint ' Max in list: ', max ([num * 2-3 for NUM in range (7)]) # a generator expressionprint ' Max in GE N: ", max (num * 2-3 for NUM in range (7)) # A Generator functiondef Genfunc (limit):    num = 0 while    num < limit:
   yield num  #generator function is used in conjunction with iteration. Yield indicates that the value has been generated. Put it on one side. Now the loop continues, and so the loop ends, and then comes back to the value generated by yield before processing.        num = num + 1print genfunc (7) # iteration using a generator functionprint "iterate over generator:" For number in Genfu NC (7):    Print number


2 Stack and queue

Stack http://www.codeskulptor.org/#user36_ZHLkI0d7kb_2. PY

Queue http://www.codeskulptor.org/#user35_AtoP6ttM6w_0. PY




3 Inheritance
http://www.codeskulptor.org/#examples_inheritance. PY
http://www.codeskulptor.org/#examples_inheritance2. PY


4 Grid Collision
http://www.codeskulptor.org/#poc_physics_quadratic. PY
Https://class.coursera.org/principlescomputing-001/wiki/view?

Page=fun_growth

Https://class.coursera.org/principlescomputing-001/wiki/view?

Page=grids



5 Implementation of the grid class
http://www.codeskulptor.org/#poc_grid. PY 
Notice the conversion method of "Def get_index (self, point, cell_size):" To convert the actual screen position to index

6 Conway ' s game of Life simulation
Game of Life Brief introductionHttp://en.wikipedia.org/wiki/Conway ' S_game_of_life
Game of life exercises for grid operationhttp://www.codeskulptor.org/#poc_gol_student. PY

7 BFS
BFS Animation Wild Fire is not the spring breeze and born
http://www.codeskulptor.org/#poc_wildfire_student. PY
http://www.codeskulptor.org/#poc_wildfire_gui. PY
http://www.codeskulptor.org/#poc_grid. PY
BFS PrincipleHttps://class.coursera.org/principlescomputing-001/wiki/view?page=bfs

8 Purpose of the grid uses bucket sorting for string sorting
https://class.coursera.org/principlescomputing-001/wiki/view?page=strings
http://www.codeskulptor.org/#poc_string_sort. PY
# Generate 26-letter list
list= [Chr (Ord ("a") + Char_num) for Char_num in range (+)]
Print List


9 stack and queue
The teacher realizes the queuehttp://www.codeskulptor.org/#poc_queue. PY
your own implementation of the stackhttp://www.codeskulptor.org/#user36_ZHLkI0d7kb_2. PY

Ten Zombie Apocalypse
http://www.codeskulptor.org/#poc_zombie_template. PY
1) Passable cells in the grid correspond to EMPTY cells while full cells is impassable
2) However, several humans and zombies may inhabit the same grid cell.

3) Note that the for all in List1 can only read the elements in the LIST1, and cannot alter the elements in the list1, assuming you want to change them. The subscript operation to use. Such as

4) The principle of zombie and human movement is this.
First, calculate a distance_grid for zombie. Each cell in this distance_grid expresses the distance from the current cell to the nearest zombie, and then, Move_human, selects a distance_ from the cell around human. The cell with the largest corresponding value of the grid, so that the human moves to a human the safest point.

Similarly, a distance_grid is computed for human. each cell in the cells expresses the distance from the current cell to the nearest human, and next, Move_zombie. From the cell around zombie, select a cell with the lowest corresponding value Distance_grid, so that human moves to a point closest to human.

5) The topic made a very much simplification.

For example, when calculating Distance_grid, both zombie and human assume that the current cell has only 4 adjacent cells. Instead of 8.

When zombie catch up with human, only the grid changes the color, assuming the next step continues human Move,human or alive.

For IDX in range (len (list1)):     


My homework.

"" "Student portion of Zombie Apocalypse mini-project" "" Import randomimport poc_gridimport poc_queueimport poc_zombie_  gui# Global Constantsempty = 0 full = 1four_way = 0eight_way = 1OBSTACLE = "obstacle" HUMAN = "HUMAN" ZOMBIE = "ZOMBIE" class Zombie (Poc_grid. Grid): "" "Class for simulating zombie pursuit of human in grid with obstacles" "Def __init__ (self, grid_ Height, grid_width, obstacle_list = none, Zombie_list = none, Human_list = none): "" "creat e A simulation of given size with given obstacles, humans, and Zombies "" "Poc_grid.                Grid.__init__ (self, grid_height, grid_width) if obstacle_list! = None:for cell in obstacle_list:        Self.set_full (Cell[0], cell[1]) if zombie_list! = None:self._zombie_list = List (zombie_list)           Else:self._zombie_list = [] if human_list! = None:self._human_list = List (human_list) Else:seLf._human_list = [] def clear (self): "", Set cells in obstacle grid to is empty Reset Zomb IE and human lists to be empty "" "Poc_grid.        Grid.clear (self) self._zombie_list = [] Self._human_list = [] def add_zombie (self, Row, col): "" "Add Zombie to the Zombie list" "" Self._zombie_list.append ((Row,col)) def              Num_zombies (self): "" "return Number of Zombies" "" Return Len (self._zombie_list)        Def Zombies (self): "", Generator that yields, the zombies in the order they were added.         "" "num = 0 while num < self.num_zombies (): yield self._zombie_list[num] num + = 1 return def add_human (self, Row, col): "" "Add human to the human list" "Self._huma N_list.append ((row,col)) def Num_humans (self): "" "Return number of HUmans "" "Return Len (self._human_list) def humans (self):" "" Generator that yields the        Humans in the order they were added.        "" "num = 0 while Num<self.num_humans (): yield self._human_list[num] num + = 1         return def compute_distance_field (self, Entity_type): "" "Function computes a 2D distance field        Distance at member of Entity_queue are zero shortest paths avoid obstacles and use distance_type distances "" "Visited = Poc_grid.  Grid (Self._grid_height, self._grid_width) Distance_field = [[Self._grid_width * self._grid_height for Dummy_col in               Range (Self._grid_width)] for Dummy_row in range (self._grid_height)] if Entity_type = = HUMAN: Boundary = Poc_queue.                Queue () for each in Self._human_list:visited.set_full (Each[0],each[1]) Distance_field[each[0]][eaCH[1]] = 0 boundary.enqueue (each) while Len (boundary) >0:cur_cell = Boundary.d Equeue () four_neighbors = Poc_grid. Grid.four_neighbors (Self,cur_cell[0],cur_cell[1]) for Each_neighbor in four_neighbors:i F Visited.is_empty (Each_neighbor[0],each_neighbor[1]) and Poc_grid. Grid.is_empty (self, each_neighbor[0], each_neighbor[1]): Visited.set_full (Each_neighbor[0],each_ne IGHBOR[1]) If distance_field[cur_cell[0]][cur_cell[1]]+1 < distance_field[each_neighbor[0]][EAC H_NEIGHBOR[1]]: distance_field[each_neighbor[0]][each_neighbor[1]] = distance_field[cur_cell[0 ]][cur_cell[1]]+1 boundary.enqueue (each_neighbor) elif Entity_type = Zombi E:boundary = Poc_queue. Queue () for each in Self._zombie_list:visited.set_full (Each[0], each[1]) distance_field[each[0]][each[1]] = 0 boundary.enqueue (each) while Len (b oundary) >0:cur_cell = Boundary.dequeue () four_neighbors = Poc_grid.                    Grid.four_neighbors (Self,cur_cell[0],cur_cell[1]) for Each_neighbor in four_neighbors: If Visited.is_empty (Each_neighbor[0],each_neighbor[1]) and Poc_grid. Grid.is_empty (self, each_neighbor[0], each_neighbor[1]): Visited.set_full (Each_neighbor[0],each_nei GHBOR[1]) if distance_field[cur_cell[0]][cur_cell[1]]+1 < Distance_field [Each_neighbor[0]] [Each_neighbor[1]]: distance_field[each_neighbor[0]][each_neighbor[1]] = Distance_field[cur_c Ell[0]][cur_cell[1]]+1 Boundary.enqueue (Each_neighbor) return Distance_fie LD def Move_humanS (self, Zombie_distance): "" "Function that moves humans away from zombies, diagonal moves is Allowe D "" for the IDX in range (len (self._human_list)): Eight_neighbor_human = Poc_grid. Grid.eight_neighbors (self, self._human_list[idx][0],self._human_list[idx][1]) max_distance = Zombie_distanc E[SELF._HUMAN_LIST[IDX][0]][SELF._HUMAN_LIST[IDX][1]] Max_pos = (self._human_list[idx][0],self._human_list[idx][ 1]) for Eight_neighbor in Eight_neighbor_human:if Zombie_distance[eight_neighbor[0]][eight_nei                    Ghbor[1]]> max_distance:max_distance = zombie_distance[eight_neighbor[0]][eight_neighbor[1]]        Max_pos = (eight_neighbor[0],eight_neighbor[1]) self._human_list[idx]= (max_pos[0],max_pos[1])        def move_zombies (self, human_distance): "" "Function that moves zombies towards humans, no diagonal moves is allowed "" "for IDX in range (len (self._zombie_list)): Four_neighbor_zombie = Poc_grid. Grid.four_neighbors (self, self._zombie_list[idx][0],self._zombie_list[idx][1]) min_distance = Human_distanc E[SELF._ZOMBIE_LIST[IDX][0]][SELF._ZOMBIE_LIST[IDX][1]] Min_pos = (self._zombie_list[idx][0],self._zombie_list[i DX][1]) for Four_neighbor in Four_neighbor_zombie:if Human_distance[four_neighbor[0]][four_nei                    ghbor[1]]< min_distance:min_distance = human_distance[four_neighbor[0]][four_neighbor[1]]  Min_pos = (four_neighbor[0],four_neighbor[1]) self._zombie_list[idx]= (min_pos[0],min_pos[1]) # Start up GUI for Simulation-you would need to write some code above# before this would work without Errors#test_zombie = Zombie (3 , 3, [], [], [(2, 2)]) #print Test_zombie.compute_distance_field (' Human ') Poc_zombie_gui.run_gui (Zombie (20, 15))



Principle of Computing (Python) Learning notes (5) BFS searching + Zombie Apocalypse

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.