文章目录
- Google Chrome的离线小恐龙游戏
- 项目结构大纲 📊👣
- 逐步编码过程 🧩💡
- 第一步:项目初始化与主程序框架
- 第二步:实现T-Rex的跳跃功能
- 第三步:添加障碍物和碰撞检测
- 第四步:添加得分机制和显示得分
- 第五步:游戏结束处理和重新开始选项
- 第六步:添加背景和地面
- 效果图
Google Chrome的离线小恐龙游戏
本文章通过详细的列举项目结构大纲和列举逐步编码过程和思路,便于学习者能够更加快速方便地掌握该游戏的开发。
项目结构大纲 📊👣
t_rex_game/
│
├── main.py # 主程序文件
├── trex.py # T-Rex角色类
├── assets/
│ └── trex.png # T-Rex图片文件
├── obstacles.py # 障碍物类
逐步编码过程 🧩💡
第一步:项目初始化与主程序框架
main.py
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
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
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
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与障碍物的碰撞检测。
项目结构大纲 📊👣
t_rex_game/
│
├── main.py # 主程序文件
├── trex.py # T-Rex角色类
├── obstacles.py # 障碍物类
├── assets/
│ └── trex.png # T-Rex图片文件
│ └── cactus.png # 障碍物图片文件
└── utils.py # 工具函数
main.py
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
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
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
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
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
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
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()
第六步:添加背景和地面
项目结构大纲
t_rex_game/
│
├── main.py # 主程序文件
├── trex.py # T-Rex角色类
├── obstacles.py # 障碍物类
├── assets/
│ └── trex.png # T-Rex图片文件
│ └── cactus.png # 障碍物图片文件
│ └── ground.png # 地面图片文件
└── utils.py # 工具函数
main.py
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
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
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和障碍物的垂直位置以适应地面高度。