import pygame
from pygame.locals import *

def main():
    pygame.init()
    pygame.display.set_caption("Move Box With Arrow Keys")
    wndsize = (320, 240)
    display = pygame.display.set_mode(wndsize)

    x = 5
    y = 5

    black = (0, 0, 0)
    white = (255, 255, 255)

    rectpos = (x, y)
    rectdim = (10, 10)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w and pygame.key.get_mods() & pygame.KMOD_CTRL:
                    pygame.quit()
                    quit()      
                if event.key == pygame.K_RIGHT:
                    x += 5
                    print("K_RIGHT")
                if event.key == pygame.K_LEFT:
                    x -= 5
                    print("K_LEFT")
                if event.key == pygame.K_UP:
                    y -= 5
                    print("K_UP")
                if event.key == pygame.K_DOWN:
                    y += 5
                    print("K_DOWN")
                
                # Don't allow coords below 0
                if 0 > x:
                    x = 5
                if 0 > y:
                    y = 5
                
                # Don't allow overflow
                if x + rectdim[0] > wndsize[0]:
                    x = wndsize[0] - rectdim[0] - 5
                
                if y + rectdim[1] > wndsize[1]:
                    y = wndsize[1] - rectdim[1] - 5
                
                rectpos = (x, y)
    
        display.fill(white)
        rect = pygame.draw.rect(display, black, ((rectpos), (rectdim)))
        pygame.display.update()

main()