Separating an unknown amount of coordinates in a list into seperate coordinates - python

I am trying to create a program that will let a simulated robot move around a space and go around obstacles in the most efficient way possible. I have a list of obstacles hard coded into the code and I have to separate those points into separate variables, but there can be an unlimited amount of obstacles in the list. Each obstacle will have a row and column number, which is how I am determining how the robot will move.
I have tried to create a list and then taken the length of that list and used that to separate the different coordinates in the list, but since there is supposed to be a random amount of obstacles, the code would have to be changed every time another obstacle is added.
obstacles = [(2,3),(3,5),(5,2)]
#list of the obstacle coordinates
length = range(0,len(obstacles))
obs1,obs2,obs3,obs4=[obstacles[i] for i in length]
#Seperation of the coordinates into groups
obsRow,obsCol=obs1
#Seperation into the row and column of the coordinates
This function is giving an output, but the output only works when the number of obstacles in the list is equal to the amount of obstacles with the number after them (ex: obs1). I want this function to work no matter how many obstacles are in the list without changing the function.

If you are dealing with a potentially infinite number of spaces and obstacles you may want to look into A* pathfinding. It's a way to find the most efficient route without exhaustively trying every possible combination (see. The Travelling Salesman problem).
The following article provides an example of how you would solve a similar problem in Python alongside the relevant theory to understand the concepts behind the solution.

Related

updating chosen elements in Pygame

I am working on animation of Fourier Transform in python, pygame. I want the result to look more or less as following:
https://www.youtube.com/watch?v=ACvXAjZE9jQ
I need to update the screen in order to constantly draw arms, or links in their new positions. However, updating the screen erases the graph drawn by the arms. I am drawing it by putting small dots in time intervals.
Would anyone have any suggestion how to deal with this dilemma or propose another solution?
My first idea was to add all the points coordinates to the list and draw them all together at every update, but the operation quickly becomes too inefficient and the animation keeps slowing dowm.
My first idea was to add all the points coordinates to the list and draw them all together at every update
This is the usual approach. However, I suggest converting the coordinates to int before adding them to the list, and only adding coordinate tuples that are not already in the list. This means that a new position must be compared with the last position before it is added. With this approach, the list should not become so long that the application slows down significantly. e.g.:
def appendPoint(point_list, x, y):
new_point = round(x), round(y)
if not point_list or point_list[-1] != new_point:
point_list.append(new_point)

Arms motion with coordinate argument with NAO?

I am beginner with NAO programming and I am now working on a project involving arms motion.
I must program a game in which NAO would first stand and point out one among three squares with different colors which would be displayed on the ground.
I think that I can "simply" make Nao move its arm so he would point towards one of three different pre-defined coordinates.
However, animation mode and motion widget do not seem usable for movements with parameters, like one out of the three coordinates.
How do I perform such a move ?
Have you look at the ALMotion.setPositions type of method ?
There are methods working in cartesian space. It means that you just positionnate some end effector (eg the hand) to be at a specific positions compared to the origin of the chest (for instance).
You can see that as a vector pointing to a direction...
The solver used for that could be enhanced, but it's a nice way to achieve what you need to do.
More info there:
http://doc.aldebaran.com/2-1/naoqi/motion/control-cartesian-api.html#ALMotionProxy::setPositions__AL::ALValueCR.AL::ALValueCR.AL::ALValueCR.floatCR.AL::ALValueCR
You could take a look at the pointAt method which takes in parameters the position that you would like to point. If the position of your three objects are known in advance, that would do the job. You can find more here:
http://doc.aldebaran.com/2-1/naoqi/trackers/altracker-api.html#ALTrackerProxy::pointAt__ssCR.std::vector:float:CR.iCR.floatCR

Expand list of strings to 2D coordinate

I'm attempting to write a Befunge interpreter in Python, and my problem right now is the p command. Basically, I have a list of strings that are each line of the file and I use a 2D coordinate system to keep track of my position. The outer list is y, and the position in each string is x.
The problem is this: The p command pops coordinates and a value out of the stack. It then puts the ASCII character corresponding to the value at that position. Unfortunately, with Python, lists and strings are really hard to expand by index. I need the most efficient way to expand the list and the strings within them to fit the updated data. I can't have it pre-expanded to a certain size for two reasons: theoretically infinite memory allocation (needed for Turing-completeness) and wrapping on the edge of the program if it isn't expanded past that edge (pre-expanded removes the ability to do that efficiently).
TL;DR: I need to find the best/most efficient way to expand a list and all the strings inside it to reach and include a specific 2D coordinate (outer list is y, inner list is x, i.e. prog[y][x]) and I can't have it pre-allocated because of several complicated and hard to explain reasons.
As it seems I was rather unclear, the p command directly modifies the running Befunge code. Thus, I can't store the data outside the program itself, as the program needs to be able to access and run it if necessary (As I have stated, Befunge is weird).
After some deliberation, I decided to use #dawg's idea tupled dicts, but in a slightly different way; basically the entire program is a tuple-key dict, that way the program can be easily modified by coordinate at any time. Thank you for your help!

directing a mass of enemies at once

I am working on a simple 2d game where many enemies continually spawn and chase the player or players in python + pygame. A problem I ran into, and one many people that have programmed this type of game have run into is that the enemies converge very quickly. I have made a temporary solution to this problem with a function that pushes any two enemies randomly apart if they are too close to each other. This works well but is about an O(n^2) algorithm which is run every frame and at high enemies the program starts to slow down.
When my program runs with this function the enemies seem to form round object I nicknamed a "clump". The clump seems to usually ecliptic but may actually be more complex (not symmetrical) because as the player moves the enemies are being pulled in different directions. I do like the way this clump behaves, however I am wondering if there is a more efficient way to calculate it. Currently every enemy in the clump (often >100) is first moved in the direction of the player, and then pushed apart. If there was instead a way to calculate the figure that the clump creates, and how it moves it would save a lot of computation.
I am not exactly sure how to approach the problem. It may be possible to calculate where the border of the figure moves, and then expand it to make sure the area stays the same.
Also my two functions currently being used to move enemies:
def moveEnemy(enemy, player, speed):
a = player.left-enemy.left
b = player.top-enemy.top
r = speed/math.hypot(a,b)
return enemy.move(r*a, r*b)
def clump(enemys):
for p in range(len(enemys)):
for q in range(len(enemys)-p-1):
a = enemys[p]
b = enemys[p+q+1]
if abs(a.left-b.left)+abs(a.top-b.top)<CLUMP:
xChange = (random.random()-.5)*CLUMP
yChange = ((CLUMP/2)**2-xChange**2)**.5
enemys[p] = enemys[p].move(int(xChange+.5), int(yChange + .5))
enemys[p+q+1] = enemys[p+q+1].move(-int(xChange+.5),-int(yChange+.5))
return enemys
Edit: some screen shots of how the clump looks:
http://imageshack.us/photo/my-images/651/elip.png/
http://imageshack.us/photo/my-images/832/newfni.png/
http://imageshack.us/photo/my-images/836/gamewk.png/
The clump seems to be mostly a round object just stretched (like an eclipse but may be stretched in multiple directions), however it currently has straight edges due to the rectangular enemies.
There are several ways to go about this, depending on your game. Here are some ideas for improving the performance:
Allow for some overlap.
Reduce your distance checking to be done after a fixed number of frames.
Improve your distance checking formula. If you are using the standard distance formula, this can be optimized in many ways. For one, get rid of the square root. Precision doesn't matter, only the relative distance.
Each unit can keep track of a list of nearby units. Only perform your calculations between the units in that list. Every so often, update that list by checking against all units.
Depending on how your game is setup, you can split the field up into areas, such as quadrants or cells. Units only get tested against other units in that cell.
EDIT: When the units get close to their target, it might not behave correctly. I would suggest rather than having them home-in on the exact target from far away, that they actually seek a randomized nearby target. Like an offset from their real target.
I'm sure there are many other ways to improve this, it is pretty open ended after all. I should also point out Boids and flocking which could be of interest.
You could define a clump as a separate object with a fixed number of spacial "slots" for each enemy unit in the clump. Each slot would have a set of coordinates relative to the clump center and would either be empty or would hold a reference to one unit.
A new unit trying to join the clump would move towards the innermost free slot, and once it got there it would "stay in formation", its position always being the position of the slot it occupied. Clumps would have a radius much larger than a single unit, would adjust position to avoid overlapping other clumps or loose units that weren't trying to join the clump, etc.
At some point, though, you'd need to deal with interactions for the individual units in the clump, though, so I'm not sure it's worthwhile. I think Austin Henley's suggestion of splitting the field up into cells/regions and only testing against units in nearby cells is the most practical approach.
I think you're looking for flocking.
The best intro to flocking / steering behavior movement: http://www.red3d.com/cwr/steer/ . See the attached paper red3d paper. And the related OpenSteer

python: sorting two lists of polygons for intersections

I have two big lists of polygons.
Using python, I want to take each polygon in list 1, and find the results of its geometric intersection with the polygons in list 2 (I'm using shapely to do this).
So for polygon i in list 1, there may be several polygons in list 2 that would intersect with it.
The problem is that both lists are big, and if I simply nest two loops and run the intersection command for every
possible pair of polygons, it takes a really long time. I'm not sure if preceding the intersection with a boolean test would speed this up significantly (e.g. if intersects: return intersection).
What would be a good way for me to sort or organize these two lists of polygons in order to make the intersections
more efficient? Is there a sorting algorithm that would be appropriate to this situation, and which I could make with python?
I am relatively new to programming, and have no background in discrete mathematics, so if you know an existing algorithm
that I should use, (which I assume exist for these kinds of situations), please link to or give some explanation that could assist me in actually
implementing it in python.
Also, if there's a better StackExchange site for this question, let me know. I feel like it kind of bridges general python programming, gis, and geometry, so I wasn't really sure.
Quadtrees are often used for the purpose of narrowing down the sets of polygons that need to be checked against each other - two polygons only need to be checked against each other if they both occupy at least one of the same regions in the quadtree. How deep you make your quadtree (in the case of polygons, as opposed to points) is up to you.
Even just dividing your space up to smaller constant-size areas would speed up the intersection detection (if your polygons are small and sparse enough). You make a grid and mark each polygon to belong to some cells in the grid. And then find cells that have more than one polygon in them and make the intersection calculations for those polygons only. This optimization is the easiest to code, but the most ineffective. The second easiest and more effective way would be quadtrees. Then there are BSP tres, KD trees, and BVH trees that are probably the most effective, but the hardest to code.
Edit:
Another optimization would be the following: find out the left-most and the right-most vertices of each polygon and put them in a list. Sort the list and then loop it somehow from left to right and easily find polygons whose bounding boxes' x coordinates overlap, and then make the intersection calculations for those polygons.

Categories