汇智学堂-python小游戏(弹球游戏之七-场景中理解反弹)

3.7场景中理解反弹
现在我们要在画布上体会一下弹球的含义。我们设定一个球从空中降落,当它与球板的水平位置平行时,让它产生一个反弹的动作。下面是我们要做的事情。
1、球的降落动画。
2、平行时,反弹回去。

实现代码如下:

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
    #tkinter.messagebox.showinfo('提示',pos[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

函数collision作用是判断球与球板是否在同一水平线上。
将代码整合起来,整合后完整代码如下:

#-- 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
    #tkinter.messagebox.showinfo('提示',pos[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):
position=canvas.coords(self.id)
if position[3]<800 and direction1:
self.canvas.move(1,0,5)
if position[3]<800 and direction
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-19),当到达图3-20位置时,开始反弹。反弹后见图3-21。
特别说明:每次运行的结果不一样。
在这里插入图片描述

图3-19
在这里插入图片描述
图3-20
在这里插入图片描述
图3-21

猜你喜欢

转载自blog.csdn.net/weixin_39593940/article/details/88361907