我试图在Python和Tkinter的帮助下编写一个简单的Arkanoid。目标是使球从顶部、右侧和左侧反射。如果球员错过了球,球碰到了底部,比赛就会停止。
代码如下:
from Tkinter import *
import time
root = Tk()
canv = Canvas(root, highlightthickness=0)
canv.pack(fill='both', expand=True)
top = canv.create_line(0, 0, 640, 0, fill='green', tags=('top'))
left = canv.create_line(0, 0, 0, 480, fill='green', tags=('left'))
right = canv.create_line(639, 0, 639, 480, fill='green', tags=('right'))
bottom = canv.create_line(0, 478, 640, 478, fill='red', tags=('bottom'))
rect = canv.create_rectangle(270, 468, 365, 478, outline='black', fill='gray40', tags=('rect'))
ball = canv.create_oval(0, 20, 20, 40, outline='black', fill='gray40', tags=('ball'))
delta_x = delta_y = 3
new_x, new_y = delta_x, -delta_y
while True:
time.sleep(0.025)
if canv.find_overlapping(canv.coords(ball)[0], canv.coords(ball)[1], canv.coords(ball)[2], canv.coords(ball)[3])[0] == 1:
new_x, new_y = delta_x, -delta_y
canv.move(ball, new_x, new_y)
print 'fitst if', new_x, new_y
if canv.find_overlapping(canv.coords(ball)[0], canv.coords(ball)[1], canv.coords(ball)[2], canv.coords(ball)[3])[0] == 2:
new_x, new_y = delta_x, delta_y
canv.move(ball, new_x, new_y)
print '2nd if', new_x, new_y
if canv.find_overlapping(canv.coords(ball)[0], canv.coords(ball)[1], canv.coords(ball)[2], canv.coords(ball)[3])[0] == 3:
new_x, new_y = -delta_x, delta_y
canv.move(ball, new_x, new_y)
if canv.find_overlapping(canv.coords(ball)[0], canv.coords(ball)[1], canv.coords(ball)[2], canv.coords(ball)[3])[0] == 4:
new_x, new_y = delta_x, -delta_y
canv.move(ball, new_x, new_y)
print new_x, new_y
canv.move(ball, new_y, new_y)
canv.update()
def move_right(event):
canv.move(rect, 7, 0)
pass
def move_left(event):
canv.move(rect, -7, 0)
pass
root.bind('<Right>', move_right)
root.bind('<Left>', move_left)
root.geometry('%sx%s+%s+%s' %(640, 480, 100, 100))
root.resizable(0, 0)
root.mainloop()
为什么球反射的方向不对?
下面是解决这个问题的一个简单方法:
要移动对象,需要使用
coords
方法或move
方法,该方法更改对象的坐标。可以使用coords
方法获取当前坐标。要制作动画,可以使用
after
。调用一个函数,然后让它在不久的将来使用after
再次调用自己。在未来的多远将决定你的帧速率(即:每10毫秒意味着大约每秒100帧)例如:
一旦您只调用一次
moveit()
,循环就开始了。同一个方法可以用于更新多个对象,也可以为不同的对象使用不同的方法。编辑:您的问题已经完全从“如何在画布上移动某些内容?”为什么它会朝错误的方向移动。后者的答案很简单:你告诉它往错误的方向发展。使用调试器或一些打印语句查看计算增量的位置和方式
相关问题 更多 >
编程相关推荐