我如何主动球?

时间:2017-03-14 21:30:51

标签: python pong

所以,作为一个个人项目,我试图建立一个PONG游戏。我已经设置了窗口,所有的代码,桨都移动得很好......它只是球。球移动一次,然后再也不移动。我不知道这是球运动定义的问题,还是我不理解如何正确使用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,取决于它击中的那一侧)和轨迹重置。

0 个答案:

没有答案