编写一个弹跳小球的程序,小球在窗口中四处反弹(python)

python 复制代码
import pygame
import random

# 初始化Pygame
pygame.init()

# 窗口尺寸
width = 800
height = 600

# 创建窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball")

# 小球初始位置和速度
ball_radius = 20
ball_color = (255, 0, 0)
ball_pos = [random.randint(ball_radius, width - ball_radius), random.randint(ball_radius, height - ball_radius)]
ball_speed = [random.randint(1, 5), random.randint(1, 5)]

# 游戏主循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # 更新小球位置
    ball_pos[0] += ball_speed[0]
    ball_pos[1] += ball_speed[1]
    
    # 检测小球与窗口边界碰撞
    if ball_pos[0] < ball_radius or ball_pos[0] > width - ball_radius:
        ball_speed[0] = -ball_speed[0]
    if ball_pos[1] < ball_radius or ball_pos[1] > height - ball_radius:
        ball_speed[1] = -ball_speed[1]
    
    # 填充背景色
    screen.fill((0, 0, 0))
    
    # 绘制小球
    pygame.draw.circle(screen, ball_color, (int(ball_pos[0]), int(ball_pos[1])), ball_radius)
    
    # 刷新屏幕
    pygame.display.flip()

# 退出游戏
pygame.quit()

在这个程序中,使用random模块来随机生成小球的初始位置和速度。然后,在主循环中,不断更新小球的位置,并检测小球是否与窗口边界发生碰撞,如果发生碰撞,则反转小球的速度。然后,使用pygame.draw.circle()函数来绘制小球,并使用pygame.display.flip()函数刷新屏幕。

运行这段代码后,将看到一个窗口中弹跳的小球。小球会在窗口中四处移动并反弹,直到关闭窗口为止。可以根据需要调整窗口大小、小球的半径、颜色以及移动速度等参数来定制属于自己的弹跳小球游戏。

相关推荐
beethobe6 小时前
PythonQt 学习之旅(一):从零构建 C++ 与 Python 的桥梁
c++·python·学习
广州智造6 小时前
如何在HyperMesh运行Python脚本及查找Python API帮助
python·仿真·cae·hypermesh·optistruct
cooldog123pp7 小时前
cplex完全安装手册,适配matlab和python!
人工智能·python·matlab·cplex
TechWayfarer7 小时前
苏超赛事网站安全防护:WAF、DDoS与仿冒页面如何联动治理
网络·python·安全·flask·ddos
huzhongqiang7 小时前
单例装饰器升级:用 jsonic 过滤私有字段
python
云梦泽࿐้7 小时前
变量与数据类型:Python世界的基石
开发语言·python
开发小能手-roy7 小时前
Lambda表达式性能陷阱:避坑指南与JIT编译优化分析
开发语言·python
风吹夏回7 小时前
RabbitMQ 核心术语 + Python pika 方法完整讲解
分布式·python·rabbitmq
爱读书的小胖7 小时前
无偿分享ChatGPT Image 2画图网页与并发绘图python程序【Ai绘图】
开发语言·python·chatgpt
cvcode_study7 小时前
Scikit-learn
python·机器学习·scikit-learn