Repository navigation
Expand file tree
/
Copy pathbackground.py
More file actions
81 lines (72 loc) · 3.11 KB
/
Copy pathbackground.py
File metadata and controls
81 lines (72 loc) · 3.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import pygame
import random
import os
# 游戏常量
SCREEN_WIDTH = 800
OBSTACLE_SPEED = 5
# 加载图像并处理可能的错误
def load_image(file_path, width, height):
try:
if os.path.exists(file_path):
image = pygame.image.load(file_path).convert_alpha()
return pygame.transform.scale(image, (width, height))
else:
print(f"图片文件不存在: {file_path}")
# 创建一个占位图像
image = pygame.Surface((width, height), pygame.SRCALPHA)
image.fill((255, 0, 255, 128)) # 紫色半透明表示缺失的图片
return image
except Exception as e:
print(f"加载图片时出错 {file_path}: {e}")
# 创建一个占位图像
image = pygame.Surface((width, height), pygame.SRCALPHA)
image.fill((255, 0, 255, 128)) # 紫色半透明表示缺失的图片
return image
class Background(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, color, bg_type="building"):
super().__init__()
self.width = width
self.height = height
self.type = bg_type
# 尝试加载背景图片
theme = "city" # 默认主题
if hasattr(self, 'theme'):
theme = self.theme
# 首先检查背景主题目录是否存在
theme_dir = os.path.join("images", "backgrounds", theme)
if not os.path.exists(theme_dir):
print(f"主题目录不存在: {theme_dir}")
# 尝试创建目录
try:
os.makedirs(theme_dir, exist_ok=True)
print(f"创建了主题目录: {theme_dir}")
except Exception as e:
print(f"创建主题目录失败: {e}")
# 根据类型加载不同的背景元素
image_path = os.path.join(theme_dir, f"{bg_type}.png")
if os.path.exists(image_path):
# 直接使用基本文件名
self.image = load_image(image_path, width, height)
else:
# 尝试查找 bg_type_1.png 这样的文件,但只尝试1和2
found_image = False
for i in range(1, 3):
alt_image_path = os.path.join(theme_dir, f"{bg_type}_{i}.png")
if os.path.exists(alt_image_path):
self.image = load_image(alt_image_path, width, height)
found_image = True
break
# 如果找不到任何可用的图片,则创建默认矩形
if not found_image:
self.image = pygame.Surface((width, height))
self.image.fill(color)
print(f"使用了默认矩形代替 {bg_type}")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed = OBSTACLE_SPEED * 0.5 # 背景移动速度较慢,产生视差效果
def update(self):
self.rect.x -= self.speed
# 如果背景元素移出屏幕,则将其移到屏幕右侧
if self.rect.right < 0:
self.rect.left = SCREEN_WIDTH + random.randint(0, 100)