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

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

相关推荐
python机器学习ML2 分钟前
机器学习——16种模型(基础+集成学习)+多角度SHAP高级可视化+Streamlit交互式应用+RFE特征选择+Optuna+完整项目
人工智能·python·机器学习·分类·数据挖掘·scikit-learn·集成学习
Java程序员威哥16 分钟前
Java应用容器化最佳实践:Docker镜像构建+K8s滚动更新(生产级完整模板+避坑指南)
java·开发语言·后端·python·docker·kubernetes·c#
资深设备全生命周期管理16 分钟前
【实时显示画面在视频上,捕获轮廓】
python
qq_21539789720 分钟前
python环境无网络环境导入依赖
开发语言·python
三七吃山漆32 分钟前
[护网杯 2018]easy_tornado
python·web安全·ctf·tornado
越甲八千36 分钟前
FastAPI传参类型
开发语言·python·fastapi
惜.己36 分钟前
单个图片转化工具分享(源码+工具)
python
大数据0039 分钟前
基于Ollama大模型学习
python·flask·大模型·alibaba·ollama·springai·deepseek
YHLG44 分钟前
LangChain v1.0+ 入门详解:概念、架构、组件、模板与实战
python·langchain
pen-ai1 小时前
PyTorch 张量维度处理详解
人工智能·pytorch·python