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

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

相关推荐
thinkMoreAndDoMore21 分钟前
深度学习(3)-TensorFlow入门(常数张量和变量)
开发语言·人工智能·python
kngines30 分钟前
【Python量化金融实战】-第1章:Python量化金融概述:1.4 开发环境搭建:Jupyter Notebook、VS Code、PyCharm
python·量化金融
kngines34 分钟前
【Python量化金融实战】-第1章:Python量化金融概述:1.2 Python在量化金融中的优势与生态
python·量化金融
wapicn9935 分钟前
‌挖数据平台对接DeepSeek推出一键云端部署功能:API接口驱动金融、汽车等行业智能化升级
java·人工智能·python·金融·汽车·php
蓝桉8021 小时前
图片爬取案例
开发语言·数据库·python
wang_yb1 小时前
『Python底层原理』--Python整数为什么可以无限大
python·databook
敲上瘾1 小时前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
阑梦清川2 小时前
Jupyter里面的manim编程学习
python·jupyter·manim
Dongwoo Jeong2 小时前
类型系统下的语言分类与类型系统基础
java·笔记·python·lisp·fortran·type
enyp802 小时前
*PyCharm 安装教程
ide·python·pycharm