赛车小游戏

 

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('简单赛车游戏')

 

# 颜色定义

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

RED = (255, 0, 0)

 

# 加载赛车图片

car_image = pygame.image.load('car.png')

car_width = car_image.get_width()

car_height = car_image.get_height()

 

# 加载障碍物图片

obstacle_image = pygame.image.load('obstacle.png')

obstacle_width = obstacle_image.get_width()

obstacle_height = obstacle_image.get_height()

 

 

# 生成障碍物

def generate_obstacle():

    x = random.randint(0, screen_width - obstacle_width)

    y = -obstacle_height

    speed = random.randint(3, 7)

    return [x, y, speed]

 

 

# 绘制赛车

def draw_car(x, y):

    screen.blit(car_image, (x, y))

 

 

# 绘制障碍物

def draw_obstacle(x, y):

    screen.blit(obstacle_image, (x, y))

 

 

# 游戏主循环

clock = pygame.time.Clock()

car_x = screen_width / 2 - car_width / 2

car_y = screen_height - car_height - 10

car_speed = 0

 

obstacles = []

 

running = True

while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False

        elif event.type == pygame.KEYDOWN:

            if event.key == pygame.K_LEFT:

                car_speed = -5

            elif event.key == pygame.K_RIGHT:

                car_speed = 5

        elif event.type == pygame.KEYUP:

            if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:

                car_speed = 0

 

    car_x += car_speed

    if car_x < 0:

        car_x = 0

    elif car_x > screen_width - car_width:

        car_x = screen_width - car_width

 

    if random.randint(1, 100) < 5:

        obstacles.append(generate_obstacle())

 

    for obstacle in obstacles:

        obstacle[1] += obstacle[2]

        if obstacle[1] > screen_height:

            obstacles.remove(obstacle)

        if (car_x < obstacle[0] + obstacle_width) and (car_x + car_width > obstacle[0]) and (

                car_y < obstacle[1] + obstacle_height) and (car_y + car_height > obstacle[1]):

            print('碰撞,游戏结束')

            running = False

 

    screen.fill(BLACK)

    draw_car(car_x, car_y)

    for obstacle in obstacles:

        draw_obstacle(obstacle[0], obstacle[1])

 

    pygame.display.flip()

    clock.tick(60)

 

pygame.quit()

 

 

 

 

在上述代码中:

 

初始化和设置:初始化 pygame ,设置游戏窗口的大小和标题,定义颜色和加载图片。

 

游戏对象:定义了赛车和障碍物的绘制函数,以及生成障碍物的函数。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值