pygame跑酷小游戏代码
时间: 2023-07-02 13:21:51 浏览: 78
下面是一个基于pygame的跑酷小游戏的代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 窗口尺寸
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("跑酷小游戏")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 加载图片
player_img = pygame.image.load("player.png")
player_img = pygame.transform.scale(player_img, (50, 50))
obstacle_img = pygame.image.load("obstacle.png")
obstacle_img = pygame.transform.scale(obstacle_img, (50, 50))
# 定义玩家和障碍物类
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = player_img
self.rect = self.image.get_rect()
self.rect.x = 100
self.rect.y = 300
self.change_x = 0
self.change_y = 0
def update(self):
self.rect.x += self.change_x
self.rect.y += self.change_y
# 碰到边缘停止移动
if self.rect.x < 0:
self.rect.x = 0
elif self.rect.x > size[0] - self.rect.width:
self.rect.x = size[0] - self.rect.width
if self.rect.y < 0:
self.rect.y = 0
elif self.rect.y > size[1] - self.rect.height:
self.rect.y = size[1] - self.rect.height
def jump(self):
self.change_y = -10
def gravity(self):
if self.change_y == 0:
self.change_y = 1
else:
self.change_y += 0.35
if self.rect.y >= size[1] - self.rect.height and self.change_y >= 0:
self.change_y = 0
self.rect.y = size[1] - self.rect.height
class Obstacle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = obstacle_img
self.rect = self.image.get_rect()
self.rect.x = size[0] + random.randrange(200, 1000)
self.rect.y = random.randrange(0, size[1] - self.rect.height)
def update(self):
self.rect.x -= 5
if self.rect.x < -self.rect.width:
self.rect.x = size[0] + random.randrange(200, 1000)
self.rect.y = random.randrange(0, size[1] - self.rect.height)
# 创建精灵组
all_sprites = pygame.sprite.Group()
obstacle_sprites = pygame.sprite.Group()
# 创建玩家和障碍物
player = Player()
all_sprites.add(player)
for i in range(6):
obstacle = Obstacle()
all_sprites.add(obstacle)
obstacle_sprites.add(obstacle)
# 游戏主循环
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.jump()
screen.fill(WHITE)
all_sprites.update()
# 碰撞检测
if pygame.sprite.spritecollide(player, obstacle_sprites, False):
done = True
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
```
这个跑酷小游戏有一个玩家和多个障碍物,玩家可以跳跃来避开障碍物。当玩家碰到障碍物时游戏结束。
阅读全文