pygame72行代码实现一个躲避类小游戏

import pygame
import random

pygame.init()

# 设置游戏窗口的大小
width = 800
height = 600
screen = pygame.display.set_mode((width, height))

# 设置游戏标题
pygame.display.set_caption("Dodge the Obstacle")

# 设置游戏时钟
clock = pygame.time.Clock()

# 加载游戏素材
player_image = pygame.image.load("player.png").convert_alpha()
obstacle_image = pygame.image.load("obstacle.png").convert_alpha()

# 定义游戏变量
player_x = width // 2
player_y = height - 100
player_speed = 5
obstacle_x = random.randint(0, width - obstacle_image.get_width())
obstacle_y = 0
obstacle_speed = 3
score = 0
font = pygame.font.SysFont(None, 50)

# 游戏循环
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] and player_x > 0:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x < width - player_image.get_width():
        player_x += player_speed

    # 更新游戏状态
    obstacle_y += obstacle_speed
    if obstacle_y > height:
        obstacle_x = random.randint(0, width - obstacle_image.get_width())
        obstacle_y = 0
        score += 1
        obstacle_speed += 0.1

    # 处理游戏碰撞
    player_rect = pygame.Rect(player_x, player_y, player_image.get_width(), player_image.get_height())
    obstacle_rect = pygame.Rect(obstacle_x, obstacle_y, obstacle_image.get_width(), obstacle_image.get_height())
    if player_rect.colliderect(obstacle_rect):
        running = False

    # 渲染游戏画面
    screen.fill((255, 255, 255))
    screen.blit(player_image, (player_x, player_y))
    screen.blit(obstacle_image, (obstacle_x, obstacle_y))
    score_text = font.render("Score: " + str(score), True, (0, 0, 0))
    screen.blit(score_text, (10, 10))
    pygame.display.flip()

    # 控制游戏帧率
    clock.tick(60)

# 游戏结束
pygame.quit()

注意:在运行这段代码之前,需要确保已经安装了 Pygame 并且准备好了用于游戏的素材图片。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值