from tkinter import *
import time
import random
弹球游戏1:小球在屏幕上反弹
canvas画布
类Ball
class Ball:
def init(self,canvas,color):
# print("begin create ball:",type(canvas),color)
self.canvas=canvas
self.id=canvas.create_oval(10,10,25,25,fill=color) #,绘制带颜色和上下坐标的椭圆形oval,保存小球ID
self.canvas.move(self.id,250,100) #用x方向和y方向位移,让小球移动到中心位置(500/2; 200/2)
starts=[-3,-2,-1,1,2,3]
random.shuffle(starts) #重新洗牌,对随机数重新放置
self.x=starts[0]
self.y=-3
self.canvas_height=self.canvas.winfo_height() #获取画布当前高度
self.canvas_width=self.canvas.winfo_width() #获取画布当前宽度
#反弹实现,用重复的移动绘制角色实现
def draw(self):
self.canvas.move(self.id,self.x,self.y)
pos=self.canvas.coords(self.id) #获取画布上某一个椭圆形当前位置坐标[x1,y1,x2,y2]两组坐标
if pos[1]<=0:
self.y=3 #遇到上边缘,向下走
if pos[3]>=self.canvas_height:
self.y=-3 #遇到下边缘,向上走
if pos[0]<=0:
self.x=3 #遇到左边缘,向右走
if pos[2]>=self.canvas_width:
self.x=-3 #遇到右边缘,向左走
tk = Tk()
tk.title('弹球游戏')
tk['width']=400
tk['height']=300
tk.resizable(False,False) #窗口大小不能调整,也可以用0替代False
tk.wm_attributes("-topmost",1) #此窗口放到其他所有窗口之前
canvas = Canvas(tk,width=500,height=400,bd=0,highlightthickness=0) #后面两个具名函数 bd high...表示画笔之外无边框
canvas.pack() #调整画布大小
tk.update() #动画初始化
ball = Ball(canvas,'red') #把画布保存到对象变量中,准备在它上面画球
循环动画,避免窗口马上关闭
while True:
ball.draw()
#重画图像
tk.update_idletasks()
tk.update()
#等待一会
time.sleep(0.01)
关闭主窗口
tk.mainloop() # stops mainloop
网友评论