PYTHON: bolas que reboten cuando se chocan: array con objetos

N = 8

pelotas = []


def setup():

    size(800, 600)

    frameRate(300)

    

    global pelotas

    pelotas = []

    for i in range(N):

        r = random(15, 40)

        x = random(r, width - r)

        y = random(r, height - r)

        dx = random(-2, 2)

        dy = random(-2, 2)

        pelotas.append(Pelota(x, y, dx, dy, r))


def draw():

    background(220)


    for pelota in pelotas:

        pelota.mover()

        pelota.rebotar()

        pelota.dibujar()


    for i in range(N):

        for j in range(i + 1, N):

            pelotas[i].choque(pelotas[j])


class Pelota:

    def __init__(self, Tx, Ty, Tdx, Tdy, Tr):

        self.x = Tx

        self.y = Ty

        self.dx = Tdx

        self.dy = Tdy

        self.r = Tr


    def mover(self):

        self.x = self.x + self.dx

        self.y = self.y + self.dy


    def rebotar(self):

        if self.x - self.r < 0 or self.x + self.r > width:

            self.dx = self.dx *-1

        if self.y - self.r < 0 or self.y + self.r > height:

            self.dy =self.dy * -1


    def dibujar(self):

        ellipse(self.x, self.y, self.r * 2, self.r * 2)


    def choque(self, otra):

        d = dist(self.x, self.y, otra.x, otra.y)

        if d <= self.r + otra.r:

            tx, ty = self.dx, self.dy

            self.dx= otra.dx

            self.dy=otra.dy

            otra.dx= tx

            otra.dy=ty

Comentarios

Entradas populares de este blog

Medidas de Seguridad

PYTHON: bolas que cuando choquen se pare el programa