1

My friend wrote this and sent it to me to debug but I can not figure out what's wrong? Why does this subtract, but not add? I have tried many workarounds like subtraction by negative number etc, but it doesn't work. Granted I am new to python and don't know much about the pygame module, so please advise.

import pygame
pygame.init
WIN = pygame.display.set_mode((1000, 600))
pygame.display.set_caption ("Space Cats")
icon = pygame.image.load('007-cat-2.png')
pygame.display.set_icon(icon)
pla_img = pygame.image.load("002-grinning.png")



def draw_window(plaHB):
    WIN.fill((0, 100, 75))
    WIN.blit(pla_img, (plaHB.x, plaHB.y))
    pygame.display.update()

def MAIN():
    run = True
    plaX, plaY = 450, 500
    plaSpeed = 0.7
    plaHB = pygame.Rect(plaX, plaY, 32, 32)
   #FPS = 60
   #clock = pygame.time.Clock
    while run == True:
        #clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
        key_pre = pygame.key.get_pressed()
        if key_pre[pygame.K_RIGHT] and plaHB.x < 1000:
           plaHB.x = plaHB.x + plaSpeed
        if key_pre[pygame.K_LEFT] and plaHB.x > 0:
           plaHB.x -= plaSpeed
        if key_pre[pygame.K_UP]:
           plaHB.y -= plaSpeed
        if key_pre[pygame.K_DOWN]:
           plaHB.y += plaSpeed
        draw_window(plaHB)
    pygame.QUIT



if __name__ == "__main__":
   MAIN()
Ari Frid
  • 127
  • 7

1 Answers1

1

Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. [...]

The fraction part of the coordinates gets lost when the new position of the object is assigned to the Rect object. Therefore the object can just be moved to the left and up.

If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables and to synchronize the pygame.Rect object. round the coordinates and assign it to the location (e.g. .topleft) of the rectangle:

def MAIN():
    # [...]

    x, y = rect.topleft
    while run == True:
        #clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
        key_pre = pygame.key.get_pressed()
        if key_pre[pygame.K_RIGHT] and plaHB.x < 1000:
            x += plaSpeed
        if key_pre[pygame.K_LEFT] and plaHB.x > 0:
            x -= plaSpeed
        if key_pre[pygame.K_UP]:
            y -= plaSpeed
        if key_pre[pygame.K_DOWN]:
            y += plaSpeed
        rect.topleft = round(x), round(y)
        draw_window(plaHB)
    pygame.quit()

Also read What is the difference between .quit and .QUIT in pygame.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174