[Python] Can someone fix my code? Rectangles not showing up

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create two rectangles as an obstacle and a finish. The player rectangle is square_pos, the obstacle rectangle is wall_pos, and the finish rectangle is finish_pos.

    import pygame
    import random
    pygame.init()
    screen = pygame.display.set_mode((1280, 720))
    clock = pygame.time.Clock()
    random_pos = random.randint(280, 1000)
    random_size = random.randint(75, 250)
    square_pos = pygame.Rect(640, 360, 25, 25)
    wall_pos = pygame.Rect(random_pos, random_pos, random_size, random_size)
    finish_pos = pygame.Rect(random_pos, random_pos, 25, 25)
    collide = pygame.Rect.colliderect(square_pos,wall_pos)
    collidefinish = pygame.Rect.colliderect(square_pos,finish_pos)
    while True:
    if pygame.event.get(pygame.QUIT): break
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
    square_pos.y -= 20
    if keys[pygame.K_DOWN]:
    square_pos.y += 20
    if keys[pygame.K_LEFT]:
    square_pos.x -= 20
    if keys[pygame.K_RIGHT]:
    square_pos.x += 20
    if collide:
    if keys[pygame.K_UP]:
    square_pos.y += 20
    if keys[pygame.K_DOWN]:
    square_pos.y -= 20
    if keys[pygame.K_LEFT]:
    square_pos.x += 20
    if keys[pygame.K_RIGHT]:
    square_pos.x -= 20
    if collidefinish:
    square_pos.move_rectangle(640, 360)
    rectangles[wall_pos, finish_pos].alive = False
    wall_pos = pygame.Rect(random_pos, random_pos, random_size, random_size)
    finish_pos = pygame.Rect(random_pos, random_pos, 25, 25)
    while collide == True:
    square_pos.move_rectangle(640, 360)
    rectangles[wall_pos, finish_pos].alive == False
    wall_pos = pygame.Rect(random_pos, random_pos, random_size, random_size)
    finish_pos = pygame.Rect(random_pos, random_pos, 25, 25)
    if collide == False: break
    if collidefinish == False: break
    while collidefinish == True:
    square_pos.move_rectangle(640, 360)
    rectangles[wall_pos, finish_pos].alive == False
    wall_pos = pygame.Rect(random_pos, random_pos, random_size, random_size)
    finish_pos = pygame.Rect(random_pos, random_pos, 25, 25)
    if collide == False: break
    if collidefinish == False: break
    screen.fill("black")
    pygame.draw.rect(screen, "red", square_pos)
    pygame.display.flip()
    clock.tick(60)
    pygame.quit()


    The two rectangles were supposed to show up. If any intersected with the player, they would be replaced.

    Continue reading...

Compartilhe esta Página