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

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

相关推荐
WJX_KOI1 小时前
Open Notebook 一个开源的结合AI的记笔记软件
python
0思必得02 小时前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
2301_822382762 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
喵手2 小时前
Python爬虫实战:从零搭建字体库爬虫 - requests+lxml 实战采集字体网字体信息数据(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·采集字体库数据·字体库字体信息采集
2301_790300963 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
程序员敲代码吗4 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
Yyyyy123jsjs4 小时前
如何通过免费的外汇API轻松获取实时汇率数据
开发语言·python
喵手4 小时前
Python爬虫实战:GovDataMiner —— 开放数据门户数据集元数据采集器(附 CSV 导出)!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·open data·开放数据门户数据集列表
历程里程碑5 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django