python代码实现滑冰车游戏

import pygame
import random

# 初始化 pygame
pygame.init()

# 设置屏幕尺寸和颜色
WIDTH, HEIGHT = 800, 600
BACKGROUND_COLOR = (135, 206, 250)  # 天空蓝
CAR_COLOR = (255, 0, 0)            # 滑冰车颜色
OBSTACLE_COLOR = (0, 0, 0)         # 障碍物颜色
FPS = 30

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("滑冰车游戏")

# 创建游戏对象
car_width, car_height = 50, 30
obstacle_width, obstacle_height = 60, 20

# 初始滑冰车位置
car_pos = [WIDTH // 2, HEIGHT - car_height - 10]
car_speed = 5
obstacles = []

clock = pygame.time.Clock()

def move_car(keys):
    if keys[pygame.K_LEFT]:
        car_pos[0] -= car_speed
    if keys[pygame.K_RIGHT]:
        car_pos[0] += car_speed

    # 防止滑冰车走出屏幕边界
    car_pos[0] = max(0, min(car_pos[0], WIDTH - car_width))

def drop_obstacle():
    x = random.randint(0, WIDTH - obstacle_width)
    y = -obstacle_height
    obstacles.append([x, y])

def move_obstacles():
    for obstacle in obstacles:
        obstacle[1] += 5

def check_collision():
    global obstacles
    for obstacle in obstacles[:]:
        if (car_pos[0] < obstacle[0] + obstacle_width and
            car_pos[0] + car_width > obstacle[0] and
            car_pos[1] < obstacle[1] + obstacle_height and
            car_pos[1] + car_height > obstacle[1]):
            return True
    return False

def draw_objects():
    screen.fill(BACKGROUND_COLOR)
    pygame.draw.rect(screen, CAR_COLOR, (*car_pos, car_width, car_height))
    for obstacle in obstacles:
        pygame.draw.rect(screen, OBSTACLE_COLOR, (*obstacle, obstacle_width, obstacle_height))
    pygame.display.flip()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    move_car(keys)
    
    if random.randint(1, 30) == 1:
        drop_obstacle()

    move_obstacles()

    if check_collision():
        print("游戏结束!")
        running = False

    draw_objects()
    clock.tick(FPS)

pygame.quit()
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值