使用tkinter模拟反弹球游戏
背景
最近在练习使用tkinter编写一些小的图形化程序,看看tkinter的基础语法,并实践一下,这一次是模拟一个反弹球游戏,算是最近这段时间tkinter实践的收尾
目的
使用tkinter模拟反弹球游戏
环境
python3.7+win7
程序设计思路
1.定义2种类,Ball和Racket;ball代表反弹球,racket代表可移动接球板 2.通过定义Ball类ball_move()方法和__init__()方法分别定义ball的移动和ball的初始化设置 3.通过定义Racket类__init__()方法和racket_move(),move_left(),move_right()方法分别定义racket的初始化设置及racket向左,向右移动需要涉及的操作
程序说明
# -*- coding:utf-8 -*-
"""
-------------------------------------------------
File Name: spring_ball.py
Author : ZhaiMingyu
date: 2020/9/20
-------------------------------------------------
"""
from tkinter import *
from tkinter import messagebox
import time
from random import *
class Ball(): #定义Ball类
def __init__(self,canvas,win_width,win_height,step,racket):
self.canvas = canvas
self.racket = racket
self.notTouchBottom = True #球没接触到底端初始值为真
self.id = canvas.create_oval(0,0,20,20,fill='yellow') #获取球对象
self.canvas.move(self.id,win_width/2,win_height/2) #球移动到画布中间
start_p=[-4,-3,-2,-1,1,2,3,4] #球最初x轴位移
shuffle(start_p) #打乱x轴位移值
self.x = start_p[0] #从上面打乱值中取一个数值当作球每次横向位移值
self.y = step #球每次纵向位移值
self.win_width = win_width
self.win_height = win_height
def ball_move(self):
self.canvas.move(self.id,self.x,self.y)
ball_pos = self.canvas.coords(self.id)
if ball_pos[0] <= 0: #球出了左边界
self.x = step
if ball_pos[1] <= 0 : #球出了上边界
self.y = step
if ball_pos[2] >= self.win_width: #球出了右边界
self.x = -step
if ball_pos[3] >= self.win_height: #球出了下边界
self.y = -step
if self.hit_racket(ball_pos) == True: #当球被接住时
self.y = -step
if ball_pos[3] >=self.win_height: #当球没被接住时
self.notTouchBottom = False
messagebox.showinfo("","You lose!!!\nRestart again!")
def hit_racket(self,ball_pos): #判断球是否被接住
racket_pos = self.canvas.coords(racket.id)
if ball_pos[2] >= racket_pos[0] and ball_pos[0] <= racket_pos[2] and ball_pos[3] >= racket_pos[1] and ball_pos[3]<= racket_pos[3]:
return True
else:
return False
class Racket(): #定义Racket类
def __init__(self,canvas,win_width,win_height):
self.canvas = canvas
self.x = 0
self.canvas.bind_all('<KeyPress-Right>',self.move_right) #绑定键盘触发右键处理函数
self.canvas.bind_all('<KeyPress-Left>',self.move_left) #绑定键盘触发左键处理函数
self.id = canvas.create_rectangle(0,0,100,15,fill='blue')
self.canvas.move(self.id,win_width/2-40,win_height-30)
def move_right(self,event): #接球拍向右移动每次移动4像素
self.x = 4
def move_left(self,event): #接球拍向左移动每次移动4像素
self.x = -4
def racket_move(self): #定义接球拍的移动
self.canvas.move(self.id,self.x,0)
if self.canvas.coords(self.id)[0] <= 0: #接球拍左边出界时不移动
self.x = 0
if self.canvas.coords(self.id)[2] >=width: #接球拍右边出界时不移动
self.x = 0
root = Tk()
width = 300
height = 300
step = 3
speed = 0.03
canvas = Canvas(root, width=width, height=height)
racket = Racket(canvas,width,height) #接球拍的定义
ball = Ball(canvas,width,height,step,racket) #球的定义
root.update()
canvas.pack()
while ball.notTouchBottom: #球没接触底端的情况下
ball.ball_move()
racket.racket_move()
time.sleep(speed)
root.update()
root.mainloop()
动态图
声明:本博客的原创文章,都是本人平时学习所做的笔记,转载请标注出处,谢谢合作。