I have a for loop that is supposed to iterate a number of times equal to the length of an array. The loop runs the correct number of times, but the index does not properly increment.
I tried manually incrementing i with i = i + 1, but that did not seem to change anything.
room = [['x','x','x','x','x'],['x','.','.','.','x'],['x','.','.','.','x'],['x','.','.','.','x'],['x','x','x','x','x']]
entities = []
class Entity:
def __init__(self, x_pos, y_pos):
self.x_pos = x_pos
self.y_pos = y_pos
self.new_x_pos = x_pos
self.new_y_pos = y_pos
def Move(self, x_move, y_move):
self.new_y_pos = self.y_pos + y_move
self.new_x_pos = self.x_pos + x_move
if self.CheckCollision(self) is True:
print("collision")
if self.CheckCollision(self) is False:
self.new_x_pos = self.x_pos
self.new_y_pos = self.y_pos
def CheckCollision(self, entity1):
for i in range(len(entities)-1):
#this loop here. It runs twice, but the value of i is zero for both iterations
entity = entities[i]
print(i)
if entity1.new_y_pos == entity.y_pos:
if entity1.new_x_pos == entity.x_pos:
return True
break
else:
return False
calipso = Entity(1, 1)
entities.append(calipso)
joseph = Entity(3,2)
entities.append(joseph)
print(entities)
calipso.Move(1,1)
print(calipso.x_pos, calipso.y_pos, sep=' ')
I want i to increment each iteration of the for loop, thus i === 0 for the first iteration and i === 1 for the second iteration. Currently, i === 0 for both iterations and I don't know why.
range(1)will only producei=0and stop afterwards. remove the-1fromlen(entities)-1.CheckCollision()twice because within the methodMove(), you callCheckCollision()twice (the twoifstatements).