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

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

相关推荐
一只小波波呀1 小时前
打卡第48天
python
zstar-_1 小时前
一套个人知识储备库构建方案
python
Amo Xiang1 小时前
《100天精通Python——基础篇 2025 第5天:巩固核心知识,选择题实战演练基础语法》
python·选择题·基础语法
江梦寻2 小时前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
霖檬ing2 小时前
Python——MySQL远程控制
开发语言·python·mysql
miniwa2 小时前
Python编程精进:CSV 模块
python
老胖闲聊9 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1189 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之9 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
lyaihao10 小时前
使用python实现奔跑的线条效果
python·绘图