简易打砖块游戏框架

这是一个完整的打砖块小游戏,有封面.小球类从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)

You must log in to read the rest of this article. Please log in or register as a user.