用python编写一个跑酷游戏 用pygame
时间: 2023-07-18 11:46:02 浏览: 72
好的,我可以给你提供一个简单的跑酷游戏的代码示例,使用的是Pygame库。这里只提供一个基础的框架,你可以根据自己的需求和想法进行修改和扩展。
```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)
# 加载图片
player_img = pygame.image.load("player.png").convert_alpha()
obstacle_img = pygame.image.load("obstacle.png").convert_alpha()
# 定义游戏对象类
class GameObject(pygame.sprite.Sprite):
def __init__(self, x, y, image):
super().__init__()
self.image = image
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# 定义主角类
class Player(GameObject):
def __init__(self, x, y, image):
super().__init__(x, y, image)
self.speed_y = 0
def update(self):
# 处理主角跳跃
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
self.speed_y = -10
self.rect.y += self.speed_y
self.speed_y += 0.5
# 定义障碍物类
class Obstacle(GameObject):
def update(self):
self.rect.x -= 5
# 创建游戏对象组
all_sprites = pygame.sprite.Group()
obstacles = pygame.sprite.Group()
# 创建主角对象
player = Player(100, 100, player_img)
all_sprites.add(player)
# 游戏循环
running = True
clock = pygame.time.Clock()
score = 0
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 创建障碍物
if random.randint(1, 100) == 1:
obstacle = Obstacle(WIDTH, random.randint(0, HEIGHT - obstacle_img.get_height()), obstacle_img)
all_sprites.add(obstacle)
obstacles.add(obstacle)
# 更新游戏对象
all_sprites.update()
# 处理碰撞检测
hits = pygame.sprite.spritecollide(player, obstacles, False)
if hits:
running = False
# 绘制游戏界面
screen.fill(WHITE)
all_sprites.draw(screen)
# 更新分数
score += 1
font = pygame.font.Font(None, 36)
text = font.render("Score: {}".format(score), True, BLACK)
screen.blit(text, (10, 10))
# 更新屏幕
pygame.display.flip()
# 控制游戏帧率
clock.tick(60)
# 退出游戏
pygame.quit()
```
这个示例代码实现了主角跳跃、障碍物生成、碰撞检测、分数计算等基础功能。你可以根据需要对其进行修改和扩展,比如添加更多的游戏元素、特效和音效等。同时注意代码的注释,有助于理解代码的功能和实现思路。