python弹球游戏完整版

2021-07-21  本文已影响0人  peter_ffec

from tkinterimport *

import time

import random

#弹球游戏1:小球在屏幕上反弹

#canvas画布

#类Ball

class Ball:

def __init__(self,canvas,paddle,color):

# print("begin create ball:",type(canvas),color)

        self.canvas=canvas

self.paddle=paddle

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 #每次向上移动3个像素

        self.canvas_height=self.canvas.winfo_height()#获取画布当前高度

        self.canvas_width=self.canvas.winfo_width()#获取画布当前宽度

        self.hit_bottom=False

    def hit_paddle(self,pos):

paddle_pos=self.canvas.coords(self.paddle.id)

if pos[2]>=paddle_pos[0]and pos[0]<=paddle_pos[2]:

if pos[3] >= paddle_pos[1]and pos[3] <= paddle_pos[3]:

return True

return False

    #反弹实现,用重复的移动绘制角色实现

    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.hit_bottom=True  #遇到下边缘,向上走

#判断是否碰到paddle

        if self.hit_paddle(pos)==True:

self.y=-3

        if pos[0]<=0:

self.x=3  #遇到左边缘,向右走

        if pos[2]>=self.canvas_width:

self.x=-3  #遇到右边缘,向左走

class Paddle:

def __init__(self,canvas,color):

self.canvas = canvas

self.id =canvas.create_rectangle(0,0,100,10,fill=color)

self.canvas.move(self.id,200,300)

self.x=0

        self.canvas_width=self.canvas.winfo_width()

self.canvas.bind_all('<KeyPress-Left>',self.turn_left)#这里只把函数名传进来,并没有传turn_left()

        self.canvas.bind_all('<KeyPress-Right>',self.turn_right)

def draw(self):

self.canvas.move(self.id,self.x,0)#只能左右移动

        pos =self.canvas.coords(self.id)# 获取画布上某一个椭圆形当前位置坐标[x1,y1,x2,y2]两组坐标

        if pos[0] <=0:

self.x =0  # 遇到上边缘,向下走

        elif pos[2] >=self.canvas_width:

self.x =0  # 遇到下边缘,向上走

    def turn_left(self,evt):

self.x=-2

    def turn_right(self,evt):

self.x=2

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()#动画初始化

paddle=Paddle(canvas,'black')

ball = Ball(canvas,paddle,'red')#把画布保存到对象变量中,准备在它上面画球

#循环动画,避免窗口马上关闭

while True:

if ball.hit_bottom==False:

ball.draw()

paddle.draw()

#重画图像

    tk.update_idletasks()

tk.update()

#等待一会

    time.sleep(0.01)

#关闭主窗口

tk.mainloop()# stops mainloop

上一篇 下一篇

猜你喜欢

热点阅读