Week 13: November 26 and 27th - ngetachew/Portfolio GitHub Wiki

On Monday, I spent the whole day working on the goTowards() function in the Beartest.py file. My first idea was to have the bear move towards the closest tile to the player after each step. This proved to be a lot harder than I thought because the way the grid was made with a single, linear index for each tile rather than a 2-d array separated by rows and columns(x and y coordinates). I thought this meant that I had to convert everything to x,y coordinates, but I found that I only needed the row(y). We had a 13 x 9 grid, so I calculated the row using a simple formula:

player_row = (player_loc-1)//13

bear_row = (bear_loc-1)//13

Where bear_loc and player_loc are the indices of the corresponding grid element. Note that the '//' operator floor divides two integers. At this point I realized that the bear could only move in 8 possible locations, all of which are the adjacent tiles. The tiles that were directly to its left and right were easy to code, but the other locations were harder to code. I had to find the adjacent tiles that weren't occupied or off of the grid. The file was separate from display.py, so I wasn't able to check for obstacles, but I was able to filter out invalid grid positions with a list comprehension:

transformations = (bear_loc-12,bear_loc-13,bear_loc-14,bear_loc+12,bear_loc+13,bear_loc+14)

transformations = tuple((x for x in transformations if (x > 1 and x < 91)))

After the only thing left to do was check which was closest, as shown below with the rest if the code:

pic

At the end of the day, while the logic seemed fine, the algorithm was acting unreliably during testing. This took me into Tuesday, when I found that I did everything wrong. One of my peers suggested that I instead use a module called networkx. This module utilizes special graphs that consist of nodes, which are essentially points, that are connected by edges to perform certain tasks. I was able to take advantage of this by assigning a node to every tile, connect them all with edges and use the module's built-in path-finding function to find the shortest possible path. The challenge in this is creating a node for every tile, but the deleting the nodes that are assigned to obstacles. What's especially annoying is that the main array that contains all the grid locations is ordered from last to first, so I have to change my code to follow this. The bulk of the programming is in the reset() function as shown below(there are two of us working on display.py, so there was no way for me to get my code on Github, which is why I have to use an image from my phone):

pic2 pic3