【Python实战】Google Chrome的离线小恐龙游戏

文章目录

Google Chrome的离线小恐龙游戏

本文章通过详细的列举项目结构大纲和列举逐步编码过程和思路,便于学习者能够更加快速方便地掌握该游戏的开发。

项目结构大纲 📊👣
bash 复制代码
t_rex_game/
│
├── main.py        # 主程序文件
├── trex.py        # T-Rex角色类
├── assets/
│   └── trex.png   # T-Rex图片文件
├── obstacles.py   # 障碍物类
逐步编码过程 🧩💡
第一步:项目初始化与主程序框架

main.py

python 复制代码
import pygame
import sys
from trex import TRex

# 初始化pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))

# 定义颜色
white = (255, 255, 255)

# 设置帧率
clock = pygame.time.Clock()
fps = 30

# 游戏主循环
def game_loop():
    t_rex = TRex(screen_width, screen_height)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        screen.fill(white)
        t_rex.draw(screen)

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

if __name__ == "__main__":
    game_loop()

trex.py

python 复制代码
import pygame
import os

class TRex:
    def __init__(self, screen_width, screen_height):
        # 获取当前脚本文件所在的目录
        current_path = os.path.dirname(__file__)
        # 拼接图片文件的完整路径
        image_path = os.path.join(current_path, 'assets', 'trex.png')
        self.image = pygame.image.load(image_path)
        self.image = pygame.transform.scale(self.image, (50, 50))  # 缩放图片
        self.x = 50
        self.y = screen_height - 70
        self.screen_width = screen_width
        self.screen_height = screen_height

    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y))

注意点

首先,trex.png指的是小恐龙的照片,要先保证照片能够正常显示;然后要使用pygame.transform.scale函数来缩放图片大小。调整后的图片大小为50x50像素,你可以根据需要调整这个尺寸。

第二步:实现T-Rex的跳跃功能

main.py

python 复制代码
import pygame
import sys
from trex import TRex

# 初始化pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))

# 定义颜色
white = (255, 255, 255)

# 设置帧率
clock = pygame.time.Clock()
fps = 30

# 游戏主循环
def game_loop():
    t_rex = TRex(screen_width, screen_height)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    t_rex.jump()

        t_rex.update()  # 更新T-Rex的状态

        screen.fill(white)
        t_rex.draw(screen)

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

if __name__ == "__main__":
    game_loop()

trex.py

python 复制代码
import pygame
import os

class TRex:
    def __init__(self, screen_width, screen_height):
        # 获取当前脚本文件所在的目录
        current_path = os.path.dirname(__file__)
        # 拼接图片文件的完整路径
        image_path = os.path.join(current_path, 'assets', 'trex.png')
        self.image = pygame.image.load(image_path)
        self.image = pygame.transform.scale(self.image, (50, 50))  # 缩放图片
        self.x = 50
        self.y = screen_height - 70
        self.jump_speed = 20  # 跳跃速度(增加)
        self.gravity = 2  # 重力(增加)
        self.velocity = 0  # 初始速度
        self.is_jumping = False  # 跳跃状态
        self.screen_width = screen_width
        self.screen_height = screen_height

    def jump(self):
        if not self.is_jumping:
            self.is_jumping = True
            self.velocity = -self.jump_speed

    def update(self):
        if self.is_jumping:
            self.y += self.velocity
            self.velocity += self.gravity

            # 检查是否着地
            if self.y >= self.screen_height - 70:
                self.y = self.screen_height - 70
                self.is_jumping = False
                self.velocity = 0

    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y))

注意点

在完成跳跃功能时,我们会使小恐龙跳跃回弹到地面的时间尽可能短。我们可以通过设置:
跳跃速度 :将self.jump_speed从15增加到20。
重力加速度 :将self.gravity从1增加到2。

第三步:添加障碍物和碰撞检测

我们需要创建一个Obstacle类,并在主程序中生成障碍物。同时,实现T-Rex与障碍物的碰撞检测。
项目结构大纲 📊👣

bash 复制代码
t_rex_game/
│
├── main.py        # 主程序文件
├── trex.py        # T-Rex角色类
├── obstacles.py   # 障碍物类
├── assets/
│   └── trex.png   # T-Rex图片文件
│   └── cactus.png # 障碍物图片文件
└── utils.py       # 工具函数

main.py

python 复制代码
import pygame
import sys
from trex import TRex
from obstacles import Obstacle
import random

# 初始化pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))

# 定义颜色
white = (255, 255, 255)

# 设置帧率
clock = pygame.time.Clock()
fps = 30

# 游戏主循环
def game_loop():
    t_rex = TRex(screen_width, screen_height)
    obstacles = []

    def create_obstacle():
        obstacle = Obstacle(screen_width, screen_height)
        obstacles.append(obstacle)

    # 每隔一段时间创建一个新障碍物
    obstacle_timer = 0

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    t_rex.jump()

        t_rex.update()  # 更新T-Rex的状态

        # 创建新障碍物
        obstacle_timer += 1
        if obstacle_timer > 50:
            create_obstacle()
            obstacle_timer = 0

        # 更新障碍物状态
        for obstacle in obstacles:
            obstacle.update()
            # 检测碰撞
            if t_rex.x < obstacle.x + obstacle.width and \
               t_rex.x + t_rex.width > obstacle.x and \
               t_rex.y < obstacle.y + obstacle.height and \
               t_rex.height + t_rex.y > obstacle.y:
                # 碰撞检测到
                pygame.quit()
                sys.exit()

        # 清除离开屏幕的障碍物
        obstacles = [obstacle for obstacle in obstacles if obstacle.x + obstacle.width > 0]

        screen.fill(white)
        t_rex.draw(screen)
        for obstacle in obstacles:
            obstacle.draw(screen)

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

if __name__ == "__main__":
    game_loop()

trex.py

python 复制代码
import pygame
import os

class TRex:
    def __init__(self, screen_width, screen_height):
        # 获取当前脚本文件所在的目录
        current_path = os.path.dirname(__file__)
        # 拼接图片文件的完整路径
        image_path = os.path.join(current_path, 'assets', 'trex.png')
        self.image = pygame.image.load(image_path)
        self.image = pygame.transform.scale(self.image, (50, 50))  # 缩放图片
        self.x = 50
        self.y = screen_height - 70
        self.width = 50
        self.height = 50
        self.jump_speed = 20  # 跳跃速度
        self.gravity = 2  # 重力
        self.velocity = 0  # 初始速度
        self.is_jumping = False  # 跳跃状态
        self.screen_width = screen_width
        self.screen_height = screen_height

    def jump(self):
        if not self.is_jumping:
            self.is_jumping = True
            self.velocity = -self.jump_speed

    def update(self):
        if self.is_jumping:
            self.y += self.velocity
            self.velocity += self.gravity

            # 检查是否着地
            if self.y >= self.screen_height - 70:
                self.y = self.screen_height - 70
                self.is_jumping = False
                self.velocity = 0

    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y))

obstacles.py

python 复制代码
import pygame
import os

class Obstacle:
    def __init__(self, screen_width, screen_height):
        # 获取当前脚本文件所在的目录
        current_path = os.path.dirname(__file__)
        # 拼接图片文件的完整路径
        image_path = os.path.join(current_path, 'assets', 'cactus.png')
        self.image = pygame.image.load(image_path)
        self.image = pygame.transform.scale(self.image, (50, 50))  # 缩放图片
        self.x = screen_width
        self.y = screen_height - 70
        self.width = 50
        self.height = 50
        self.speed = 10

    def update(self):
        self.x -= self.speed

    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y))

解释
障碍物类 :Obstacle类用于表示游戏中的障碍物。每个障碍物都有位置、大小和速度属性。
创建和更新障碍物 :在主程序中,我们定期创建新障碍物,并在每一帧更新它们的位置。
碰撞检测:在主程序的每一帧,我们检查T-Rex与每个障碍物是否发生碰撞。如果发生碰撞,游戏结束。

第四步:添加得分机制和显示得分

main.py

python 复制代码
import pygame
import sys
from trex import TRex
from obstacles import Obstacle
import random

# 初始化pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)

# 设置帧率
clock = pygame.time.Clock()
fps = 30

# 游戏主循环
def game_loop():
    t_rex = TRex(screen_width, screen_height)
    obstacles = []
    score = 0

    def create_obstacle():
        obstacle = Obstacle(screen_width, screen_height)
        obstacles.append(obstacle)

    # 每隔一段时间创建一个新障碍物
    obstacle_timer = 0

    # 创建字体对象
    font = pygame.font.Font(None, 36)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    t_rex.jump()

        t_rex.update()  # 更新T-Rex的状态

        # 创建新障碍物
        obstacle_timer += 1
        if obstacle_timer > 50:
            create_obstacle()
            obstacle_timer = 0

        # 更新障碍物状态
        for obstacle in obstacles:
            obstacle.update()
            # 检测碰撞
            if t_rex.x < obstacle.x + obstacle.width and \
               t_rex.x + t_rex.width > obstacle.x and \
               t_rex.y < obstacle.y + obstacle.height and \
               t_rex.height + t_rex.y > obstacle.y:
                # 碰撞检测到
                pygame.quit()
                sys.exit()

        # 更新得分
        for obstacle in obstacles:
            if obstacle.x + obstacle.width < t_rex.x:
                score += 1
                obstacles.remove(obstacle)  # 删除已通过的障碍物

        screen.fill(white)
        t_rex.draw(screen)
        for obstacle in obstacles:
            obstacle.draw(screen)

        # 显示得分
        score_text = font.render(f'Score: {score}', True, black)
        screen.blit(score_text, (10, 10))

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

if __name__ == "__main__":
    game_loop()

trex.py

python 复制代码
import pygame
import os

class TRex:
    def __init__(self, screen_width, screen_height):
        # 获取当前脚本文件所在的目录
        current_path = os.path.dirname(__file__)
        # 拼接图片文件的完整路径
        image_path = os.path.join(current_path, 'assets', 'trex.png')
        self.image = pygame.image.load(image_path)
        self.image = pygame.transform.scale(self.image, (50, 50))  # 缩放图片
        self.x = 50
        self.y = screen_height - 70
        self.width = 50
        self.height = 50
        self.jump_speed = 20  # 跳跃速度
        self.gravity = 2  # 重力
        self.velocity = 0  # 初始速度
        self.is_jumping = False  # 跳跃状态
        self.screen_width = screen_width
        self.screen_height = screen_height

    def jump(self):
        if not self.is_jumping:
            self.is_jumping = True
            self.velocity = -self.jump_speed

    def update(self):
        if self.is_jumping:
            self.y += self.velocity
            self.velocity += self.gravity

            # 检查是否着地
            if self.y >= self.screen_height - 70:
                self.y = self.screen_height - 70
                self.is_jumping = False
                self.velocity = 0

    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y))

obstacles.py

python 复制代码
import pygame
import os

class Obstacle:
    def __init__(self, screen_width, screen_height):
        # 获取当前脚本文件所在的目录
        current_path = os.path.dirname(__file__)
        # 拼接图片文件的完整路径
        image_path = os.path.join(current_path, 'assets', 'cactus.png')
        self.image = pygame.image.load(image_path)
        self.image = pygame.transform.scale(self.image, (50, 50))  # 缩放图片
        self.x = screen_width
        self.y = screen_height - 70
        self.width = 50
        self.height = 50
        self.speed = 10

    def update(self):
        self.x -= self.speed

    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y))

解释
更新得分机制:在每一帧中,检查每个障碍物是否已经通过了T-Rex的位置(obstacle.x + obstacle.width < t_rex.x)。如果通过,增加得分,并从障碍物列表中删除该障碍物。

第五步:游戏结束处理和重新开始选项

main.py

python 复制代码
import pygame
import sys
from trex import TRex
from obstacles import Obstacle
import random

# 初始化pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

# 设置帧率
clock = pygame.time.Clock()
fps = 30

# 显示游戏结束画面
def show_game_over_screen(score):
    screen.fill(white)
    font = pygame.font.Font(None, 48)
    game_over_text = font.render('Game Over', True, red)
    score_text = font.render(f'Score: {score}', True, black)
    restart_text = font.render('Press R to Restart', True, black)
    
    screen.blit(game_over_text, (screen_width // 2 - game_over_text.get_width() // 2, screen_height // 2 - 50))
    screen.blit(score_text, (screen_width // 2 - score_text.get_width() // 2, screen_height // 2))
    screen.blit(restart_text, (screen_width // 2 - restart_text.get_width() // 2, screen_height // 2 + 50))
    
    pygame.display.update()

    # 等待用户按下 R 键重新开始
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    return  # 重新开始游戏

# 游戏主循环
def game_loop():
    t_rex = TRex(screen_width, screen_height)
    obstacles = []
    score = 0

    def create_obstacle():
        obstacle = Obstacle(screen_width, screen_height)
        obstacles.append(obstacle)

    # 每隔一段时间创建一个新障碍物
    obstacle_timer = 0

    # 创建字体对象
    font = pygame.font.Font(None, 36)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    t_rex.jump()

        t_rex.update()  # 更新T-Rex的状态

        # 创建新障碍物
        obstacle_timer += 1
        if obstacle_timer > 50:
            create_obstacle()
            obstacle_timer = 0

        # 更新障碍物状态
        for obstacle in obstacles:
            obstacle.update()
            # 检测碰撞
            if t_rex.x < obstacle.x + obstacle.width and \
               t_rex.x + t_rex.width > obstacle.x and \
               t_rex.y < obstacle.y + obstacle.height and \
               t_rex.height + t_rex.y > obstacle.y:
                # 碰撞检测到,显示游戏结束画面
                show_game_over_screen(score)
                return

        # 更新得分
        for obstacle in obstacles:
            if obstacle.x + obstacle.width < t_rex.x:
                score += 1
                obstacles.remove(obstacle)  # 删除已通过的障碍物

        screen.fill(white)
        t_rex.draw(screen)
        for obstacle in obstacles:
            obstacle.draw(screen)

        # 显示得分
        score_text = font.render(f'Score: {score}', True, black)
        screen.blit(score_text, (10, 10))

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

if __name__ == "__main__":
    while True:
        game_loop()
第六步:添加背景和地面

项目结构大纲

bash 复制代码
t_rex_game/
│
├── main.py        # 主程序文件
├── trex.py        # T-Rex角色类
├── obstacles.py   # 障碍物类
├── assets/
│   └── trex.png   # T-Rex图片文件
│   └── cactus.png # 障碍物图片文件
│   └── ground.png # 地面图片文件
└── utils.py       # 工具函数

main.py

python 复制代码
import pygame
import sys
from trex import TRex
from obstacles import Obstacle
import random

# 初始化pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

# 设置帧率
clock = pygame.time.Clock()
fps = 30

# 加载地面图片
ground = pygame.image.load('assets/ground.png')
ground_height = 20
ground = pygame.transform.scale(ground, (screen_width, ground_height))

# 显示游戏结束画面
def show_game_over_screen(score):
    screen.fill(white)
    font = pygame.font.Font(None, 48)
    game_over_text = font.render('Game Over', True, red)
    score_text = font.render(f'Score: {score}', True, black)
    restart_text = font.render('Press R to Restart', True, black)
    
    screen.blit(game_over_text, (screen_width // 2 - game_over_text.get_width() // 2, screen_height // 2 - 50))
    screen.blit(score_text, (screen_width // 2 - score_text.get_width() // 2, screen_height // 2))
    screen.blit(restart_text, (screen_width // 2 - restart_text.get_width() // 2, screen_height // 2 + 50))
    
    pygame.display.update()

    # 等待用户按下 R 键重新开始
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    return  # 重新开始游戏

# 游戏主循环
def game_loop():
    t_rex = TRex(screen_width, screen_height)
    obstacles = []
    score = 0

    def create_obstacle():
        obstacle = Obstacle(screen_width, screen_height)
        obstacles.append(obstacle)

    # 每隔一段时间创建一个新障碍物
    obstacle_timer = 0

    # 创建字体对象
    font = pygame.font.Font(None, 36)

    # 背景颜色控制
    bg_color = white
    bg_color_change_timer = 0
    bg_color_change_interval = 500  # 颜色变化间隔(帧数)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    t_rex.jump()

        t_rex.update()  # 更新T-Rex的状态

        # 创建新障碍物
        obstacle_timer += 1
        if obstacle_timer > 50:
            create_obstacle()
            obstacle_timer = 0

        # 更新障碍物状态
        for obstacle in obstacles:
            obstacle.update()
            # 检测碰撞
            if t_rex.x < obstacle.x + obstacle.width and \
               t_rex.x + t_rex.width > obstacle.x and \
               t_rex.y < obstacle.y + obstacle.height and \
               t_rex.height + t_rex.y > obstacle.y:
                # 碰撞检测到,显示游戏结束画面
                show_game_over_screen(score)
                return

        # 更新得分
        for obstacle in obstacles:
            if obstacle.x + obstacle.width < t_rex.x:
                score += 1
                obstacles.remove(obstacle)  # 删除已通过的障碍物

        # 变换背景颜色
        bg_color_change_timer += 1
        if bg_color_change_timer > bg_color_change_interval:
            bg_color = black if bg_color == white else white
            bg_color_change_timer = 0

        screen.fill(bg_color)
        screen.blit(ground, (0, screen_height - ground_height))  # 显示地面

        t_rex.draw(screen)
        for obstacle in obstacles:
            obstacle.draw(screen)

        # 显示得分
        score_text = font.render(f'Score: {score}', True, black if bg_color == white else white)
        screen.blit(score_text, (10, 10))

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

if __name__ == "__main__":
    while True:
        game_loop()

trex.py

python 复制代码
import pygame
import os

class TRex:
    def __init__(self, screen_width, screen_height):
        # 获取当前脚本文件所在的目录
        current_path = os.path.dirname(__file__)
        # 拼接图片文件的完整路径
        image_path = os.path.join(current_path, 'assets', 'trex.png')
        self.image = pygame.image.load(image_path)
        self.image = pygame.transform.scale(self.image, (50, 50))  # 缩放图片
        self.x = 50
        self.y = screen_height - 70 - 20  # 调整位置以适应地面高度
        self.width = 50
        self.height = 50
        self.jump_speed = 20  # 跳跃速度
        self.gravity = 2  # 重力
        self.velocity = 0  # 初始速度
        self.is_jumping = False  # 跳跃状态
        self.screen_width = screen_width
        self.screen_height = screen_height

    def jump(self):
        if not self.is_jumping:
            self.is_jumping = True
            self.velocity = -self.jump_speed

    def update(self):
        if self.is_jumping:
            self.y += self.velocity
            self.velocity += self.gravity

            # 检查是否着地
            if self.y >= self.screen_height - 70 - 20:
                self.y = self.screen_height - 70 - 20
                self.is_jumping = False
                self.velocity = 0

    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y))

obstacles.py

python 复制代码
import pygame
import os

class Obstacle:
    def __init__(self, screen_width, screen_height):
        # 获取当前脚本文件所在的目录
        current_path = os.path.dirname(__file__)
        # 拼接图片文件的完整路径
        image_path = os.path.join(current_path, 'assets', 'cactus.png')
        self.image = pygame.image.load(image_path)
        self.image = pygame.transform.scale(self.image, (50, 50))  # 缩放图片
        self.x = screen_width
        self.y = screen_height - 70 - 20  # 调整位置以适应地面高度
        self.width = 50
        self.height = 50
        self.speed = 10

    def update(self):
        self.x -= self.speed

    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y))

解释
背景颜色切换 :在主程序中,我们使用一个计时器bg_color_change_timer来控制背景颜色的变化。每当计时器达到设定的间隔时,背景颜色在白色和黑色之间切换。
地面调整:调整了T-Rex和障碍物的垂直位置以适应地面高度。

效果图
相关推荐
waterHBO24 分钟前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七1 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AIAdvocate3 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼3 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
FreakStudio5 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy
redcocal7 小时前
地平线秋招
python·嵌入式硬件·算法·fpga开发·求职招聘
artificiali7 小时前
Anaconda配置pytorch的基本操作
人工智能·pytorch·python
RaidenQ7 小时前
2024.9.13 Python与图像处理新国大EE5731课程大作业,索贝尔算子计算边缘,高斯核模糊边缘,Haar小波计算边缘
图像处理·python·算法·课程设计
花生了什么树~.8 小时前
python基础知识(六)--字典遍历、公共运算符、公共方法、函数、变量分类、参数分类、拆包、引用
开发语言·python
Trouvaille ~8 小时前
【Python篇】深度探索NumPy(下篇):从科学计算到机器学习的高效实战技巧
图像处理·python·机器学习·numpy·信号处理·时间序列分析·科学计算