vendredi 6 avril 2018

two bouncing balls always linking up in tkinter

I'm trying to create a couple of bouncing balls but for some reason, they keep meeting up in the same coordinates even though they have different speeds and starting coordinates. If you run the code below, you will see that after a little while one of the balls is going to get stuck in the corner then the other one is going to follow it as one ball for the rest of the animation even they both have different speeds..

import tkinter as tk
from time import *
from random import randint, choice

myInterface = tk.Tk()
s = tk.Canvas(myInterface, width=800, height=800, background="black")
s.pack()



d = 75 

spdx = 8
spdy = 4.5 * -1

spdxb = 10 * -1
spdyb = 5 

xblock1 = 0
yblock1 = 0
xblock2 = 800
yblock2 = 800

x1 = randint(475,725)
y1 = randint(475,725)

x1b = randint(75,375)
y1b = randint(75,375)

color = ["yellow", "hot pink","deep skyblue","dark green"]
c = choice(color)
while True:
    ##c = choice(color) activate for disco mode!!
    x1 = x1 + spdx
    y1 = y1 - spdy
    x2 = x1 + d
    y2 = y1 + d

    x1b = x1b + spdx
    y1b = y1b - spdy
    x2b = x1b + d
    y2b = y1b + d


    firstball = s.create_oval(x1,y1,x2,y2, fill=c)
    secondball = s.create_oval(x1b,y1b, x2b,y2b, fill =c)

    #A1
    if x1 <= xblock1:
        x1 = xblock1
        x2 = x1 + d
        spdx = spdx * -1
    #B1  
    if x1b <= xblock1:
        x1b = xblock1
        x2b = x1b + d
        spdxb = spdxb * -1
    #A2
    if x2 >= xblock2:
        x2 = xblock2
        x1 = x2 - d
        spdx = spdx * -1
    #B2
    if x2b >= xblock2:
        x2b = xblock2
        x1b = x2b - d
        spdxb = spdxb * -1
    #A3
    if y1 <= yblock1:
        y1 = yblock1
        y2 = y1 + d
        spdy = spdy * -1
    #B3
    if y1b <= yblock1:
        y1b = yblock1
        y2b = y1b + d
        spdyb = spdyb * -1
    #A4
    if y2 >= yblock2:
        y2 = yblock2
        y1 = y2 - d
        spdy = spdy * -1

    #B4
    if y2b >= yblock2:
        y2b = yblock2
        y1b = y2b - d
        spdyb = spdyb * -1


    s.update()
    sleep(0.03)
    s.delete(firstball,secondball)

Aucun commentaire:

Enregistrer un commentaire