我该怎么把球打圈?

2024-09-28 05:20:58 发布

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

所以,作为一个个人项目,我正在尝试建立一个乒乓球游戏。我已经设置好了窗户,所有的代码,桨都可以移动了。。。只是球而已。球移动一次,然后再也不会移动。我不知道这是不是球的运动定义有问题,或者只是我不知道如何正确使用mainloop(),但是如果我知道如何让球永远保持运动,那就太好了。如果你想让我解释我想让球做什么,看看下面的代码

#Setting up the window

from tkinter import *
from time import *

HEIGHT=800
WIDTH=1280
window=Tk()

window.title('PONG!')
c=Canvas(window,width=WIDTH,height=HEIGHT,bg='black')
c.pack()

MID_X=WIDTH/2
MID_Y=HEIGHT/2
def pongstick():
    return c.create_polygon(0,0, 10,0, 10,70, 0,70, fill='white')
def ball():
    return c.create_oval(MID_X-10,MID_Y-10, MID_X+10,MID_Y+10, fill='white')

pong1=pongstick()
pong2=pongstick()
ballplay=ball()
MID_Y=MID_Y-35
c.move(pong1, 40, MID_Y)
c.move(pong2, WIDTH-40, MID_Y)

#Scores
player1p=0
player2p=0
ballspeed=10

#Movement of the paddles
stickspeed=10
def move_stick(event):
    if event.keysym == 'w':
        c.move(pong1, 0, -stickspeed)
    elif event.keysym == 's':
        c.move(pong1, 0, stickspeed)
    if event.keysym == 'Up':
        c.move(pong2, 0, -stickspeed)
    elif event.keysym == 'Down':
        c.move(pong2, 0, stickspeed)

#Ball movement logic
ballspeed=10
ballY=ballspeed
ballX=ballspeed
ballXadd=WIDTH/2
ballYadd=HEIGHT/2

def move_ball(ballX,ballY,ballXadd,ballYadd,player1p,player2p):

    #Movement + edge hit detector
    c.move(ballplay, ballX, ballY)
    ballXadd=ballXadd+ballX
    ballYadd=ballYadd+ballY
    if ballXadd > WIDTH:
        player2p=player2p+1
        c.move(ball,MID_X-10,MID_Y-10)
        ballXadd=0
        ballYadd=0

    elif ballXadd < WIDTH:
        player1p=player1p+1
        c.move(ball,MID_X-10,MID_Y-10)
        ballXadd=0
        ballYadd=0

    elif ballYadd > HEIGHT:
        if ballX == ballspeed:
            ballY = -ballspeed
        elif ballX == -ballspeed:
            ballY = ballspeed

    elif ballYadd < HEIGHT:
        if ballX == ballspeed:
            ballY = ballspeed
        elif ballX == -ballspeed:
            ballY = -ballspeed


#GAME!
c.bind_all('<Key>',move_stick)
while 5<7:
    move_ball(ballX,ballY,ballXadd,ballYadd,player1p,player2p)
    mainloop()

所以,ballX沿着x轴移动,而ballY。。。显而易见的 ballX/Yadd是针对窗口边缘设置命中检测的变量。如果ballYadd大于或小于高度,那么轨迹将改变。如果ballXadd大于或小于宽度,球将返回到中间,并重置一个点(player1p或player2p,取决于它击中哪一侧)和轨迹。你知道吗


Tags: eventmovewidthheightelifmidballballx

热门问题