import sys
import pygame as py
import time

#初始化
py.init()
py.display.init()

#创建屏幕
a=py.display.set_mode((400,320))
running = True
#设置小球x、y坐标
ball_x = 200
ball_y = 240
#设置小球x、y坐标速度
ball_x_speed = 2
ball_y_speed = -3
# 显示小球
ball = py.draw.circle(a, 'blue', (ball_x, ball_y), 10)
#创建球拍
qp = py.Rect(160,270,80,20)
#设置分数
poins = 0
#砖块列表
zk_list = []
#把砖块添加砖块列表
for j in range(3):
    for i in range(5):
        r = py.Rect(i*78+14,j*45+35,60,37)
        zk_list.append(r)
while running:
    # a的背景设为(238,238,238)
    a.fill((238,238,238))
    #判断退出事件
    for e in py.event.get():
        if e.type == py.QUIT:
            running = False
    #球拍的移动
    keys = py.key.get_pressed()#py.key.get_pressed() : 所有按钮是否按下的逻辑值以序列的形式的变量
    if keys[py.K_LEFT] and qp.x > 0 :#py.K_LEFT : 左方向键
        qp.x -= 5
    if keys[py.K_RIGHT] and qp.x < 320 :#py.K_RIGHT : 右方向键
        qp.x += 5
    #球碰到边界的反弹
    if ball_x > 390 or ball_x < 10:
        ball_x_speed = - ball_x_speed
    if ball_y < 10:
        ball_y_speed = - ball_y_speed
    #球碰到球拍的反弹
    if ball.colliderect(qp):#判断球是否碰到球拍
        ball_y_speed = -ball_y_speed
    #球的移动
    ball_x = ball_x + ball_x_speed
    ball_y = ball_y + ball_y_speed
    #球打碎砖块
    for r in zk_list:
        if ball.colliderect(r):#判断球是否碰到砖块
            ball_y_speed = -ball_y_speed
            zk_list.remove(r)
            poins += 1
    # 球碰到下边界
    if ball_y > 310:
        # 终断循环
        running = False
    # 球打完了砖块
    if not zk_list :
        # 创建字体(完美)
        text = py.font.Font(None, 50).render('prefect!!', True, (0, 0, 0))
        # 显示字体(完美)
        a.blit(text, (150, 100))
        time.sleep(5)
        #终断循环
        running = False
    # 画出所有砖块
    for zk in zk_list:
        py.draw.rect(a, 'red', zk)
    # 显示球拍
    py.draw.rect(a, (0, 0, 0), rect=qp)
    # 显示小球
    ball = py.draw.circle(a, 'blue', (ball_x, ball_y), 10)
    # 创建字体(得分)
    text = py.font.Font(None, 30).render(f'poins:{poins}', True, (0, 0, 0))
    # 显示字体(得分)
    a.blit(text, (10, 10))
    #更新显示
    py.display.flip()
    # 把帧率设为100(一帧为每秒更新1篇画面)
    py.time.Clock().tick(50)
#pygame初始化
py.quit()
#结束系统进程
sys.exit()