栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

弹跳的小球实训报告(小球弹跳动画)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

弹跳的小球实训报告(小球弹跳动画)

弹跳的小球(Python)

看看效果吧!代码

看看效果吧!

代码
# 安装以下几个库
# pip install pygame
# pip install pgzero
# pip install keyboard
import pgzrun # 导入游戏库
import keyboard

WIDTH = 640 # 设置窗口宽度
HEIGHT = 480 # 设置窗口高度
TITLE = '弹跳的小球' # 窗口标题
r = 20 # 设置小球的半径
c_x = 180 # 设置小球的起始坐标x
c_y = 100 # 设置小球的起始坐标y
r_x = 0 #滑块的移动
speed_x = 3 # 设置小球x轴方向
speed_y = 5 #设置小球y轴方向
r_speed = 5 #设置滑块的移动速度
flag = 1 # 设置一个标志,来判断游戏失败

# 绘制函数
def draw():
    rect = Rect((260 + r_x, 330), (120, 20)) #矩形的坐标,大小
    if flag:
        screen.fill('yellow') # 修改背景颜色
        # screen.draw.circle((400,300),100,'white')# 画一个空心圆
        screen.draw.filled_circle((c_x,c_y),r,'red') # 画一个实心圆
        # screen.draw.rect(rect,'red') # 画一个空心矩形
        screen.draw.filled_rect(rect,"red") # 画一个实心矩形
    else:
        screen.clear() # 清屏
        screen.draw.text('Game Over!',(130,150),fontsize=100,color='red') #画文本
        screen.draw.text('游戏失败',(130,250),fontsize=100,fontname="simhei",color='yellow')

# 更新函数,当程序运行后,每帧都会执行一次该函数
def update():
    global c_x,c_y,speed_x,speed_y,r,r_x,flag # 表示全局变量
    c_x += speed_x # 小球移动
    c_y += speed_y
    if c_x >= WIDTH -r or c_x <= r: # 如果小球撞到窗口就改变方向
        speed_x = -speed_x
    if c_y > HEIGHT - r or c_y <= r:
        speed_y = -speed_y
    if keyboard.is_pressed('a') and r_x >= -260: # 当按下a键,滑块左移,并当碰到窗口左壁时停止左移
        r_x -= r_speed
    if keyboard.is_pressed('d') and r_x <= 260: # 当按下d键,滑块右移,并当碰到窗口右壁时停止右移
        r_x += r_speed
    if c_x >= 260 + r_x and c_x <= 380 + r_x and c_y >= 325 and c_y <= 330: #如果小球碰到滑块就反弹
        speed_x = -speed_x
        speed_y = -speed_y
    if c_y == HEIGHT - r: # 如果小球碰到窗口底端,标志位置零,游戏结束
        flag = 0
pgzrun.go() # 开始执行游戏
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/772766.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号