编写一个弹跳小球的程序,小球在窗口中四处反弹(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()函数刷新屏幕。

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

相关推荐
想做富婆9 分钟前
python入门:简单介绍和python和pycharm软件安装/学习网址/pycharm设置(改成中文界面,主题,新建文件)
python·学习·pycharm
Start_Present9 分钟前
Pytorch 第十四回:神经网络编码器——变分自动编解码器
pytorch·python·深度学习·神经网络·数据分析
Jwoka1 小时前
正则表达式学习笔记
笔记·python·正则表达式·re
移远通信1 小时前
智能硬件开发革命:低代码平台+物联网
python·物联网·低代码·智能硬件
亚林瓜子1 小时前
python的web框架flask(hello,world版)
python·flask·conda·web·python3
IT从业者张某某2 小时前
Python数据可视化-第7章-绘制3D图表和统计地图
python·3d·信息可视化
攻城狮7号2 小时前
Python爬虫第13节-解析库pyquery 的使用
爬虫·python·python爬虫
在线打码3 小时前
禅道MCP Server开发实践与功能全解析
python·ai·禅道·deepseek·mcp·zentao·mcp server
恶霸不委屈3 小时前
重新定义健康监护!基于DeepSeek的人体生理状况智能检测装置技术解析
人工智能·python·deepseek·生理监测
我感觉。3 小时前
Anaconda环境管理及 pycharm、jupyter notebook 的配置
开发语言·pytorch·python·深度学习