-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaprender.py
More file actions
291 lines (243 loc) · 10.4 KB
/
maprender.py
File metadata and controls
291 lines (243 loc) · 10.4 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import pygame
import json
import sys
import os
from typing import Dict, List, Any
class MapEditor:
def __init__(self, width=1200, height=800):
pygame.init()
self.screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("JSON Map Editor")
self.clock = pygame.time.Clock()
self.objects_config = {}
self.current_map = {
"width": 100,
"height": 100,
"objects": []
}
self.selected_object_type = "wall"
self.grid_size = 32
self.camera_x = 0
self.camera_y = 0
self.dragging = False
self.last_mouse_pos = (0, 0)
self.colors = {
"background": (40, 40, 40),
"grid": (80, 80, 80),
"panel": (60, 60, 60),
"text": (255, 255, 255)
}
self.load_default_objects()
def load_default_objects(self):
# Загрузка стандартных объектов как в примере
self.objects_config = {
"player": {
"modules": ["sprite", "move", "camera", "collision"],
"params": {
"color": "#FF0000",
"size": 2,
"speed": 1,
"followSpeed": 0.1,
"smooth": True,
"width": 500,
"height": 500,
"collidable": True,
"solid": True,
"checkCollision": True
}
},
"wall": {
"modules": ["square", "collision"],
"params": {
"color": "#3333FF",
"size": 2,
"collidable": True,
"solid": True
}
},
"box": {
"modules": ["square", "collision"],
"params": {
"color": "#11FF11",
"size": 3,
"collidable": True,
"solid": False
}
},
"trawa": {
"modules": ["square", "collision"],
"params": {
"color": "#305530",
"size": 30,
"collidable": True,
"solid": False
}
}
}
def load_objects_config(self, filepath):
try:
with open(filepath, 'r') as f:
self.objects_config = json.load(f)
print(f"Loaded objects config from {filepath}")
except Exception as e:
print(f"Error loading config: {e}")
def save_map(self, filepath):
try:
with open(filepath, 'w') as f:
json.dump(self.current_map, f, indent=2)
print(f"Map saved to {filepath}")
except Exception as e:
print(f"Error saving map: {e}")
def hex_to_rgb(self, hex_color):
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def get_object_color(self, obj_type):
if obj_type in self.objects_config:
color_hex = self.objects_config[obj_type]["params"].get("color", "#FFFFFF")
return self.hex_to_rgb(color_hex)
return (255, 255, 255)
def get_object_size(self, obj_type):
if obj_type in self.objects_config:
return self.objects_config[obj_type]["params"].get("size", 2)
return 2
def world_to_screen(self, x, y):
screen_x = (x - self.camera_x) * self.grid_size
screen_y = (y - self.camera_y) * self.grid_size
return screen_x, screen_y
def screen_to_world(self, screen_x, screen_y):
world_x = screen_x / self.grid_size + self.camera_x
world_y = screen_y / self.grid_size + self.camera_y
return world_x, world_y
def add_object(self, obj_type, x, y):
# Округляем координаты до целых
x = int(x)
y = int(y)
# Проверяем, нет ли уже объекта на этой позиции
for obj in self.current_map["objects"]:
if obj["x"] == x and obj["y"] == y:
return
self.current_map["objects"].append({
"name": obj_type,
"x": x,
"y": y
})
def remove_object(self, x, y):
x = int(x)
y = int(y)
self.current_map["objects"] = [
obj for obj in self.current_map["objects"]
if not (obj["x"] == x and obj["y"] == y)
]
def draw_grid(self):
for x in range(0, self.screen.get_width(), self.grid_size):
pygame.draw.line(self.screen, self.colors["grid"],
(x, 0), (x, self.screen.get_height()), 1)
for y in range(0, self.screen.get_height(), self.grid_size):
pygame.draw.line(self.screen, self.colors["grid"],
(0, y), (self.screen.get_width(), y), 1)
def draw_objects(self):
for obj in self.current_map["objects"]:
obj_type = obj["name"]
x, y = self.world_to_screen(obj["x"], obj["y"])
size = self.get_object_size(obj_type) * self.grid_size
color = self.get_object_color(obj_type)
pygame.draw.rect(self.screen, color, (x, y, size, size))
# Обводка для видимости
pygame.draw.rect(self.screen, (255, 255, 255), (x, y, size, size), 1)
def draw_ui(self):
# Панель инструментов
panel_rect = pygame.Rect(10, 10, 200, 400)
pygame.draw.rect(self.screen, self.colors["panel"], panel_rect)
pygame.draw.rect(self.screen, self.colors["text"], panel_rect, 2)
font = pygame.font.Font(None, 36)
title = font.render("Map Editor", True, self.colors["text"])
self.screen.blit(title, (20, 20))
# Кнопки объектов
y_offset = 60
for obj_type in self.objects_config.keys():
color = self.get_object_color(obj_type)
button_rect = pygame.Rect(20, y_offset, 180, 40)
# Подсветка выбранного объекта
if obj_type == self.selected_object_type:
pygame.draw.rect(self.screen, (100, 100, 100), button_rect)
pygame.draw.rect(self.screen, color, (25, y_offset + 5, 30, 30))
text = pygame.font.Font(None, 24).render(obj_type, True, self.colors["text"])
self.screen.blit(text, (65, y_offset + 10))
y_offset += 50
# Информация
info_text = [
f"Objects: {len(self.current_map['objects'])}",
f"Grid: {self.grid_size}px",
"LMB: Place object",
"RMB: Remove object",
"Mouse wheel: Zoom",
"WASD: Move camera",
"Ctrl+S: Save map",
"Ctrl+L: Load config"
]
y_offset = 450
for line in info_text:
text = pygame.font.Font(None, 20).render(line, True, self.colors["text"])
self.screen.blit(text, (20, y_offset))
y_offset += 25
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # ЛКМ
mouse_x, mouse_y = pygame.mouse.get_pos()
world_x, world_y = self.screen_to_world(mouse_x, mouse_y)
# Проверяем клик по UI
if mouse_x > 220: # Не в панели инструментов
self.add_object(self.selected_object_type, world_x, world_y)
else:
# Выбор объекта из панели
y_offset = 60
for obj_type in self.objects_config.keys():
button_rect = pygame.Rect(20, y_offset, 180, 40)
if button_rect.collidepoint(mouse_x, mouse_y):
self.selected_object_type = obj_type
break
y_offset += 50
elif event.button == 3: # ПКМ
mouse_x, mouse_y = pygame.mouse.get_pos()
if mouse_x > 220:
world_x, world_y = self.screen_to_world(mouse_x, mouse_y)
self.remove_object(world_x, world_y)
elif event.button == 4: # Колесо вверх
self.grid_size = min(64, self.grid_size + 4)
elif event.button == 5: # Колесо вниз
self.grid_size = max(8, self.grid_size - 4)
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_s and pygame.key.get_mods() & pygame.KMOD_CTRL:
self.save_map("map.json")
elif event.key == pygame.K_l and pygame.key.get_mods() & pygame.KMOD_CTRL:
# Загрузка конфига объектов
self.load_objects_config("objects.json")
# Управление камерой
keys = pygame.key.get_pressed()
camera_speed = 10 / self.grid_size
if keys[pygame.K_w]:
self.camera_y -= camera_speed
if keys[pygame.K_s]:
self.camera_y += camera_speed
if keys[pygame.K_a]:
self.camera_x -= camera_speed
if keys[pygame.K_d]:
self.camera_x += camera_speed
return True
def run(self):
running = True
while running:
self.screen.fill(self.colors["background"])
running = self.handle_events()
self.draw_grid()
self.draw_objects()
self.draw_ui()
pygame.display.flip()
self.clock.tick(60)
pygame.quit()
if __name__ == "__main__":
editor = MapEditor()
editor.run()