I have a script that is dealing with a list of ships that are racing. The number of racers can be selected at the start of the race.
Now the fun begins!
During the race each ships lap is recorded- and so as each ship passes the start/ finish line a string will print the result. The main problem I am trying to get around is that ships can be destroyed, so the way in which this information is recorded needs to be flexible.
This is the code:
try: ship is not None ship_in_race = bge.logic.getCurrentController().sensors["Collision"].hitObject if collision.positive and ship_in_race == ship and ship["lap"] > 0: ow["ship_1_lap_time"] = ship_in_race["race_time"] print(str("First place:") + str(" ") + str(ship_in_race) + str(" ") + str("lap time:") + str(" ") + ow["ship_1_lap_time"]) except IndexError: print("ship was not selected at race start or has been destroyed")
As you can see, the script creates a reference to any ship that activates the collision sensor, and checks to see if that object in the list exists. There are eight properties that are used by the controlling object to store up to eight lap times.
If the racer does not exist, it generates an exception (in the case of a ship that is destroyed or is not selected) and one of the eight lap time properties is not written to.
Now my question: is there a way to get around using a try / except style approach to this? In essence is there a way of stopping an ‘out of index’ error without ignoring it like I am doing here?
If I do choose to keep the try /except approach, would it cause any problems later along the line?
I hope this makes sense!