我有下面的代码,设法使一个球反弹的顶部和底部的屏幕。在
上下跳动的工作代码
from tkinter import *
import random
import time
class Ball:
def __init__(self,canvas,color):
self.canvas=canvas
self.id=canvas.create_oval(30,30,50,50,fill=color)
self.canvas.move(self.id,100,200)
#ADD THESE LINES TO OUR __INIT__ METHOD
self.x=0
self.y=-1
self.canvas_height=self.canvas.winfo_height()
def draw(self):
self.canvas.move(self.id,self.x,self.y)
pos=self.canvas.coords(self.id)
if pos[1] <=0:
self.y=1
if pos[3] >=self.canvas_height:
self.y=-1
def main():
tk=Tk()
tk.title("My 21st Century Pong Game")
tk.resizable(0,0)
tk.wm_attributes("-topmost",1)
canvas=Canvas(tk,bg="white",width=500,height=400,bd=0,highlightthickness=0)
canvas.pack()
tk.update()
ball1=Ball(canvas,'green')
while 1:
tk.update()
ball1.draw() #call the ball draw method here
time.sleep(0.01)
main()
当我试图从左到右(在左墙和右墙上弹跳)时,我不能很好地理解逻辑或解决我的错误,如下所示。在
我尝试过的左右跳跃
^{pr2}$要得到答案
有人能提供一个简单的解释关于解决问题所需的逻辑,坐标从哪里来,pos[0]、pos[1]等指的是什么。我有一个想法,但它一点也不清楚,而且会从某种程度上受益(正如我想象的那样)。在
所以,我正在寻求一个解释+编码的解决方案修复(使用我的原始代码)来解决问题。在
代码几乎是正确的。事实上,这几乎是对的,如果你再仔细想一想,也许就能给你答案了。“移动x”代码已从“移动y”代码复制粘贴,但更改不够。小心这样做。在
为了回答“pos[0]等是什么意思”,我邀请您阅读Get coords of an oval in Tkinter。 通常,矩形的坐标是(左,上,右,下)。在
您会注意到,除了纠正您的错误之外,我还更改了以下一些内容:
x
&;y
变量改为vx
和{move
,而不是draw
,因为函数移动而不绘制。在tk.protocol
行的alive
变量为程序在用户关闭窗口后提供了一种整洁的清理方法。在一。在
相关问题 更多 >
编程相关推荐