重置变量会增加它而不是重置变量--Tkinter

时间:2017-04-10 10:50:13

标签: python tkinter

我正在使用tkinter创建一个Pong游戏作为一个小项目。我写过这个游戏,它完全有效。然而,我遇到了一个奇怪的错误,在游戏结束时,当一个玩家达到3分时,当游戏重新开始时,球的速度似乎加倍,并且每次游戏重置时都会发生这种情况。 startgame函数应该在调用时将变量dx(球的x移动)设置为2,所以我不确定为什么它似乎每次都加快2,因为没有添加。 我已经发布了下面的整个代码块,并且完全不知道为什么会发生这种情况,任何帮助都会非常感激!

from tkinter import *
root = Tk()

#size of window
w = 600
h = 400
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

#playing frame, with Canvas inside
canvframe = Frame(relief=SUNKEN, width=600, height = 350, background="black")
canvframe.pack()

canv = Canvas(canvframe, background="black", width=600, height = 350)
canv.pack(fill=NONE)

# Objects in canvas           
ball = canv.create_oval(300,160,310,170, outline="white", fill="white", width=2, tags=('ball'))
paddle1 = canv.create_rectangle(0,200,10,120, outline="white", fill="white", width=2, tags=('paddle1'))
paddle2 = canv.create_rectangle(590,200,600,120, outline="white", fill="white", width=2)

#Paddle movement      
def moveUp1(event):
    canv.move(paddle1, 0, -10)        
    pass
def moveUp2(event):
    canv.move(paddle2, 0, -10)        
    pass
def moveDown1(event):
    canv.move(paddle1, 0, 10)        
    pass
def moveDown2(event):
    canv.move(paddle2, 0, 10)        
    pass 

#InitialVelocity
dx = 0
dy = 0

#initial score
Player1score = 0
Player2score = 0

#start game - what happens when you push start button (reset velocity and scores)
def startgame():
    global dy, dx, Player1score, Player2score
    canv.coords(paddle1, 0,200,10,120)
    canv.coords(paddle2, 590,200,600,120)
    dx = 2
    dy = 0
    Player1score = 0
    Player2score = 0
    Player1scoreLabel.configure(text="Score: "+ str(Player1score))
    Player2scoreLabel.configure(text="Score: "+ str(Player2score))
    moveBall()

#Ball Movement
def moveBall():
    global dy, dx, Player1score, Player2score
#    to make ball bounce off paddle 1
    if canv.coords(ball)[0]<=canv.coords(paddle1)[2] and canv.coords(paddle1)[1]<= canv.coords(ball)[1] <= canv.coords(paddle1)[3]:        
        dx = -dx
        if canv.coords(paddle1)[1] <= canv.coords(ball)[1] <= (int((canv.coords(paddle1)[1] + canv.coords(paddle1)[3])) / 2 ):
            dy -=1
            canv.move(ball, dx, dy)
        elif (int(canv.coords(paddle1)[1] + canv.coords(paddle1)[3]) / 2 ) <= canv.coords(ball)[3] <= canv.coords(paddle1)[3]:
            dy += 1
            canv.move(ball, dx, dy)
        else:
            canv.move(ball, dx, dy)
#    to make ball bounce off paddle 2
    elif canv.coords(ball)[2]>=canv.coords(paddle2)[0] and canv.coords(paddle2)[1]<= canv.coords(ball)[3] <= canv.coords(paddle2)[3]:
        dx = -dx
        if canv.coords(paddle2)[1] <= canv.coords(ball)[1] <= (int((canv.coords(paddle2)[1] + canv.coords(paddle2)[3])) / 2 ):
            dy -= 1
            canv.move(ball, dx, dy)
        elif (int(canv.coords(paddle2)[1] + canv.coords(paddle2)[3])/ 2 ) <= canv.coords(ball)[3] <= canv.coords(paddle2)[3]:
            dy += 1
            canv.move(ball, dx, dy)
        else:
            canv.move(ball, dx, dy)
#     to make ball bounce off roof
    elif canv.coords(ball)[1]<=0:
        dy = -dy
        canv.move(ball, dx, dy)
#        to mkae ball bounce of floor
    elif canv.coords(ball)[1]>=325:
        dy = -dy
        canv.move(ball, dx, dy)
#        if player 2 scores
    elif canv.coords(ball)[2]<=0:
        Player2score += 1
        Player2scoreLabel.configure(text="Score: "+ str(Player2score))
        canv.coords(ball, 300,160,310,170)
        canv.coords(paddle1, 0,200,10,120)
        canv.coords(paddle2, 590,200,600,120)
        dx=2
        dy=0
#        if player1 scores
    elif canv.coords(ball)[0]>=600:
        Player1score += 1
        Player1scoreLabel.configure(text="Score: "+ str(Player1score))
        canv.coords(ball, 300,160,310,170)
        canv.coords(paddle1, 0,200,10,120)
        canv.coords(paddle2, 590,200,600,120)
        dx=-2
        dy=0
#        end game if player 1 wins
    elif Player1score==3:
        dx=0
        dy=0
#        end game if player 2 wins
    elif Player2score==3:
        dx=0
        dy=0
#        move ball if nothign happens
    else:        
        canv.move(ball, dx, dy)
    canv.after(10, moveBall)

#buttons
Butframe = Frame(relief=SUNKEN, width=200, height = 150, background="white")
Butframe.pack()
startButton = Button(Butframe, text="Start", command = startgame)
startButton.pack(side=LEFT)
quitButton = Button(Butframe, text="Quit", command=root.destroy)
quitButton.pack(side=LEFT)

#scores
Score1frame = Frame(relief=SUNKEN, width=200, height = 150, background="white")
Score1frame.pack(side=LEFT)    
Player1scoreLabel = Label(Score1frame, text="Score: "+ str(Player1score), background="green")
Player1scoreLabel.pack()
Score2frame = Frame(relief=SUNKEN, width=200, height = 150, background="white")
Score2frame.pack(side=RIGHT) 
Player2scoreLabel = Label(Score2frame, text="Score: "+ str(Player2score), background="green")
Player2scoreLabel.pack()

#binding of movement keys    
root.bind("<Up>", moveUp2)
root.bind("<w>", moveUp1)
root.bind("<Down>", moveDown2)
root.bind("<s>", moveDown1)
root.mainloop()

1 个答案:

答案 0 :(得分:0)

您的明显速度增加是由于对.after()方法的重叠调用造成的。

当其中一个玩家获胜时,您应该在moveBall()中停止循环,例如使用名为gameover的全局变量,如下所示:

# Initialize gameover variable
gameover = False

# (...) (Reset gameover to False in startgame() as well)

def moveBall():
    global dy, dx, Player1score, Player2score, gameover

    # (...)

    # end game if player 1 or 2 wins
    elif Player1score==3 or Player2score==3:
        dx=0
        dy=0
        gameover = True
    # move ball if nothing happens
    else:        
        canv.move(ball, dx, dy)

    # Repeat until game is over
    if not gameover:
        canv.after(10, moveBall)