Another list comprehension question: I am making a racing position indicator that reads
what place a player is in the race- like 2 / 4 (player is second out of four).
Now, I can easily get how many racers there are (via len), and I can easily sort the racers into order, but I have a problem in that I need to return the position of the player in a list (so I can use the .index() command).
Psuedocode:
sce = bge.logic.getCurrentScene()
objList = sce.objects
Players = [ob for ob in sce.objects if 'distance' in ob]
Players.sort(key=lambda sortkey: sortkey['distance'],reverse=True)
print(Players)
Players_len = len(Players) # establishes how many racers
Position = Players.sort(key=lambda sortkey: sortkey['distance'],reverse=True).index(objList['Cube'])
print(Position)
The last line is the problem: I can sort the racers via the [‘distance’] property, but I need to get the position of the players object in the list to return a number for the HUD.
The annoying thing is the list returns the objects names (like Cube, Cube001) but I cannot use them to get their position in the list (via .index(objList[‘Cube’]) or equivalent).
I think I am confusing myself, but this is what I need to find:
I sort the players by a property [distance], so I would get a list like [player1,player2,player3] etc. Now in this example I only want to get player 2s position in the list regardless of what position it might be ([0], [1] or [2]) and use that as an integer (for a race position property)- so when I use len(Players) to get the total players I would hopefully get Player2 current position out of the racers, which is 2nd out of 3 (2/3).
I can do the initial sort, and I can get the number of racers. I just need a way to say ‘only report what Player 2s position on the list is’. I can do the reverse (Print(Position2) which gives me whoever is second just not the other way round.