基于Python3.5写一个源程序实现小鸡快跑游戏
时间: 2024-02-03 15:03:50 浏览: 38
好的,以下是一个基于Python3.5实现小鸡快跑游戏的示例源代码:
```python
import pygame
import random
# 初始化pygame模块
pygame.init()
# 定义游戏窗口大小
WIDTH = 800
HEIGHT = 600
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置游戏窗口标题
pygame.display.set_caption("小鸡快跑")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# 加载小鸡图片
chicken_img = pygame.image.load("chicken.png")
# 获取小鸡图片的矩形
chicken_rect = chicken_img.get_rect()
# 定义小鸡的初始位置
chicken_x = 50
chicken_y = HEIGHT - chicken_rect.height - 50
# 定义小鸡的速度
chicken_speed = 5
# 加载障碍物图片
obstacle_img = pygame.image.load("obstacle.png")
# 定义障碍物的初始位置
obstacle_x = WIDTH
obstacle_y = HEIGHT - obstacle_img.get_rect().height - 50
# 定义障碍物的速度
obstacle_speed = 5
# 定义分数
score = 0
# 加载字体
font = pygame.font.Font(None, 36)
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 获取键盘输入
keys = pygame.key.get_pressed()
# 移动小鸡
if keys[pygame.K_LEFT]:
chicken_x -= chicken_speed
elif keys[pygame.K_RIGHT]:
chicken_x += chicken_speed
# 移动障碍物
obstacle_x -= obstacle_speed
# 判断障碍物是否出界
if obstacle_x < -obstacle_img.get_rect().width:
obstacle_x = WIDTH
obstacle_y = HEIGHT - obstacle_img.get_rect().height - 50
score += 1
obstacle_speed += 1
# 检测碰撞
if chicken_rect.colliderect(pygame.Rect(obstacle_x, obstacle_y, obstacle_img.get_rect().width, obstacle_img.get_rect().height)):
running = False
# 绘制游戏界面
screen.fill(WHITE)
screen.blit(chicken_img, (chicken_x, chicken_y))
screen.blit(obstacle_img, (obstacle_x, obstacle_y))
score_text = font.render("Score: {}".format(score), True, BLACK)
screen.blit(score_text, (10, 10))
pygame.display.update()
# 退出游戏
pygame.quit()
```
请注意,此示例代码仅供学习参考,可能存在不足之处,如有需要请自行完善。