以下是一个用Python编写的赛车小游戏的示例代码:

import pygame
import random

# 初始化游戏
pygame.init()

# 设置游戏窗口大小
screen_width = 800
screen_height = 600
win = pygame.display.set_mode((screen_width, screen_height))

# 设置游戏标题
pygame.display.set_caption("赛车小游戏")

# 加载赛车图片
car_image = pygame.image.load('car.png')

# 设置赛车初始位置和速度
car_x = 370
car_y = 480
car_speed = 0

# 加载障碍物图片
obstacle_image = pygame.image.load('obstacle.png')

# 设置障碍物初始位置和速度
obstacle_x = random.randint(0, screen_width)
obstacle_y = -600
obstacle_speed = 5

# 加载背景音乐
pygame.mixer.music.load('background_music.mp3')
pygame.mixer.music.play(-1)  # 循环播放背景音乐

# 游戏主循环
running = True
while running:
    # 监听事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 监听键盘按键事件
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                car_speed = -5
            if event.key == pygame.K_RIGHT:
                car_speed = 5

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                car_speed = 0

    # 更新赛车位置
    car_x += car_speed

    # 碰撞检测
    if car_x < 0:
        car_x = 0
    elif car_x > screen_width - 64:
        car_x = screen_width - 64

    # 更新障碍物位置
    obstacle_y += obstacle_speed

    # 如果障碍物超出屏幕,则重新生成障碍物
    if obstacle_y > screen_height:
        obstacle_x = random.randint(0, screen_width)
        obstacle_y = -600

    # 绘制游戏界面
    win.fill((255, 255, 255))  # 填充白色背景
    win.blit(obstacle_image, (obstacle_x, obstacle_y))  # 绘制障碍物
    win.blit(car_image, (car_x, car_y))  # 绘制赛车
    pygame.display.update()  # 更新游戏界面

# 退出游戏
pygame.quit()

请注意,这只是一个简单的示例代码,游戏功能有限。您可以根据自己的需求进行修改和扩展


原文地址: https://www.cveoy.top/t/topic/hTBS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录