looking for some solutions? You are welcome.

SOLVED: How do I check for collisions in pygame between all the objects of my class

Colday96:

I am currently trying to print on the screen when a collision occurs but don't know how to do it for only 1 class. I know how to make 2 objects collide from different classes but I don't know how to do it for one classes with 1000 different objects

I tried using some in game pygame functions like pygame.rect.contain but i had no idea where to go from there. Thanks for helping me guys.

The code is listed below :

import pygame
import random
import sys
import time

Height = 800
Width = 800
Steps = 0
running = True

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

pygame.init()
display = pygame.display.set_mode((Height, Width))
clock = pygame.time.Clock()
pygame.display.set_caption("Game")


class Ball(object):

def __init__(self, x, y, delta_x, delta_y):
    self.x = x
    self.y = y
    self.delta_x = delta_x
    self.delta_y = delta_y

def draw(self):

    pygame.draw.rect(display, WHITE, (self.x, self.y, 1, 1))

def update(self):
    self.x += self.delta_x
    self.y += self.delta_y

    if self.x < 0:
        self.delta_x = self.delta_x * -1
    if self.x > Width - 5:
        self.delta_x = self.delta_x * -1

    if self.y < 0:
        self.delta_y = self.delta_y * -1
    if self.y > Height - 5:
        self.delta_y = self.delta_y * -1


list = []
for i in range(1000):
    ball = Ball(random.randrange(0, Width - 5), random.randrange(0, Height - 5),
                random.randint(-10, 10), random.randint(-10, 10))

    list.append(ball)

while running:
    display.fill(BLACK)
    clock.tick(60)

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.quit()

    # Update

    # Draw
    for ball in list:

        ball.draw()
        ball.update()

    pygame.display.update()

    pygame.display.update()
    print(clock.tick(60))



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent