两个弹跳的球总是连在一起

2024-09-28 05:22:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着创造几个弹跳球,但是由于某些原因,它们在同一个坐标上不断相遇,即使它们有不同的速度和起始坐标。如果你运行下面的代码,你会看到一个球在一段时间后会被卡在角落里,然后另一个球会跟着它,作为动画的一个球,即使它们都有不同的速度。。你知道吗

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)

Tags: ifspdxx1x2randintx1by1y2
1条回答
网友
1楼 · 发布于 2024-09-28 05:22:42

问题是您正在使用spdxspdy来更新ball 2,而不是spdxbspdyb。你知道吗

所以,当球2击中左边缘时,它每帧只来回翻转一次spdxb。这没有任何作用,因为您没有使用spdxb进行任何操作。同时,两个球都使用的spdx,直到球1也击中左边缘才翻转。你知道吗

顺便说一下,这是一个很好的例子,说明为什么干燥(不要重复你自己)是如此重要的规则。因为您已经多次复制和粘贴了带有小更改的同一代码,所以很容易将其中一个小更改弄错而看不到它。尤其是在你盯着看了几个小时的代码里。你知道吗

相关问题 更多 >

    热门问题