1

I tried to make a boundary and it didn't work so I deleted it however now it just doesn't want to work. It is a code with an image and uses keys to move it. I am a beginner at coding so I don't know much so I would appreciate some edits or recommendations on what I should do.

This is my code:

#Imports Pygame module
import pygame

#Initializing/ Starting Pygame module
pygame.init()

#Setting the  background and starting location of logo
dvdLogoSpeed = [1, 1]
backgroundColor = 0, 0, 0

#Screen size display variable
screen = pygame.display.set_mode(600, 600)

#Variable for logo and made rectangle for logo
dvdLogo = pygame.image.load("dvd-logo-white.png")
dvdLogoRect = dvdLogo.get_rect()

#Variables
x = 200
y = 200
vel = 10
width = 20
height = 20

def dvdwKeys ():
  
  run = True
  
  while run == True:
    
    pygame.time.delay(10)
        
    for event in pygame.event.get():
            
      if event.type == pygame.QUIT:
                
        run = False
        
    screen.fill (backgroundColor)
    screen.blit(dvdLogo, dvdLogoRect)
    
    keys = pygame.key.get_pressed()
    
    if keys[pygame.K_LEFT] and x>0:
            
      dvdLogoRect.x -= vel
            
    if keys[pygame.K_RIGHT] and x<600-width:
            
      dvdLogoRect.x += vel
           
    if keys[pygame.K_UP] and y>0:
            
      dvdLogoRect.y -= vel
            
    if keys[pygame.K_DOWN] and y<600-height:
      
      dvdLogoRect.y += vel
  
    pygame.display.flip()

dvdwKeys()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Blu
  • 21
  • 4

1 Answers1

1

You need to test dvdLogoRect.x and dvdLogoRect.y instead of x and y:

while run == True:
    # [...]

    if keys[pygame.K_LEFT] and dvdLogoRect.x>0:
      dvdLogoRect.x -= vel
            
    if keys[pygame.K_RIGHT] and dvdLogoRect.right<600:
      dvdLogoRect.x += vel
           
    if keys[pygame.K_UP] and dvdLogoRect.y>0:          
      dvdLogoRect.y -= vel
            
    if keys[pygame.K_DOWN] and dvdLogoRect.bottom<600:
      dvdLogoRect.y += vel

However, you can simplify the code with pygame.Rect.clamp_ip:

def dvdwKeys ():
    clock = pygame.time.Clock() 
    run = True
    while run == True:
        clock.tick(100)    
        for event in pygame.event.get():    
            if event.type == pygame.QUIT:       
                run = False

    keys = pygame.key.get_pressed()
    dvdLogoRect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
    dvdLogoRect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel

    dvdLogoRect.clamp_ip(screen.get_rect())
        
    screen.fill(backgroundColor)
    screen.blit(dvdLogo, dvdLogoRect)
    pygame.display.flip()

See also Setting up an invisible boundary for my sprite and How can I make a sprite move when key is held down and

Rabbid76
  • 202,892
  • 27
  • 131
  • 174