python游戏生成随机小球
时间: 2024-11-16 17:11:35 浏览: 3
在Python中,我们可以利用`random`模块以及`pygame`库来创建一个简单的随机移动的小球游戏。首先,你需要安装`pygame`,如果还没安装,可以使用`pip install pygame`命令。
以下是一个基础的示例,展示如何生成一个随机位置并随机移动的小球:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
window_size = (800, 600)
screen = pygame.display.set_mode(window_size)
# 小球属性
ball_radius = 20
ball_color = (255, 0, 0) # 红色
# 随机生成初始位置
ball_pos = [random.randint(0, window_size[0] - ball_radius),
random.randint(0, window_size[1] - ball_radius)]
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动小球
ball_pos[0] += random.uniform(-5, 5) # 随机速度在-5到5之间
ball_pos[1] += random.uniform(-5, 5)
# 如果小球超出屏幕边界,让它反弹回来
if ball_pos[0] < ball_radius or ball_pos[0] > window_size[0] - ball_radius:
ball_pos[0] = ball_radius if ball_pos[0] < ball_radius else window_size[0] - ball_radius
if ball_pos[1] < ball_radius or ball_pos[1] > window_size[1] - ball_radius:
ball_pos[1] = ball_radius if ball_pos[1] < ball_radius else window_size[1] - ball_radius
# 绘制小球
pygame.draw.circle(screen, ball_color, ball_pos, ball_radius)
# 更新屏幕
pygame.display.update()
# 退出pygame
pygame.quit()
```
阅读全文