python中的tkinter
好吧,所以我正在尝试制作2个玩家的乒乓球游戏,到目前为止,我遇到了3个问题。老实说,这是我无法转过头的第三个(如果您想查看问题出现的位置,请找到 #Ball Movement Logic )
#Setting up the window
from tkinter import *
HEIGHT=500
WIDTH=800
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
#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():
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)
move_ball()
问题是,每当我运行此操作时,我会收到以下错误消息:
Traceback (most recent call last):
File "/Users/jackstrange/Documents/Untitled.py", line 79, in <module>
move_ball()
File "/Users/jackstrange/Documents/Untitled.py", line 50, in move_ball
c.move(ballplay, ballX, ballY)
UnboundLocalError: local variable 'ballY' referenced before assignment
我可能缺少的是,这是一个非常基本的,例如使用返回命令之类的东西,但是让我感到困惑的是为什么Ballx可以工作,但Bally却没有。一些帮助会很好:D
问题是 c.move will change ballx 和 bally的值。如果要更改全局变量,则必须在功能中声明全局。你没有那样做;因此,您功能中的 ballx/y 是局部变量。
鉴于这一点,错误更容易理解:您没有定义 local 变量 ballx/y 。
这只是取决于全球变量的许多危险之一。
要解决这个问题,我怀疑您需要做的就是在功能的顶部添加一行:
global ballX, ballY
将您的def move_ball()
声明更改为def move_ball(ballX, ballY)
,然后使用move_ball(ballX, ballY)