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

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

相关推荐
deephub9 分钟前
告别脆弱的单体应用,用多智能体网络构建稳定的生产力工具
人工智能·python·大语言模型·多智能体
烟雨江南aabb11 分钟前
Python第六弹:python爬虫篇:什么是爬虫
开发语言·爬虫·python
MomentYY15 分钟前
第 1 篇:Agent 到底是什么?别被概念唬住了
人工智能·python·agent
Python大数据分析@22 分钟前
对你而言, Vibe Coding 的乐趣是什么?
python
WL_Aurora22 分钟前
Python 算法基础篇之排序算法(一):冒泡、选择、插入
python·算法·排序算法
龙腾AI白云23 分钟前
中国人工智能培训网—AI系列录播课
python·beautifulsoup
AI算法沐枫25 分钟前
大一学生如何入门机器学习,深度学习,学习顺序如何?
人工智能·python·深度学习·学习·线性代数·算法·机器学习
用户67570498850229 分钟前
Python 统一大业:uv 如何整合 Pip、Pyenv 和 Venv?
后端·python
SilentSamsara40 分钟前
运算符重载:让自定义对象支持 +、[]、in 操作
开发语言·python·算法·青少年编程·pycharm
wuxinyan12341 分钟前
工业级大模型学习之路020:LangChain零基础入门教程(第三篇):提示词工程与提示模板系统
人工智能·python·学习·langchain