【趣味Python】第8课:小汽车游戏

专栏导读

在这里插入图片描述

  • 🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手

  • 🏳️‍🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注

  • 👍 该系列文章专栏:请点击——>Python办公自动化专栏求订阅

  • 🕷 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅

  • 📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅

  • 文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏

  • ❤️ 欢迎各位佬关注! ❤️

背景介绍

  • 今天我们要用Python的Pygame库来创建一个简单但有趣的小汽车游戏!在这个游戏中,你将控制一辆红色小车躲避从上方驶来的蓝色敌车,看看你能坚持多久并获得多高的分数。

游戏概述

这个游戏包含以下元素:

  • 玩家控制的红色小车
  • 随机出现的蓝色敌车
  • 道路边界和中间的虚线
  • 计分系统和难度递增机制

库的安装

用途安装
pygame游戏库pip install pygame -i https://pypi.tuna.tsinghua.edu.cn/simple/

代码解析

1. 初始化设置

  • 首先我们导入必要的库,初始化Pygame,并设置游戏窗口的大小为400x600像素。

import pygame
import sys
import random

# 初始化
pygame.init()

# 屏幕尺寸
WIDTH, HEIGHT = 400, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("升级版赛车游戏")

2. 玩家车辆设置

  • 这里定义了玩家车辆的大小、初始位置和移动速度。

# 小车参数
car_width, car_height = 50, 100
car_x = WIDTH // 2 - car_width // 2
car_y = HEIGHT - car_height - 20
car_speed = 5

3. 敌车设置

  • 敌车大小与玩家车辆相同,初始位置随机出现在屏幕顶部上方。

# 敌人车参数
enemy_width, enemy_height = 50, 100
enemy_x = random.randint(40, WIDTH - 40 - enemy_width)
enemy_y = -enemy_height
enemy_speed = 5

4. 游戏元素

  • 这里定义了道路中间的虚线参数和一些常用的颜色值。

# 虚线参数
line_height = 40
line_width = 5
line_gap = 20
lines = [y for y in range(0, HEIGHT, line_height + line_gap)]

# 颜色定义
GRAY = (50, 50, 50)
WHITE = (255, 255, 255)
RED = (200, 0, 0)
BLUE = (0, 100, 255)
BLACK = (0, 0, 0)

5. 游戏主循环

  • 游戏的核心是一个无限循环,直到发生碰撞才会退出:

running = True
while running:
    screen.fill(GRAY)
    
    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

6. 道路和车辆绘制

# 虚线移动
for i in range(len(lines)):
    pygame.draw.rect(screen, WHITE, (WIDTH // 2 - line_width // 2, lines[i], line_width, line_height))
    lines[i] += 5
    if lines[i] > HEIGHT:
        lines[i] = -line_height - line_gap

# 画边界
pygame.draw.rect(screen, WHITE, (30, 0, 5, HEIGHT))
pygame.draw.rect(screen, WHITE, (WIDTH - 35, 0, 5, HEIGHT))

# 画小车和敌人车
pygame.draw.rect(screen, RED, car_rect)      # 玩家小车
pygame.draw.rect(screen, BLUE, enemy_rect)   # 敌人车

7. 玩家控制

  • 玩家可以使用左右方向键控制车辆移动,但不能超出道路边界。

# 按键控制
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and car_x > 40:
    car_x -= car_speed
if keys[pygame.K_RIGHT] and car_x < WIDTH - car_width - 40:
    car_x += car_speed

8. 敌车移动和计分

# 移动敌人车
enemy_y += enemy_speed
if enemy_y > HEIGHT:
    enemy_y = -enemy_height
    enemy_x = random.randint(40, WIDTH - 40 - enemy_width)
    score += 1  # 每次成功避开一个敌人 +1分

9. 碰撞检测

# 移动敌人车
# 碰撞检测
car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
enemy_rect = pygame.Rect(enemy_x, enemy_y, enemy_width, enemy_height)
if car_rect.colliderect(enemy_rect):
    running = False  # 游戏结束

10. 难度递增

  • 随着游戏进行,敌车速度会逐渐增加,提高游戏难度。

# 难度随时间增加
frame_count += 1
if frame_count % 300 == 0:
    enemy_speed += 1
    level += 1

11. 游戏结束画面

# 游戏结束画面
screen.fill(BLACK)
game_over_text = font.render("游戏结束", True, RED)
final_score = font.render(f"最终得分:{score}", True, WHITE)
screen.blit(game_over_text, (WIDTH // 2 - 60, HEIGHT // 2 - 40))
screen.blit(final_score, (WIDTH // 2 - 80, HEIGHT // 2 + 10))
pygame.display.update()
pygame.time.wait(3000)

完整代码

import pygame
import sys
import random

# 初始化
pygame.init()

# 屏幕尺寸
WIDTH, HEIGHT = 400, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("升级版赛车游戏")

# 小车参数
car_width, car_height = 50, 100
car_x = WIDTH // 2 - car_width // 2
car_y = HEIGHT - car_height - 20
car_speed = 5

# 敌人车参数
enemy_width, enemy_height = 50, 100
enemy_x = random.randint(40, WIDTH - 40 - enemy_width)
enemy_y = -enemy_height
enemy_speed = 5

# 分数与难度
score = 0
font = pygame.font.SysFont('simhei', 36)
level = 1
frame_count = 0

# 虚线参数
line_height = 40
line_width = 5
line_gap = 20
lines = [y for y in range(0, HEIGHT, line_height + line_gap)]

# 颜色定义
GRAY = (50, 50, 50)
WHITE = (255, 255, 255)
RED = (200, 0, 0)
BLUE = (0, 100, 255)
BLACK = (0, 0, 0)

# 时钟
clock = pygame.time.Clock()

# 主循环
running = True
while running:
    screen.fill(GRAY)

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 虚线移动
    for i in range(len(lines)):
        pygame.draw.rect(screen, WHITE, (WIDTH // 2 - line_width // 2, lines[i], line_width, line_height))
        lines[i] += 5
        if lines[i] > HEIGHT:
            lines[i] = -line_height - line_gap

    # 按键控制
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and car_x > 40:
        car_x -= car_speed
    if keys[pygame.K_RIGHT] and car_x < WIDTH - car_width - 40:
        car_x += car_speed

    # 移动敌人车
    enemy_y += enemy_speed
    if enemy_y > HEIGHT:
        enemy_y = -enemy_height
        enemy_x = random.randint(40, WIDTH - 40 - enemy_width)
        score += 1  # 每次成功避开一个敌人 +1分

    # 碰撞检测
    car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
    enemy_rect = pygame.Rect(enemy_x, enemy_y, enemy_width, enemy_height)
    if car_rect.colliderect(enemy_rect):
        running = False  # 游戏结束

    # 画边界
    pygame.draw.rect(screen, WHITE, (30, 0, 5, HEIGHT))
    pygame.draw.rect(screen, WHITE, (WIDTH - 35, 0, 5, HEIGHT))

    # 画小车和敌人车
    pygame.draw.rect(screen, RED, car_rect)      # 玩家小车
    pygame.draw.rect(screen, BLUE, enemy_rect)   # 敌人车

    # 显示分数
    score_text = font.render(f"得分:{score}", True, WHITE)
    screen.blit(score_text, (10, 10))

    # 难度随时间增加
    frame_count += 1
    if frame_count % 300 == 0:
        enemy_speed += 1
        level += 1

    level_text = font.render(f"等级:{level}", True, WHITE)
    screen.blit(level_text, (WIDTH - 130, 10))

    pygame.display.update()
    clock.tick(60)

# 游戏结束画面
screen.fill(BLACK)
game_over_text = font.render("游戏结束", True, RED)
final_score = font.render(f"最终得分:{score}", True, WHITE)
screen.blit(game_over_text, (WIDTH // 2 - 60, HEIGHT // 2 - 40))
screen.blit(final_score, (WIDTH // 2 - 80, HEIGHT // 2 + 10))
pygame.display.update()
pygame.time.wait(3000)

pygame.quit()
sys.exit()

总结

  • 希望对初学者有帮助

  • 致力于办公自动化的小小程序员一枚

  • 希望能得到大家的【一个免费关注】!感谢

  • 求个 🤞 关注 🤞

  • 此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏

  • 求个 ❤️ 喜欢 ❤️

  • 此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏

  • 求个 👍 收藏 👍

  • 此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小庄-Python办公

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值