简易打砖块游戏框架

这是一个完整的打砖块小游戏,有封面.小球类从ball模块导入,砖块类从brick模块导入。

"""
   打砖块小游戏.py
   按方向箭头或用鼠标指针拖曳拦板去接小球,按回车键开始游戏.
"""
# 会员可直接向李兴球博主索取源代码,其它文章省略的代码也一样.
from ball import * 
from brick import *
from time import sleep
from random import randint,choice
       
def start_game(screen,writer ):
    """生成拦板,绑定按键,小球和砖块,让小球不断移动。"""
    writer.clear()                       # 按回车键后清除所写的标题
    screen.onkeypress(None,"Return")     # 取消回车键事件绑定
    screen.bgcolor("white")              # 重设背景色为白
    height = screen.window_height()      # 得到屏幕高度
    board  = Turtle(shape = 'square')    # 新建形状为square的方形体
    board.shapesize(1,10)                # 长方形的长度为200x20像素     
    board.penup()                        # 抬笔
    board.color("blue")                  # 设颜色
    board.sety(50-height/2)              # 把拦板y坐标定位
    def move_to_right():
        board.setx(board.xcor() + 10)    # x坐标右移10个单位        
    def move_to_left():
        board.setx(board.xcor() - 10)    # x坐标左移10个单位        
    
    screen.onkeypress(move_to_right,"Right")# 绑定右方向箭头
    screen.onkeypress(move_to_left,"Left")  # 绑定左方向箭头
    board.ondrag(lambda x,y:board.setx(x))  # 绑定拖动事件

    all_balls = [Ball() for i in range(2)]  # 生成两个球
    rows  = 4
    cols = 6
    Brick.amounts = rows * cols             # 类变量,砖块所有数量
    startpos = (-120,160)                   # 所有砖块的起点坐标
    for r in range(rows):                   # 一行一行的排砖块
        for c in range(cols):               # 一行之中的每一块砖
            x = startpos[0] + c * 50        # 设定x坐标
            y = startpos[1] - r * 40        # 设定y坐标
            Brick('magenta',(x,y),all_balls)# 生成砖块   
    while True:
        for ball in all_balls:
            if ball.isvisible():ball.move(board)
            screen.update()
            sleep(0.01)
            
def main():
    """新建屏幕,显示标题,按回车键开始游戏"""
    title = "打砖块小游戏"
    width,height = 480,360
    screen = Screen()                        # 新建屏幕
    screen.delay(0)                          # 延时为0
    screen.bgcolor("black")                  # 背景为黑
    screen.title(title)                      # 标题为title
    screen.setup(width,height)               # 设定宽高
    
    w = Turtle(visible=False)                # 用来写标题的海龟
    w.color("cyan")                          # 颜色为青色
    w.penup()                                # 抬笔
    w.write(title,align='center',font=("楷体",32,"normal"))
    w.sety(-100)                             # 下移100个单位
    w.color("gray")                          # 颜色为灰色
    w.write("按回车键开始",align='center',font=("黑体",12,"normal"))   

    # 绑定回车到匿名函数
    screen.onkeypress(lambda:start_game(screen,w),"Return") 
    screen.listen()                          # 监听屏幕(设置焦点) 
    screen.mainloop()                        # 进入主循环
    
if __name__ == "__main__":

    main()