python实现有血条,有回血、障碍物、有计时的2d平面跑酷小游戏源码
时间: 2024-01-13 17:04:07 浏览: 161
以下是一个简单的Python实现有血条、有回血、有障碍物和有计时的2D平面跑酷小游戏的源码,供您参考:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 创建游戏窗口
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("2D平面跑酷小游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义游戏时钟和字体
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 25)
# 定义玩家类
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((50, 50))
self.image.fill(green)
self.rect = self.image.get_rect()
self.rect.x = 50
self.rect.y = screen_height - 100
self.health = 100
def update(self):
# 玩家移动
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= 5
elif keys[pygame.K_RIGHT]:
self.rect.x += 5
if keys[pygame.K_SPACE]:
self.rect.y -= 5
self.rect.y += 5
# 碰撞检测
if pygame.sprite.spritecollide(self, obstacles_group, False):
self.health -= 10
if self.health <= 0:
game_over()
# 回血
if self.health < 100:
self.health += 0.1
# 定义障碍物类
class Obstacle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((50, 50))
self.image.fill(red)
self.rect = self.image.get_rect()
self.rect.x = random.randint(100, screen_width - 100)
self.rect.y = -50
def update(self):
self.rect.y += 5
if self.rect.y > screen_height:
self.rect.x = random.randint(100, screen_width - 100)
self.rect.y = -50
# 定义计时器函数
def timer(seconds):
time_text = font.render("Time: " + str(seconds), True, black)
screen.blit(time_text, (10, 10))
# 定义血条函数
def health_bar(player_health):
pygame.draw.rect(screen, red, (10, 40, 100, 20))
pygame.draw.rect(screen, green, (10, 40, player_health, 20))
# 定义游戏结束函数
def game_over():
game_over_text = font.render("Game Over!", True, red)
screen.blit(game_over_text, (screen_width/2 - 50, screen_height/2))
pygame.display.update()
pygame.time.delay(3000)
pygame.quit()
quit()
# 创建玩家和障碍物群组
player_group = pygame.sprite.Group()
player = Player()
player_group.add(player)
obstacles_group = pygame.sprite.Group()
for i in range(5):
obstacle = Obstacle()
obstacles_group.add(obstacle)
# 游戏循环
game_running = True
start_ticks = pygame.time.get_ticks()
while game_running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
# 计时器
seconds = (pygame.time.get_ticks() - start_ticks) // 1000
timer(seconds)
# 绘制血条
health_bar(player.health)
# 更新玩家和障碍物
player_group.update()
player_group.draw(screen)
obstacles_group.update()
obstacles_group.draw(screen)
# 刷新游戏窗口
pygame.display.update()
# 控制游戏帧率
clock.tick(60)
# 退出 Pygame
pygame.quit()
```
以上代码仅供参考,可能需要根据您的具体需求进行修改。
阅读全文