python小猴子接香蕉游戏代码
时间: 2024-07-17 09:00:22 浏览: 120
"Python小猴子接香蕉"通常是一个简单的教学示例,用来展示事件驱动编程和条件语句的概念。这是一个基本的游戏场景,猴子在屏幕下方移动,香蕉随机从顶部落下,猴子需要接住香蕉。以下是一个简化版的Python代码示例:
```python
import random
import pygame
# 初始化 Pygame
pygame.init()
# 设置窗口大小和标题
window_size = (600, 400)
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("Monkey Banana Game")
# 定义猴子、香蕉和得分
monkey_pos = [window_size // 2, window_size - 50]
banana_pos = [0, window_size - 50]
score = 0
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 香蕉下落
banana_pos -= 5
if banana_pos < 0:
banana_pos = window_size
# 猴子移动
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and monkey_pos > 0:
monkey_pos -= 10
if keys[pygame.K_DOWN] and monkey_pos < window_size - 50:
monkey_pos += 10
# 检查碰撞
if abs(monkey_pos - banana_pos) < 20 and abs(monkey_pos - banana_pos) < 20:
score += 1
banana_pos = [random.randint(0, window_size), window_size - 50]
# 绘制元素
screen.fill((255, 255, 255))
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(monkey_pos, (30, 30)))
pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(banana_pos, (30, 30)))
font = pygame.font.SysFont(None, 30)
text = font.render(f"Score: {score}", True, (0, 0, 0))
screen.blit(text, (10, 10))
# 更新屏幕
pygame.display.flip()
```
阅读全文