Search code examples
pythonpygamegame-physicscollision

How can I implement boundaries or collisions for this movement style?


I'm trying to make a simple game and it's working well. The movement is like the movement of a tetris block (instantly, like teleporting) and this is what I want. I don't want smooth movement, I want this movement style.

But there is a problem... When I try to add boundaries or collision for my character and rect, it's not working, but if I write this code it's working only one time and then both the left and the right arrow key don't work anymore. How can I solve this problem?

import pygame
pygame.init()

ekranx = 160
ekrany = 310
window = pygame.display.set_mode((ekranx, ekrany))
white = (255,255,255)
black = (0,0,0)
blue = (0,0,200)
pygame.display.set_caption("TOP")
clock = pygame.time.Clock()
ball = pygame.image.load("top.png")


def top(x,y):
    window.blit(ball,(x,y))
top_x = (55)
top_y = (250)
cikis = False
while not cikis:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            cikis = True
        if event.type == pygame.KEYDOWN:
                #--SOL
                if event.key == pygame.K_LEFT:
                    top_x += -50


                #--SAĞ
                if event.key == pygame.K_RIGHT:
                    top_x += 50


    #print(event)
    window.fill(white)
    top(top_x,top_y)
    pygame.draw.rect(window,blue,(5,5,150,300),5)
    if top_x < 6:
        pygame.K_LEFT = False
    if top_x > 104:
        pygame.K_RIGHT = False
    pygame.display.update()
    clock.tick(60)
pygame.quit()
quit()

Solution

  • pygame.K_LEFT = False <-- Don't do that. You're overriding the pygame.K_LEFT constant (which is actually an integer 276) here and that means you can't use it anymore in your program (pygame won't recognize these events anymore).

    Just set top_x to the minimum or maximum value if the ball moves too far left or right:

    if top_x < 6:
        top_x = 6
    if top_x > 104:
        top_x = 104