Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

python - How can I stop my rectangles in pygame thinking they are colliding into themselves?

So I am currently creating a game in pygame, where rectangles spawn in random parts of the game's window, and move around in random directions.

For one of this game's features, I have to tried make it so that each rectangle can detect if another rectangle is near to it. To do this, I have added a second rectangle around each rectangle that follow them around, so I can detect if these second rectangles collide, then giving commands to the main rectangles on where to move next.

However, whenever I run the code below, the 2nd rectangles (written in the code as 'rect_anti_collsion'), seem to believe they are constantly colliding with themselves, even though that isn't possible.

There seems to be an error at this code although I don't know what:

    while loop1 < len(rects):
        try:
            if rects[-1][1].colliderect(rects[loop1][1]):
                print("collided")
        except IndexError:
            print("INDEX ERROR")
        loop1 += 1

The full code (if this game seems a bit odd, it is because I have simplified the code to all that is important to this bug):

import pygame
import time
import random
import sys
import os

def rect_animation(given_rect, given_rect_anti_collision):
    global rect_movement_counter, can_move_left, can_move_right, can_move_up, can_move_down

    del rects[rect_loop]
    rects.append([given_rect, given_rect_anti_collision])
    given_rect_anti_collision = rects[-1][1]
    given_rect = rects[-1][0]

    if given_rect.x <= 10:
        can_move_left = False

    if given_rect.x >= 1100:
        can_move_right = False

    if given_rect.y <= 10:
        can_move_up = False

    if given_rect.y >= 600:
        can_move_down = False

    direction = random.randint(1, 4)

    if direction == 1 and rect_movement_counter <= 0 and can_move_right:


        given_rect.x += 30

        given_rect_anti_collision.x += 30
        rect_movement_counter += 60


    elif direction == 2 and rect_movement_counter <= 0 and can_move_up:  # UP

        given_rect.y -= 30

        given_rect_anti_collision.y -= 30
        rect_movement_counter += 60

    elif direction == 3 and rect_movement_counter <= 0 and can_move_down:  # DOWN

        given_rect.y += 30

        given_rect_anti_collision.y += 30
        rect_movement_counter += 60

    elif direction == 4 and rect_movement_counter <= 0 and can_move_left:  # LEFT

        given_rect.x -= 30

        given_rect_anti_collision.x -= 30
        rect_movement_counter += 60

    else:
        rect_movement_counter -= 1
    loop1 = 0

    while loop1 < len(rects):
        try:
            if rects[-1][1].colliderect(rects[loop1][1]):
                print("collided")
        except IndexError:
            print("INDEX ERROR")
        loop1 += 1


    pygame.display.update()



pygame.init()

clock = pygame.time.Clock()

FPS = 10

screen_width, screen_height = 1160, 640

screen = pygame.display.set_mode((screen_width, screen_height))


rects = []

add_rect = True
for i in range(20):
    random_x = random.randint(1,18)
    random_y = random.randint(1,10)
    rect_x = 60 * random_x
    rect_y = 60 * random_y

    rect = pygame.Rect(rect_x, rect_y, 30,30)
    rect_anti_collision = pygame.Rect(rect_x - 1, rect_y - 1, 32,32)

    rects.append([rect, rect_anti_collision])

x_location = 0
y_location = 0

rect_movement_counter = 30

while True:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill((20,140,20))

    for certain_rect_anti_collision in range(len(rects)):
        pygame.draw.rect(screen, (200, 200, 20), rects[certain_rect_anti_collision][1])
    for certain_rect in range(len(rects)):
        pygame.draw.rect(screen, (200, 200, 200), rects[certain_rect][0])



    rect_loop = 0

    while rect_loop < len(rects):
        can_move_right = True
        can_move_left = True
        can_move_up = True
        can_move_down = True

        rect_animation(rects[rect_loop][0],rects[rect_loop][1])
        rect_loop += 1

    pygame.display.flip()
question from:https://stackoverflow.com/questions/66058945/how-can-i-stop-my-rectangles-in-pygame-thinking-they-are-colliding-into-themselv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just don't test the last rectangle in the list:

while loop1 < len(rects):

while loop1 < len(rects)-1:
    try:
        if rects[-1][1].colliderect(rects[loop1][1]):
        print("collided")
    except IndexError:
        print("INDEX ERROR")
    loop1 += 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...