I can't figure this out for the life of me, but in PyGame, I'm trying to add logic to reset an object's position whenever it loses a life. However, when I set the position of the object to the start position variable, nothing happens.
Here's what I have so far (abridged of course):
#setup of variables, etc
window_size = (1000, 750)
...
start_position = [window_size[0]/2, window_size[1]/2]
...
pac_man = PacMan(start_position, 3, 0, 0)
...
pygame.draw.rect(DISPLAYSURF, red, [pac_man.position[0], pac_man.position[1], 10, 10])
...
#inside the main game while loop
#event handlers
...
pac_man.move()
for ghost in ghosts:
ghost.move(pac_man.position)
if pac_man.position[0] == ghost.position[0] and pac_man.position[1] == ghost.position[1]:
pac_man.lives -= 1
pac_man.position = start_position
#redraw map
DISPLAYSURF.fill(black)
for ghost in ghosts:
pygame.draw.rect(DISPLAYSURF, white, [ghost.position[0], ghost.position[1], 10, 10])
pygame.draw.rect(DISPLAYSURF, red, [pac_man.position[0], pac_man.position[1], 10, 10])
pygame.display.update()
clock.tick(60)
Here's what the pac-man class looks like:
def __init__(self, position, lives, x_speed, y_speed):
self.position = position
self.lives = lives
self.x_speed = x_speed
self.y_speed = y_speed
def move(self):
self.position[0] += self.x_speed
self.position[1] += self.y_speed
def move_to(self, position):
self.position[0] = position[0]
self.position[1] = position[1]
At first I thought it might be a race condition or something, but there's no concurrency going on at all.
I've tried every permutation of resetting the position I can think of (pac_man.position = start_position, pac_man.position[0] = start_position[0], pac_man.move_to(start_position))
This is pretty perplexing to me, because PacMan initializes properly using start_position. I thought maybe it had something to do with the fact that he moves during the same step as the ghosts do, but that can't be it, because the life lost triggers just fine (so it has to have gotten inside the if statement). Nothing in the code changes the value of pac_man.position until well after the redraw, only accessors are called.
The current behaviour as it stands is that whenever PacMan touches a ghost, he continues moving in his original direction, he loses one life, and the ghost follows after him as before.
Am I missing something major? Shouldn't changing the value of position affect his position when the next screen redraw happens? Even if the redraw doesn't work out, he should still mechanically have "start_position", right?
I apologize if this is a dumb question. I'm very new to python/pygame, but I don't think this should be as confusing as it currently is. I'm sure I'm missing something big.
Thanks!