-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapmanager.py
More file actions
152 lines (110 loc) · 4.52 KB
/
mapmanager.py
File metadata and controls
152 lines (110 loc) · 4.52 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import pickle
class Mapmanager():
""" Управление картой """
def __init__(self):
self.model = 'block' # модель кубика лежит в файле block.egg
# # используются следующие текстуры:
self.texture = 'stone.png'
self.colors = [
(0.2, 0.2, 0.35, 1),
(0.2, 0.5, 0.2, 1),
(0.7, 0.2, 0.2, 1),
(0.5, 0.3, 0.0, 1)
] #rgba
# создаём основной узел карты:
self.startNew()
# self.addBlock((0,10, 0))
def startNew(self):
"""создаёт основу для новой карты"""
self.land = render.attachNewNode("Land") # узел, к которому привязаны все блоки карты
def getColor(self, z):
if z < len(self.colors):
return self.colors[z]
else:
return self.colors[len(self.colors) - 1]
def addBlock(self, position, texture = 'stone.png'):
# создаём строительные блоки
self.texture = texture
self.block = loader.loadModel(self.model)
self.block.setTexture(loader.loadTexture(self.texture))
self.block.setPos(position)
#self.color = self.getColor(int(position[2]))
#self.block.setColor(self.color)
self.block.setTag("at", str(position))
self.block.setTag("texture", self.texture)
self.block.reparentTo(self.land)
def clear(self):
"""обнуляет карту"""
self.land.removeNode()
self.startNew()
def loadLand(self, filename):
"""создаёт карту земли из текстового файла, возвращает её размеры"""
self.clear()
with open(filename) as file:
y = 0
for line in file:
x = 0
line = line.split(' ')
for z in line:
for z0 in range(int(z)+1):
block = self.addBlock((x, y, z0))
x += 1
y += 1
return x,y
def findBlocks(self, pos):
return self.land.findAllMatches("=at=" + str(pos))
def isEmpty(self, pos):
blocks = self.findBlocks(pos)
if blocks:
return False
else:
return True
def findHighestEmpty(self, pos):
x, y, z = pos
z = 1
while not self.isEmpty((x, y, z)):
z += 1
return (x, y, z)
def buildBlock(self, pos, texture):
"""Ставим блок с учётом гравитации: """
x, y, z = pos
new = self.findHighestEmpty(pos)
if new[2] <= z + 1:
self.addBlock(new, texture)
def delBlock(self, position):
"""удаляет блоки в указанной позиции """
blocks = self.findBlocks(position)
for block in blocks:
block.removeNode()
def delBlockFrom(self, position):
x, y, z = self.findHighestEmpty(position)
pos = x, y, z - 1
for block in self.findBlocks(pos):
block.removeNode()
def saveMap(self):
"""сохраняет все блоки, включая постройки, в бинарный файл"""
"""возвращает коллекцию NodePath для всех существующих в карте мира блоков"""
blocks = self.land.getChildren()
# открываем бинарный файл на запись
with open('my_map.dat', 'wb') as fout:
# сохраняем в начало файла количество блоков
pickle.dump(len(blocks), fout)
# обходим все блоки
for block in blocks:
# сохраняем позицию
x, y, z = block.getPos()
texture = block.getTag('texture')
data = (int(x), int(y), int(z), texture)
pickle.dump(data, fout)
def loadMap(self):
# удаляем все блоки
self.clear()
# открываем бинарный файл на чтение
with open('my_map.dat', 'rb') as fin:
# считываем количество блоков
length = pickle.load(fin)
for i in range(length):
# считываем позицию
data = pickle.load(fin)
# создаём новый блок
self.addBlock((data[0], data[1], data[2]), data[3])