Pygame Sprite Motion with Wrap-Around


import pygame

WIDTH = 500
HEIGHT = 500
FPS = 60

#define colors
#colors are defined in red,green,blue
#values from 0-255
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
YELLOW = (255,255,0)

pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH,HEIGHT))
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
  
  def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = pygame.Surface((50,40))
    self.image.fill(GREEN)
    self.rect = self.image.get_rect()
    self.rect.centerx = 30
    self.rect.centery = 30
    self.speedx = 0
    self.speedy = 0
    self.ticker = 0
  
  def update(self):
    speed = 5
    self.speedx = 0
    self.speedy = 0
    keystate = pygame.key.get_pressed()
    if keystate[pygame.K_LEFT]:
      self.speedx = -speed
    if keystate[pygame.K_RIGHT]:
      self.speedx = speed
    if keystate[pygame.K_UP]:
      self.speedy = -speed
      self.ticker += 1 #NEW CODE
    if keystate[pygame.K_DOWN]:
      self.speedy = speed
      self.ticker += 1 #NEW CODE
    self.rect.x += self.speedx
    
    
    #HERE IS WHERE WE 
    self.ticker = self.ticker % 20
    if self.ticker  >9:
      self.image.fill(GREEN)
    else:
      self.image.fill(BLUE)
    #HERE WE ARE GOING TO WRAP AROUND THE EDGES IF THE SPRITE
    #GOES OFF THE SCREEN
    #REMEMBER THAT X IS LEFT TO RIGHT AND Y IS UP AND DOWN
    if self.rect.x > WIDTH:
      self.rect.x = 0
    if self.rect.x < 0:
      self.rect.x = WIDTH
    self.rect.y += self.speedy
    if self.rect.y > HEIGHT:
      self.rect.y = 0
    if self.rect.y < 0:
      self.rect.y = HEIGHT
      
    

all_sprites = pygame.sprite.Group()
james = Player()
all_sprites.add(james)
running = True

while running:
  
  clock.tick(FPS)
  pygame.event.get()
  all_sprites.update()
  screen.fill(BLACK)
  all_sprites.draw(screen)
  pygame.display.flip()