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()