pygame库小猴子接香蕉
时间: 2023-06-29 17:09:06 浏览: 161
好的,这是一个简单的pygame例子,让小猴子接香蕉:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小和标题
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("小猴子接香蕉")
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
# 加载图片
monkey_img = pygame.image.load("monkey.png")
banana_img = pygame.image.load("banana.png")
# 获取图片大小
monkey_width, monkey_height = monkey_img.get_size()
banana_width, banana_height = banana_img.get_size()
# 随机生成香蕉的位置
banana_x = random.randint(0, screen_width - banana_width)
banana_y = random.randint(0, screen_height - banana_height)
# 设置小猴子的初始位置
monkey_x = screen_width / 2 - monkey_width / 2
monkey_y = screen_height - monkey_height
# 设置小猴子的移动速度
monkey_speed = 5
# 游戏循环
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 获取键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
monkey_x -= monkey_speed
if keys[pygame.K_RIGHT]:
monkey_x += monkey_speed
# 判断是否接到香蕉
if (banana_x < monkey_x + monkey_width and banana_x + banana_width > monkey_x
and banana_y < monkey_y + monkey_height and banana_y + banana_height > monkey_y):
banana_x = random.randint(0, screen_width - banana_width)
banana_y = random.randint(0, screen_height - banana_height)
# 绘制背景和图片
screen.fill(white)
screen.blit(monkey_img, (monkey_x, monkey_y))
screen.blit(banana_img, (banana_x, banana_y))
# 更新屏幕
pygame.display.update()
# 退出pygame
pygame.quit()
```
其中,`monkey.png` 和 `banana.png` 是小猴子和香蕉的图片,你可以自己准备或者下载。这个例子中,小猴子可以通过左右箭头键移动,如果接到了香蕉,香蕉会重新随机出现在屏幕上。
阅读全文