Chance Herriage Chance Herriage - 21 days ago 5
Python Question

Getting next two indexes regardless of current index

I am trying to create a mock rock, paper, scissors game with each name having two enemies, so I must be able to grab the values of all the names regardless of the position.

Say I am given this list:

names = ["Kings", "Queens", "Jacks", "Jokers", "Masons", "Warriors", "Soldiers"]


And I am trying to use the logic with the indexes being the values and would gather the next two values of the indexes. Each index would return the these values.

0 - 1, 2
1 - 2, 3
2 - 3, 4
3 - 4, 5
4 - 5, 6
5 - 6, 0
6 - 0, 1


So 'Warriors' will have the enemies of: Soldiers and Kings

Below being my current implementation:

def state_to_text(self):
names = ["Kings", "Queens", "Jacks", "Jokers", "Masons", "Warriors", "Soldiers"]
if self.state == 0:
return str(names[1], names[2])
if self.state == 1:
return str(names[2], names[3])
if self.state == 2:
return str(names[3], names[4])
if self.state == 3:
return str(names[4], names[5])
if self.state == 4:
return str(names[5], names[6])
if self.state == 5:
return str(names[6], names[1])
if self.state == 6:
return str(names[0], names[1])


Thank you.

Answer

As the comment said you can use modular arithmetic:

def state_to_text(self): 
    names = ["Kings", "Queens", "Jacks", "Jokers", "Masons", "Warriors", "Soldiers"]
    names_length = len(names) 
    return str(names[(self.state + 1) % names_length], names[(self.state + 2) % names_length])

Or basically repeat the first two elements in the end of the list so you can get them by simply add 1 or 2

def state_to_text(self): 
    names = ["Kings", "Queens", "Jacks", "Jokers", "Masons", "Warriors", "Soldiers", "Kings", "Queens"] 
    return str(names[self.state + 1], names[self.state + 2])
Comments