Reputation: 7303
How can I set boundaries for pygame
that will not let a rectangle ( you can say square ) get out of the screen?
I visited other sites but nothing was useful for me.
Box will move left ( a ) , right ( d ) , up ( w ) , down ( s )
.
My code:
import sys
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect = pg.Rect(300, 220, 20, 20)
velocity = (0, 0)
done = False
#screen
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
keys = pg.key.get_pressed()
#move slow
if keys[pg.K_a]:
rect.x -= 4
if keys[pg.K_d]:
rect.x += 4
if keys[pg.K_s]:
rect.y += 4
if keys[pg.K_w]:
rect.y -= 4
#move fast
if keys[pg.K_g]:
rect.x -= 8
if keys[pg.K_j]:
rect.x += 8
if keys[pg.K_h]:
rect.y += 8
if keys[pg.K_y]:
rect.y -= 8
screen.fill((40, 40, 40))
pg.draw.rect(screen, (100, 200, 20), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
Upvotes: 2
Views: 6673
Reputation: 13327
On the following code, the boundaries are the screen width and height, so you better define them from the beginning.
A way to handle this is to prevent the x
and y
coordinates from going below 0
and above the width for x
and the height for y
, without forgetting to subtract the size of the box.
I suggest a little gameplay improvement to use the booster, rather than pressing other keys, its better to use a modifier like shift or control. The below code use left shift to speed up the movement.
import sys
import pygame as pg
def main():
width, height = 640, 480
hbox, vbox = 20, 20
screen = pg.display.set_mode((width, height))
clock = pg.time.Clock()
rect = pg.Rect(300, 220, hbox, vbox)
velocity = (0, 0)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
keys = pg.key.get_pressed()
# booster
move = 8 if keys[pg.K_LSHIFT] else 4
if keys[pg.K_a]: #to move left
rect.x -= move
if rect.x < 0 : rect.x = 0
if keys[pg.K_d]: #to move right
rect.x += move
if rect.x > width-hbox : rect.x = width - hbox
if keys[pg.K_w]: #to move up
rect.y -= move
if rect.y < 0: rect.y = 0
if keys[pg.K_s]: #to move down
rect.y += move
if rect.y > height - hbox: rect.y = height - vbox
screen.fill((40, 40, 40))
pg.draw.rect(screen, (150, 200, 20), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
Upvotes: 2