python - Window boundaries in pygame -
basically trying add boundaries small game making, have sprite can move left right , trying prevent from moving off game window, if sprite reaches edge can go no further , can go in opposite direction. current code:
tanksprite = pygame.image.load('sprites/tank.png') #fixed apostrophe tanksprite_width = 28 def tank(x,y): gamewindow.blit(tanksprite, (x,y)) def game_loop(): x = (display_width * 0.45) y = (display_height * 0.8) x_change = 0 gameexit = false gamemove = true while not gameexit , gamemove == true: event in pygame.event.get(): if event.type == pygame.quit: gameexit = false if event.type ==pygame.keydown: if event.key == pygame.k_left: x_change = -5 if event.key == pygame.k_right: x_change = 5 if event.type == pygame.keyup: if event.key == pygame.k_leftor event.key == pygame.k_right: x_change = 0 x += x_change gamewindow.fill(white) tank(x,y) if x > display_width - tanksprite_width or x < 0: gamemove = false elif x < display_width - tanksprite_width or x > 0: gamemove = true pygame.display.update() clock.tick(60) game_loop() pygame.quit() quit()
my current code partially works, when sprite reaches edge solution closes rather letting me go back. if remove:
pygame.quit() quit()
then sprite stops , can't move back. in project did while used like:
if event.key == pygame.k_left , sprite.x < 590: sprite.x += 5
the above code worked can remember can't seem figure out project now, can me out please? wish make sprite can't go past screen border, when player reaches border either stay or go in opposite direction. thanks
p.s. sorry dodgy formatting
just split if-statement , check condition each direction separately:
tanksprite = pygame.image.load('sprites/tank.png') tanksprite_width = 28 def tank(x,y): gamewindow.blit(tanksprite, (x,y)) def game_loop(): x = (display_width * 0.45) y = (display_height * 0.8) x_change = 0 gameexit = false gamemove = true while not gameexit , gamemove == true: event in pygame.event.get(): if event.type == pygame.quit: gameexit = false if event.type ==pygame.keydown: if event.key == pygame.k_left: x_change = -5 if event.key == pygame.k_right: x_change = 5 if event.type == pygame.keyup: if event.key == pygame.k_leftor event.key == pygame.k_right: x_change = 0 #valid move, add x_change if((x+x_change)> 0 , (x+x_change)<(display_width - tanksprite_width): x += x_change gamewindow.fill(white) tank(x,y) #deleted stuff here pygame.display.update() clock.tick(60) game_loop() pygame.quit() quit()
with method, don't need use gamemove
variable anymore.
you rid of x_change
variable entirely applying changes directly x
instead.
also, think may have meant gameexit = true
under if statement if event.type == pygame.quit:
, makes sense exit when event pygame.quit
triggered.
Comments
Post a Comment