'How to move the object in squared path repeatedly?

So basically what I want to happen here is to make my object move to the screen in all directions whenever it reaches the endpoint. For example, if I go -> then if I reach the endpoint, downward then if I reach the endpoint, <- then if I reach the endpoint then upward as it keeps repeating. Here's the code.

import pygame

#Initialize Game
pygame.init()

#Create a screen (width,height)
screen = pygame.display.set_mode((550,725))

#Title and icon
pygame.display.set_caption('Bounce')
icon = pygame.image.load('assets/ball.png')
court = pygame.image.load('assets/court.png')
pygame.display.set_icon(icon)
clock = pygame.time.Clock()

def ball(x,y):
    screen.blit(icon,(x,y))

def court_(x,y):
    screen.blit(court,(x,y))

x = 430
y = 630

direction = "right" #Directions

running = True
while running:

#background
  screen.fill((255,175,0)) 

    
  for event in pygame.event.get():
      if event.type == pygame.QUIT:
          running = False

  if direction == "right":
      x -= 2
  if direction == "left":
      x += 2
  if direction == "up":
      y -= 2
  if direction == "down":
      y += 2

  if x <= 30: 
      direction = "up"
  if y <= 30:
      direction = "left"
  if x >= 430:
      direction = "down"
  if y == 630:
      direction = "right"

  court_(0,0)
  ball(x,y)

  pygame.display.update()
  clock.tick(60)

Here is my expectation enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source