要求:小球撞击到墙壁的时候,会反弹,当碰到球拍的时候,也会反弹,如果碰到底部的时候,游戏结束,输出总共碰撞了多少次。
控制程序运行的类(paddleball.py)
#!/usr/bin/python
#coding: utf-8
#from __future__ import unicode_literals
from Tkinter import *
# from the_ball import Ball
import random
import time
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, 250, 400)
# x为左右移动的时候每一步的距离
self.x = 0
# 左右移动的速度
self.speed = 2
# 获取画布的宽度
self.canvas_width = self.canvas.winfo_width()
# 处理事件,当点击向左向右的时候作出反应
self.canvas.bind_all('<KeyPress-Left>', self.turn_left)
self.canvas.bind_all('<KeyPress-Right>', self.turn_right)
self.canvas.bind_all('<KeyPress-Down>', self.reduce_speed)
self.canvas.bind_all('<KeyPress-Up>', self.increase_speed)
def draw(self):
self.canvas.move(self.id, self.x, 0)
pos = self.canvas.coords(self.id)
# 设置如果碰到边界就自动反弹
if pos[0] <= 0:
self.x = self.speed
elif pos[2] >= self.canvas_width:
self.x = -self.speed
def turn_left(self, event):
self.x = -self.