3.8完成持续反弹
现在我们完成反弹后到达顶部的反弹。下面是我们要做的事情。
1、理解顶部反弹的数学意义是:position[3]<=0。
2、当position[3]<=0改变方向的参数值。
实现代码如下:
class ball:
def init(self,canvas,color):
self.canvas=canvas
self.a=random.randint(50,600)
self.b=random.randint(50,200)
self.id=canvas.create_oval(self.a, self.b, self.a+20, self.b+20, fill =color)
def draw(self):
global direction
position=canvas.coords(self.id)
if position[3]<=0:
direction=1
if position[3]<800 and direction==1:
self.canvas.move(1,0,5)
if position[3]<800 and direction==0 and position[3]>0:
self.canvas.move(1,0,-5)
global direction:direction前面加globald的作用时:变量可以在其它类中修改它的值。
将代码整合起来,整合后完整代码如下:
#-- coding:GBK --
from tkinter import *
import time
import random
import tkinter.messagebox #messagebox
closeornot=1
direction=1
position=[1,1,1,1]
tk = Tk()
tk.title(“雷雷的弹球游戏”)
tk.resizable(0, 0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=800, height=800, bd=0, highlightthickness=0)
canvas.pack()
class racket:
def init(self,canvas,color,ball):
self.canvas=canvas
self.x=0
self.id=canvas.create_rectangle(400, 600, 500, 620, fill =color)
self.canvas.bind_all(’’, self.turn_left)
self.canvas.bind_all(’’, self.turn_right)
self.ball=ball
def turn_left(self,evt):
self.x=-5
def turn_right(self, evt):
self.x = 5
def draw(self):
pos = self.canvas.coords(self.id)
if pos[0] <= 0:
self.x = 0
if pos[0]>=700:
self.x=0
self.canvas.move(self.id,self.x,0)
if self.collision(pos)==True:
global direction
direction=0
def collision(self,pos):
posball = self.canvas.coords(self.ball.id)
if posball[1]>=pos[1]:
return True
return False
class ball:
def init(self,canvas,color):
self.canvas=canvas
self.a=random.randint(50,600)
self.b=random.randint(50,200)
self.id=canvas.create_oval(self.a, self.b, self.a+20, self.b+20, fill =color)
def draw(self):
global direction
position=canvas.coords(self.id)
if position[3]<=0:
direction=1
if position[3]<800 and direction==1:
self.canvas.move(1,0,5)
if position[3]<800 and direction==0 and position[3]>0:
self.canvas.move(1,0,-5)
ball=ball(canvas,‘red’)
racket=racket(canvas,‘green’,ball)
while 1:
racket.draw()
ball.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.05)
运行这段代码,我们可以看到球在顶部与球板水平的位置间来回运动。见图3-22、3-23、3-24
图3-22
图3-23
图3-24