import os
import traceback
from core.map_loader import MapLoader
from core.object_handler import ObjectHandler
from layers.bg_layer import BackgroundLayer
from layers.stories_layer import StoriesLayer
from layers.important_coords import ImportantCoordsLayer
from layers.ladders_layer import LaddersLayer
from layers.dangerous_layer import DangerousLayer
from layers.mission_layer import MissionLayer
from layers.texts_layer import TextsLayer
from entities.enemy_placer import EnemyPlacer
from entities.police_placer import PolicePlacer
from entities.worker_placer import WorkerPlacer
from entities.mover_placer import MoverPlacer
from entities.boss_placer import BossPlacer
def generate(self):
"""Generate the complete map with all layers and entities"""
try:
map_data = self.map_loader.load()
if map_data is None:
print("Failed to load map data.")
return
# Process each layer
for layer_name, layer in self.layers.items():
try:
layer.process(map_data)
print(f"Processed {layer_name} layer successfully.")
except Exception as e:
print(f"Error processing {layer_name} layer: {e}")
traceback.print_exc() # Print detailed traceback for debugging
self.map_loader.save(map_data)
print("Map generation completed successfully.")
except Exception as main_exception:
print(f"Failed to generate the map: {main_exception}")
traceback.print_exc()
if name == "main":
import argparse
code
Assistant
parser = argparse.ArgumentParser(description="Generate game map with all layers and entities")
parser.add_argument("map_path", help="Path to the TMX map file")
args = parser.parse_args()
generator = MapGenerator(args.map_path)
generator.generate()
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import logging
import traceback
from pathlib import Path
from main import MapGenerator
import xml.etree.ElementTree as ET
logging.basicConfig(level=logging.INFO)
class AIMapController:
def init(self):
self.logger = logging.getLogger(name)
self.scaler = MinMaxScaler()
code
# Parameters for different entity types
self.params = {
'enemy_density': 0.15, # Enemies per tile area
'police_density': 0.08, # Police per tile area
'worker_density': 0.2, # Workers per tile area
'trap_density': 0.1, # Traps per tile area
'min_distance': 100, # Minimum distance between entities
'view_range': {
'enemy': 200,
'police': 250,
'worker': 150,
'boss': 400
}
}
def generate_map(self, map_path, difficulty=0.5):
"""Generate a complete map with AI-controlled placement"""
try:
self.logger.info(f"Starting AI map generation with difficulty {difficulty}")
# Initialize map generator
generator = MapGenerator(map_path)
self.logger.info(f"Map path: {map_path}")
# Analyze map structure
map_data = self._analyze_map(map_path)
# Adjust parameters based on difficulty
self._adjust_parameters(difficulty)
# Generate entity positions
positions = self._generate_positions(map_data)
# Apply positions to map
self._apply_positions(generator, positions)
# Generate the final map
generator.generate()
self.logger.info("AI map generation completed successfully")
print("Map generation successful") # Print for Node.js to capture
return True
except Exception as e:
error_message = f"AI map generation failed: {e}\n{traceback.format_exc()}"
self.logger.error(error_message)
print(f"Map generation failed: {e}")
return False
def _analyze_map(self, map_path):
"""Analyze map structure and return useful data"""
self.logger.info("Analyzing map...")
try:
# Get map dimensions and walkable areas
map_size = self._get_map_size(map_path)
walkable_areas = self._get_walkable_areas(map_path)
if not walkable_areas:
self.logger.error("No walkable areas found in the map.")
self._log_error_to_file("No walkable areas found in the map.", map_path)
raise ValueError("No walkable areas found in the map.")
return {
'size': map_size,
'walkable_areas': walkable_areas,
'complexity': self._calculate_complexity(walkable_areas)
}
except Exception as e:
error_message = f"Map analysis failed: {e}\n{traceback.format_exc()}"
self.logger.error(error_message)
self._log_error_to_file(error_message, map_path)
raise
def _get_walkable_areas(self, map_path):
"""Get walkable areas from the collision layer"""
try:
tree = ET.parse(map_path)
root = tree.getroot()
walkable_areas = []
width = int(root.attrib['width'])
height = int(root.attrib['height'])
tile_width = int(root.attrib['tilewidth'])
tile_height = int(root.attrib['tileheight'])
empty_layer = True
for layer in root.findall('layer'):
layer_name = layer.get('name')
if layer_name == 'Tile Layer 1':
empty_layer = False
data = layer.find('data').text.strip().split(',')
for index, tile_id in enumerate(data):
if int(tile_id) == 0: # Walkable tile
x = (index % width) * tile_width
y = (index // width) * tile_height
walkable_areas.append({
'x': x,
'y': y,
'width': tile_width,
'height': tile_height
})
# If layer is empty, consider all tiles walkable
if empty_layer:
for y in range(height):
for x in range(width):
walkable_areas.append({
'x': x * tile_width,
'y': y * tile_height,
'width': tile_width,
'height': tile_height
})
return walkable_areas
except Exception as e:
error_message = f"Error getting walkable areas: {e}\n{traceback.format_exc()}"
self.logger.error(error_message)
self._log_error_to_file(error_message, map_path)
return []
def _adjust_parameters(self, difficulty):
"""Adjust entity parameters based on difficulty"""
try:
scale = 0.5 + difficulty # Scale from 0.5 to 1.5
self.params['enemy_density'] *= scale
self.params['police_density'] *= scale
self.params['trap_density'] *= scale
# Adjust view ranges
for entity_type in self.params['view_range']:
self.params['view_range'][entity_type] = int(
self.params['view_range'][entity_type] * scale
)
except Exception as e:
self.logger.error(f"Error adjusting parameters: {e}\n{traceback.format_exc()}")
raise
def _generate_positions(self, map_data):
"""Generate optimal positions for all entities"""
try:
positions = {
'enemies': [],
'police': [],
'workers': [],
'traps': [],
'bosses': []
}
map_size = map_data['size']
walkable = map_data['walkable_areas']
# Calculate number of entities based on density and map size
area = map_size[0] * map_size[1]
num_enemies = int(area * self.params['enemy_density'])
num_police = int(area * self.params['police_density'])
num_workers = int(area * self.params['worker_density'])
# Generate positions ensuring minimum distance between entities
positions['enemies'] = self._place_entities(
num_enemies, walkable, self.params['min_distance']
)
positions['police'] = self._place_entities(
num_police, walkable, self.params['min_distance']
)
positions['workers'] = self._place_entities(
num_workers, walkable, self.params['min_distance']
)
# Place boss at strategic location
positions['bosses'] = self._place_boss(walkable, positions)
return positions
except Exception as e:
self.logger.error(f"Error generating positions: {e}\n{traceback.format_exc()}")
raise
def _place_entities(self, num_entities, walkable_areas, min_distance):
"""Place entities with minimum distance constraints"""
try:
positions = []
attempts = 0
max_attempts = num_entities * 10
while len(positions) < num_entities and attempts < max_attempts:
pos = self._get_random_walkable_position(walkable_areas)
# Check minimum distance from other entities
if all(self._calculate_distance(pos, p) >= min_distance for p in positions):
positions.append(pos)
attempts += 1
return positions
except Exception as e:
self.logger.error(f"Error placing entities: {e}\n{traceback.format_exc()}")
raise
def _place_boss(self, walkable_areas, existing_positions):
"""Place boss in strategic location"""
try:
# Find position far from other entities but in walkable area
best_pos = None
max_min_distance = 0
for _ in range(100): # Try 100 random positions
pos = self._get_random_walkable_position(walkable_areas)
min_distance = float('inf')
# Check distance from all other entities
for positions in existing_positions.values():
for p in positions:
dist = self._calculate_distance(pos, p)
min_distance = min(min_distance, dist)
if min_distance > max_min_distance:
max_min_distance = min_distance
best_pos = pos
return [best_pos] if best_pos else []
except Exception as e:
self.logger.error(f"Error placing boss: {e}\n{traceback.format_exc()}")
raise
def _get_random_walkable_position(self, walkable_areas):
"""Get random position in walkable area"""
try:
area = np.random.choice(walkable_areas)
x = np.random.uniform(area['x'], area['x'] + area['width'])
y = np.random.uniform(area['y'], area['y'] + area['height'])
return {'x': x, 'y': y}
except Exception as e:
self.logger.error(f"Error getting random walkable position: {e}\n{traceback.format_exc()}")
raise
def _calculate_distance(self, pos1, pos2):
"""Calculate Euclidean distance between two positions"""
try:
return np.sqrt(
(pos1['x'] - pos2['x'])**2 +
(pos1['y'] - pos2['y'])**2
)
except Exception as e:
self.logger.error(f"Error calculating distance: {e}\n{traceback.format_exc()}")
raise
def _apply_positions(self, generator, positions):
"""Apply generated positions to the map"""
try:
for entity_type, pos_list in positions.items():
for pos in pos_list:
if entity_type == 'enemies':
generator.layers['enemies'].add_enemy(pos['x'], pos['y'])
elif entity_type == 'police':
generator.layers['police'].add_police(pos['x'], pos['y'])
elif entity_type == 'workers':
generator.layers['workers'].add_worker(pos['x'], pos['y'])
elif entity_type == 'bosses':
generator.layers['bosses'].add_boss(pos['x'], pos['y'])
except Exception as e:
self.logger.error(f"Error applying positions: {e}\n{traceback.format_exc()}")
raise
def _get_map_size(self, map_path):
"""Get map dimensions from TMX file"""
try:
tree = ET.parse(map_path)
root = tree.getroot()
return (
int(root.get('width', 0)) * int(root.get('tilewidth', 0)),
int(root.get('height', 0)) * int(root.get('tileheight', 0))
)
except Exception as e:
self.logger.error(f"Error getting map size: {e}\n{traceback.format_exc()}")
raise
def _log_error_to_file(self, error_message, map_path):
"""Log error message to a file for further analysis."""
error_log_path = 'error_log.txt'
error_msg = f"Error in {map_path}: {error_message}\n"
with open(error_log_path, 'a') as file:
file.write(error_msg)
self.logger.info(f"Error logged to {error_log_path}")
def _calculate_complexity(self, walkable_areas):
"""Calculate map complexity score"""
try:
return len(walkable_areas) # Complexity based on number of walkable areas
except Exception as e:
self.logger.error(f"Error calculating map complexity: {e}\n{traceback.format_exc()}")
raise
if name == "main":
import argparse
code
parser = argparse.ArgumentParser(description="Generate AI maps.")
parser.add_argument("--map", help="Path to the TMX map file", required=True)
parser.add_argument("--difficulty", type=float, default=0.5, help="Difficulty level for map generation")
args = parser.parse_args()
controller = AIMapController()
success = controller.generate_map(args.map, args.difficulty)
if success:
print("Map generation successful.")
else:
print("Map generation failed.")
import xml.etree.ElementTree as ET
from pathlib import Path
import traceback
class MapLoader:
def init(self, map_path):
self.map_path = Path(map_path)
class ObjectHandler:
def init(self):
self.objects = {}
code
def add_object(self, layer, obj_type, x, y, properties=None):
"""Add object to specified layer"""
if layer not in self.objects:
self.objects[layer] = []
# Center the object
centered_x = x + (properties.get('width', 0) / 2 if properties else 0)
centered_y = y + (properties.get('height', 0) / 2 if properties else 0)
obj = {
'type': obj_type,
'x': centered_x,
'y': centered_y,
'properties': properties or {}
}
self.objects[layer].append(obj)
return obj
def get_objects(self, layer):
"""Get all objects in a layer"""
return self.objects.get(layer, [])
import xml.etree.ElementTree as ET
BossPlacer Class
class BossPlacer:
def init(self):
self.view_range = 400 # Larger view range for bosses
self.bosses = []
code
def add_boss(self, x, y):
"""Add boss position to the list"""
self.bosses.append({'x': x, 'y': y})
def process(self, map_data):
"""Process boss robot placement"""
obj_group = map_data.find(".//objectgroup[@name='Battle_Mecha_Robots']")
if obj_group is None:
obj_group = ET.SubElement(map_data.getroot(), 'objectgroup')
obj_group.set('name', 'Battle_Mecha_Robots')
for boss_pos in self.bosses:
boss_obj = ET.SubElement(obj_group, 'object')
boss_obj.set('x', str(boss_pos['x']))
boss_obj.set('y', str(boss_pos['y']))
boss_obj.set('width', '64')
boss_obj.set('height', '64')
boss_obj.set('type', 'Boss')
# Add properties
properties = ET.SubElement(boss_obj, 'properties')
# Add boss-specific properties
health_prop = ET.SubElement(properties, 'property')
health_prop.set('name', 'health')
health_prop.set('value', '1000')
damage_prop = ET.SubElement(properties, 'property')
damage_prop.set('name', 'damage')
damage_prop.set('value', '50')
attack_range_prop = ET.SubElement(properties, 'property')
attack_range_prop.set('name', 'attack_range')
attack_range_prop.set('value', '150')
# View area
view_prop = ET.SubElement(properties, 'property')
view_prop.set('name', 'view_range')
view_prop.set('value', str(self.view_range))
import xml.etree.ElementTree as ET
class EnemyPlacer:
def init(self):
self.view_range = 200 # Default view range in pixels
self.enemies = []
def process(self, map_data):
"""Process enemy placement in the map"""
for obj_group in map_data.findall(".//objectgroup[@name='enemies']"):
for enemy in obj_group.findall(".//object"):
self._add_view_area(enemy)
def add_enemy(self, x, y):
"""Add enemy position to the list"""
self.enemies.append({'x': x, 'y': y})
code
def _add_view_area(self, enemy):
"""Add view area for enemy"""
x = float(enemy.get('x'))
y = float(enemy.get('y'))
# Default dimensions if not specified in the object
width = float(enemy.get('width', 32)) # Default width (assuming 32 if not specified)
height = float(enemy.get('height', 32)) # Default height (assuming 32 if not specified)
# Create view area rectangle based on the enemy's current position and view range
view_area = {
'x': x - width,
'y': y - height,
'width': width,
'height': height
}
# Add view area properties to enemy object
properties = enemy.find('properties')
if properties is None:
properties = ET.SubElement(enemy, 'properties')
view_prop = ET.SubElement(properties, 'property')
view_prop.set('name', 'view_area')
view_prop.set('value', f"{view_area['x']},{view_area['y']},{view_area['width']},{view_area['height']}")
# Log or print the view area for debugging
print(f"Enemy at ({x},{y}) has view area: {view_area}")
import xml.etree.ElementTree as ET
class MoverPlacer:
def process(self, map_data):
"""Process moving objects with paths"""
obj_group = map_data.find(".//objectgroup[@name='movers']")
if obj_group is None:
obj_group = ET.SubElement(map_data.getroot(), 'objectgroup')
obj_group.set('name', 'movers')
code
for mover in obj_group.findall(".//object"):
self._add_mover_properties(mover)
def _add_mover_properties(self, mover):
properties = mover.find('properties')
if properties is None:
properties = ET.SubElement(mover, 'properties')
# Add movement path
path_prop = ET.SubElement(properties, 'property')
path_prop.set('name', 'path_points')
# Get start and end points from object
start_x = float(mover.get('x'))
start_y = float(mover.get('y'))
width = float(mover.get('width', 32))
# Create a simple back-and-forth path
end_x = start_x + width
path_points = f"{start_x},{start_y} {end_x},{start_y}"
path_prop.set('value', path_points)
# Add velocity
velocity_prop = ET.SubElement(properties, 'property')
velocity_prop.set('name', 'velocity')
velocity_prop.set('value', '100')
import xml.etree.ElementTree as ET
class PolicePlacer:
def init(self):
self.view_range = 250 # Larger view range for cyber police
self.polices = []
code
def add_police(self, x, y):
"""Add police position to the list"""
self.polices.append({'x': x, 'y': y})
def process(self, map_data):
"""Process cyber police placement"""
# Get or create object group for polices
obj_group = map_data.find(".//objectgroup[@name='polices']")
if obj_group is None:
obj_group = ET.SubElement(map_data.getroot(), 'objectgroup')
obj_group.set('name', 'polices')
# Process each police position
for police_pos in self.polices:
police_obj = ET.SubElement(obj_group, 'object')
police_obj.set('x', str(police_pos['x']))
police_obj.set('y', str(police_pos['y']))
police_obj.set('width', '48')
police_obj.set('height', '48')
police_obj.set('type', 'Police')
self._add_police_properties(police_obj)
# Update existing police objects
for police in obj_group.findall(".//object"):
self._center_police_and_add_properties(police)
def _add_police_properties(self, police):
"""Add default properties to a police object"""
properties = police.find('properties')
if properties is None:
properties = ET.SubElement(police, 'properties')
# Add view range property
view_prop = ET.SubElement(properties, 'property')
view_prop.set('name', 'view_range')
view_prop.set('value', str(self.view_range))
# Add patrol behavior property
patrol_prop = ET.SubElement(properties, 'property')
patrol_prop.set('name', 'patrol_type')
patrol_prop.set('value', 'aggressive')
def _center_police_and_add_properties(self, police):
"""Center police object and add specific properties"""
x = float(police.get('x', 0))
y = float(police.get('y', 0))
width = float(police.get('width', 48))
height = float(police.get('height', 48))
# Center the police object
police.set('x', str(x + width / 2))
police.set('y', str(y + height / 2))
# Add view area property
properties = police.find('properties')
if properties is None:
properties = ET.SubElement(police, 'properties')
view_area = {
'x': x - self.view_range / 2,
'y': y - self.view_range / 2,
'width': self.view_range,
'height': self.view_range
}
view_area_prop = ET.SubElement(properties, 'property')
view_area_prop.set('name', 'view_area')
view_area_prop.set('value', str(view_area))
import xml.etree.ElementTree as ET
WorkerPlacer Class
class WorkerPlacer:
def init(self):
self.view_range = 150 # Default view range for workers
self.workers = []
#bunu da ilk başladığında colliderlar tanımlı değilse tanımlasın
#scripts/collision_detector.py
import cv2
import logging
import numpy as np
from pytiled_parser import parse_tileset, Tile,Size
from pytiled_parser.common_types import OrderedPair
from pytiled_parser.tiled_object import TiledObject, Polygon
from pytiled_parser.layer import ObjectLayer
import xml.etree.ElementTree as ET
import traceback
from collections import OrderedDict
from pathlib import Path
import argparse
def save_tileset(tileset, tsx_path,output):
try:
# TSX dosyasını aç ve kök düğümü al
tree = ET.parse(tsx_path)
root = tree.getroot()
code
# `tiles` özelliği yoksa başlat
if tileset.tiles is None:
tileset.tiles = OrderedDict()
# Her bir tile için işlem yap
for tile_id, tile in tileset.tiles.items():
if tile.objects:
# Mevcut `tile` elemanını bul veya oluştur
tile_elem = root.find(f"./tile[@id='{tile_id}']")
if tile_elem is None:
tile_elem = ET.SubElement(root, 'tile', id=str(tile_id))
else:
# Önceki `objectgroup` elemanlarını kaldır
for og in tile_elem.findall('objectgroup'):
tile_elem.remove(og)
# Yeni `objectgroup` oluştur
og_elem = ET.SubElement(tile_elem, 'objectgroup', draworder="index")
for obj in tile.objects.tiled_objects: # Düzeltilmiş erişim
obj_attribs = {
'id': str(obj.id),
'x': str(obj.coordinates.x), # Access x from coordinates
'y': str(obj.coordinates.y), # Access y from coordinates
}
if hasattr(obj, 'polygon') and obj.polygon: # Check if the polygon attribute exists
# Polygon collider için işlem
object_elem = ET.SubElement(og_elem, 'object', obj_attribs)
points_str = ' '.join(['{0},{1}'.format(pt.x, pt.y) for pt in obj.polygon.points])
ET.SubElement(object_elem, 'polygon', points=points_str)
else:
# Rectangle collider için işlem
obj_attribs.update({
'width': str(obj.size.width), # Access width from size
'height': str(obj.size.height), # Access height from size
})
ET.SubElement(og_elem, 'object', obj_attribs)
# Güncellenmiş TSX dosyasını kaydet
output_file = output if (output and not Path(output).is_dir()) else tsx_path
tree.write(output_file, encoding='utf-8', xml_declaration=True)
logging.info(f"TSX dosyası başarıyla kaydedildi: {output_file}")
except ET.ParseError as e:
logging.error(f"TSX dosyası okunurken/parçalanırken hata: {e}")
except Exception as e:
logging.error(f"save_tileset fonksiyonunda beklenmeyen bir hata oluştu: {e}")
def process_map(image_path, tsx_path, sensitivity=100,output=None):
"""
Processes the tileset image, detects colliders for each tile,
and updates the TSX file with collider data.
"""
try:
logging.info("Starting image processing...")
code
# Parse the TSX file
tileset = parse_tileset(tsx_path)
if not tileset:
logging.error(f"Tileset could not be parsed: {tsx_path}")
return
# Ensure tiles dictionary is initialized
if tileset.tiles is None:
tileset.tiles = {}
# Load the tileset image
tileset_image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if tileset_image is None:
logging.error(f"Tileset image could not be loaded: {image_path}")
return
tile_width = tileset.tile_width
tile_height = tileset.tile_height
# Calculate the number of tiles in x and y directions
tiles_x = tileset_image.shape[1] // tile_width
tiles_y = tileset_image.shape[0] // tile_height
for ty in range(tiles_y):
for tx in range(tiles_x):
# Extract the tile image
tile_image = tileset_image[
ty * tile_height : (ty + 1) * tile_height,
tx * tile_width : (tx + 1) * tile_width
]
# Process the tile image
edges = cv2.Canny(tile_image, threshold1=sensitivity, threshold2=sensitivity * 2)
# Find contours in the tile
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
# Compute the global tile ID
tile_id = ty * tiles_x + tx
# Get or create the tile in the tileset
tile = tileset.tiles.get(tile_id)
if not tile:
tile = Tile(id=tile_id)
tileset.tiles[tile_id] = tile
# Create an ObjectLayer for the tile if it doesn't exist
logging.info(tile)
if tile.objects is None:
tile.objects = ObjectLayer(
name="Colliders",
draw_order="index",
tiled_objects=[] # Corrected parameter name
)
# Add collision objects to the tile's ObjectLayer
for cnt in contours:
# Calculate contour area and tile area
contour_area = cv2.contourArea(cnt)
tile_area = tile_width * tile_height
area_ratio = contour_area / tile_area
try:
if area_ratio > 0.5:
# Create a polygon collider
points = cnt.reshape(-1, 2)
points[:, 0] = np.clip(points[:, 0], 0, tile_width)
points[:, 1] = np.clip(points[:, 1], 0, tile_height)
polygon_points = [OrderedPair(x=float(pt[0]), y=float(pt[1])) for pt in points]
collider = TiledObject(
id=len(tile.objects.tiled_objects) + 1,
coordinates=OrderedPair(x=0, y=0), # Coordinates (x, y)
size=Size(width=0, height=0), # Size (width, height) default to 0
rotation=0, # Default rotation
visible=True, # Default visible
name="", # Empty name
class_="", # Empty class
properties={}, # Empty properties dictionary
polygon=Polygon(points=polygon_points) # Polygon points
)
else:
# Create a rectangle collider
x, y, w, h = cv2.boundingRect(cnt)
x = max(0, min(x, tile_width))
y = max(0, min(y, tile_height))
w = min(w, tile_width - x)
h = min(h, tile_height - y)
# Assuming 'coordinates' is an OrderedPair (x, y), and 'size' is a Size (width, height)
collider = TiledObject(
id=len(tile.objects.tiled_objects) + 1, # Unique ID
coordinates=OrderedPair(x=float(x), y=float(y)), # Coordinates (x, y)
size=Size(width=float(w), height=float(h)), # Size (width, height)
rotation=0, # Default rotation
visible=True, # Default visible
name="", # Empty name
class_="", # Empty class
properties={} # Empty properties dictionary
)
# Append the collider to the tile's object layer
tile.objects.tiled_objects.append(collider)
except Exception as e:
# Log the error along with the line number
logging.error(f"Error while processing tile ({tx}, {ty}): {e}")
logging.error(f"Error details: {traceback.format_exc()}")
# Save the modified tileset
save_tileset(tileset, tsx_path,output)
logging.info("Collider settings successfully added.")
except Exception as e:
# Log the general error
logging.error(f"An unexpected error occurred: {e}")
logging.error(f"Error details: {traceback.format_exc()}")
User input for sensitivity value
#image_path = "harita.png" # Path to the tileset image
#tsx_path = r"C:\Users\Casper\Downloads\project-bolt-sb1-rfjg3a (1)\project\project_map\tsx\fabrika.tsx"
#sensitivity = int(input("Enter sensitivity value (e.g., 100): "))
#output = input("Enter output directory path: ")
if name == "main":
parser = argparse.ArgumentParser(description="Process tileset and add colliders.")
parser.add_argument("image_path", type=str, help="Path to the tileset image")
parser.add_argument("tsx_path", type=str, help="Path to the TSX file")
parser.add_argument("sensitivity", type=int, help="Sensitivity value for edge detection")
parser.add_argument("--output", type=str, default=None, help="Output directory path (optional)")
// Ana fonksiyon
async function main() {
try {
const mapPath = path.join(__dirname, 'maps', "boş", "tsx", 'level1.tmx');
code
// Map dosyasının var olup olmadığını kontrol edelim
console.log(`Checking if map file exists at: ${mapPath}`);
if (!fs.existsSync(mapPath)) {
console.error(`Map file does not exist: ${mapPath}`);
return;
}
console.log('Starting map generation...');
// Map oluşturma fonksiyonunu çalıştır
await generateMap(mapPath, 0.7);
console.log('Map generation completed successfully');
} catch (error) {
console.error('Map generation failed:', error);
process.exit(1);
}
}
// Eğer bu dosya doğrudan çalıştırılıyorsa, main fonksiyonunu çağır
if (require.main === module) {
main();
}
buna şu özellikleri ekle:
ilk olarak bu çalışacak
import cv2
import logging
import numpy as np
from pytiled_parser import parse_tileset, Tile,Size
from pytiled_parser.common_types import OrderedPair
from pytiled_parser.tiled_object import TiledObject, Polygon
from pytiled_parser.layer import ObjectLayer
import xml.etree.ElementTree as ET
import traceback
from collections import OrderedDict
from pathlib import Path
def save_tileset(tileset, tsx_path,output):
try:
# TSX dosyasını aç ve kök düğümü al
tree = ET.parse(tsx_path)
root = tree.getroot()
code
# `tiles` özelliği yoksa başlat
if tileset.tiles is None:
tileset.tiles = OrderedDict()
# Her bir tile için işlem yap
for tile_id, tile in tileset.tiles.items():
if tile.objects:
# Mevcut `tile` elemanını bul veya oluştur
tile_elem = root.find(f"./tile[@id='{tile_id}']")
if tile_elem is None:
tile_elem = ET.SubElement(root, 'tile', id=str(tile_id))
else:
# Önceki `objectgroup` elemanlarını kaldır
for og in tile_elem.findall('objectgroup'):
tile_elem.remove(og)
# Yeni `objectgroup` oluştur
og_elem = ET.SubElement(tile_elem, 'objectgroup', draworder="index")
for obj in tile.objects.tiled_objects: # Düzeltilmiş erişim
obj_attribs = {
'id': str(obj.id),
'x': str(obj.coordinates.x), # Access x from coordinates
'y': str(obj.coordinates.y), # Access y from coordinates
}
if hasattr(obj, 'polygon') and obj.polygon: # Check if the polygon attribute exists
# Polygon collider için işlem
object_elem = ET.SubElement(og_elem, 'object', obj_attribs)
points_str = ' '.join(['{0},{1}'.format(pt.x, pt.y) for pt in obj.polygon.points])
ET.SubElement(object_elem, 'polygon', points=points_str)
else:
# Rectangle collider için işlem
obj_attribs.update({
'width': str(obj.size.width), # Access width from size
'height': str(obj.size.height), # Access height from size
})
ET.SubElement(og_elem, 'object', obj_attribs)
# Güncellenmiş TSX dosyasını kaydet
output_file = output if (output and not Path(output).is_dir()) else tsx_path
tree.write(output_file, encoding='utf-8', xml_declaration=True)
logging.info(f"TSX dosyası başarıyla kaydedildi: {output_file}")
except ET.ParseError as e:
logging.error(f"TSX dosyası okunurken/parçalanırken hata: {e}")
except Exception as e:
logging.error(f"save_tileset fonksiyonunda beklenmeyen bir hata oluştu: {e}")
def process_map(image_path, tsx_path, sensitivity=100,output=None):
"""
Processes the tileset image, detects colliders for each tile,
and updates the TSX file with collider data.
"""
try:
logging.info("Starting image processing...")
code
# Parse the TSX file
tileset = parse_tileset(tsx_path)
if not tileset:
logging.error(f"Tileset could not be parsed: {tsx_path}")
return
# Ensure tiles dictionary is initialized
if tileset.tiles is None:
tileset.tiles = {}
# Load the tileset image
tileset_image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if tileset_image is None:
logging.error(f"Tileset image could not be loaded: {image_path}")
return
tile_width = tileset.tile_width
tile_height = tileset.tile_height
# Calculate the number of tiles in x and y directions
tiles_x = tileset_image.shape[1] // tile_width
tiles_y = tileset_image.shape[0] // tile_height
for ty in range(tiles_y):
for tx in range(tiles_x):
# Extract the tile image
tile_image = tileset_image[
ty * tile_height : (ty + 1) * tile_height,
tx * tile_width : (tx + 1) * tile_width
]
# Process the tile image
edges = cv2.Canny(tile_image, threshold1=sensitivity, threshold2=sensitivity * 2)
# Find contours in the tile
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
# Compute the global tile ID
tile_id = ty * tiles_x + tx
# Get or create the tile in the tileset
tile = tileset.tiles.get(tile_id)
if not tile:
tile = Tile(id=tile_id)
tileset.tiles[tile_id] = tile
# Create an ObjectLayer for the tile if it doesn't exist
logging.info(tile)
if tile.objects is None:
tile.objects = ObjectLayer(
name="Colliders",
draw_order="index",
tiled_objects=[] # Corrected parameter name
)
# Add collision objects to the tile's ObjectLayer
for cnt in contours:
# Calculate contour area and tile area
contour_area = cv2.contourArea(cnt)
tile_area = tile_width * tile_height
area_ratio = contour_area / tile_area
try:
if area_ratio > 0.5:
# Create a polygon collider
points = cnt.reshape(-1, 2)
points[:, 0] = np.clip(points[:, 0], 0, tile_width)
points[:, 1] = np.clip(points[:, 1], 0, tile_height)
polygon_points = [OrderedPair(x=float(pt[0]), y=float(pt[1])) for pt in points]
collider = TiledObject(
id=len(tile.objects.tiled_objects) + 1,
coordinates=OrderedPair(x=0, y=0), # Coordinates (x, y)
size=Size(width=0, height=0), # Size (width, height) default to 0
rotation=0, # Default rotation
visible=True, # Default visible
name="", # Empty name
class_="", # Empty class
properties={}, # Empty properties dictionary
polygon=Polygon(points=polygon_points) # Polygon points
)
else:
# Create a rectangle collider
x, y, w, h = cv2.boundingRect(cnt)
x = max(0, min(x, tile_width))
y = max(0, min(y, tile_height))
w = min(w, tile_width - x)
h = min(h, tile_height - y)
# Assuming 'coordinates' is an OrderedPair (x, y), and 'size' is a Size (width, height)
collider = TiledObject(
id=len(tile.objects.tiled_objects) + 1, # Unique ID
coordinates=OrderedPair(x=float(x), y=float(y)), # Coordinates (x, y)
size=Size(width=float(w), height=float(h)), # Size (width, height)
rotation=0, # Default rotation
visible=True, # Default visible
name="", # Empty name
class_="", # Empty class
properties={} # Empty properties dictionary
)
# Append the collider to the tile's object layer
tile.objects.tiled_objects.append(collider)
except Exception as e:
# Log the error along with the line number
logging.error(f"Error while processing tile ({tx}, {ty}): {e}")
logging.error(f"Error details: {traceback.format_exc()}")
# Save the modified tileset
save_tileset(tileset, tsx_path,output)
logging.info("Collider settings successfully added.")
except Exception as e:
# Log the general error
logging.error(f"An unexpected error occurred: {e}")
logging.error(f"Error details: {traceback.format_exc()}")
User input for sensitivity value
image_path = "harita.png" # Path to the tileset image
tsx_path = r".\maps\boş\tsx\fabrika.tmx"
sensitivity = int(input("Enter sensitivity value (e.g., 100): "))
output = input("Enter output directory path: ")
await tileBaseMapForGeneration(mapType,width,height,{x: perTileSize.x,y:perTileSize.y}); # bunu hazırla ve diğer iki fonksiyonu bunlara uyarla hata istemiyorum
await generateMap(mapPath, 0.7,bu parametre haritanın);
mapType haritanın tiled üzerindeki tarzı yani
platform ya da üstten bakış ya da izometirk olabilir
width height ise isminden anlaşılıyor
perTileSize da ismi ile alakalı zaten
Certainly! I'll help you integrate the requested features into your code.
Objective:
First, the process_map function should run to process the tileset image and add colliders to the TSX file.
Then, tileBaseMapForGeneration should create a base TMX map with the specified parameters (mapType, width, height, perTileSize).
Finally, generateMap should generate the map using the modified tileset and base map.
Here's how you can adjust your code:
1. Adjust the Node.js code to include these function calls:
First, we need to modify your Node.js script to:
Call process_map to process the tileset image and update the TSX file.
Call tileBaseMapForGeneration to create the base map.
Call generateMap to generate the final map.
Updated main.js (Node.js code):
javascript
const { PythonShell } = require('python-shell');
const path = require('path');
const fs = require('fs');
// Function to process the tileset image and update the TSX file
function processTilesetImage(imagePath, tsxPath, sensitivity = 100, output = null) {
return new Promise((resolve, reject) => {
console.log(`Processing tileset image: ${imagePath}`);
const options = {
mode: 'text',
pythonPath: 'python',
pythonOptions: ['-u'], // unbuffered output
scriptPath: __dirname,
args: [imagePath, tsxPath, sensitivity.toString()]
};
PythonShell.run('process_tileset.py', options, (err, results) => {
if (err) {
console.error('Error processing tileset image:', err);
reject(err);
} else {
console.log('Tileset image processed successfully');
resolve(results);
}
});
});
}
// Function to create the base TMX map
function tileBaseMapForGeneration(mapType, width, height, perTileSize, outputMapPath) {
return new Promise((resolve, reject) => {
console.log(`Creating base map with type: ${mapType}, width: ${width}, height: ${height}, tileSize: ${perTileSize.x}x${perTileSize.y}`);
// Assuming we have a Python script to create the base map
const options = {
mode: 'text',
pythonPath: 'python',
pythonOptions: ['-u'],
scriptPath: __dirname,
args: [
'--map_type', mapType,
'--width', width.toString(),
'--height', height.toString(),
'--tile_width', perTileSize.x.toString(),
'--tile_height', perTileSize.y.toString(),
'--output', outputMapPath
]
};
PythonShell.run('create_base_map.py', options, (err, results) => {
if (err) {
console.error('Error creating base map:', err);
reject(err);
} else {
console.log('Base map created successfully');
resolve(results);
}
});
});
}
// Map generation function
function generateMap(mapPath, difficulty = 0.5) {
return new Promise((resolve, reject) => {
console.log(`Starting map generation with path: ${mapPath} and difficulty: ${difficulty}`);
const options = {
mode: 'text',
pythonPath: 'python', // Python interpreter path
pythonOptions: ['-u'], // unbuffered output
scriptPath: __dirname, // Script directory
args: [
'--map', mapPath,
'--difficulty', difficulty.toString()
]
};
PythonShell.run('ai_controller.py', options, (err, results) => {
if (err) {
console.error('Error running AI controller:', err);
reject(err);
} else {
console.log('Python script executed successfully');
if (results && results.length > 0) {
console.log('Map generation completed:');
results.forEach(result => console.log(result));
resolve(results);
} else {
console.error('No results returned or unexpected output.');
reject(new Error('No results returned.'));
}
}
});
});
}
// Main function
async function main() {
try {
// Paths to your tileset image and TSX file
const imagePath = path.join(__dirname, 'maps', 'boş', 'fabrika (2).png');
const tsxPath = path.join(__dirname, 'maps', 'boş', 'tsx', 'fabrika.tmx');
// Process the tileset image to add colliders
await processTilesetImage(imagePath, tsxPath, 100);
// Map parameters
const mapType = 'platform'; // or 'top-down', 'isometric'
const width = 100; // example width
const height = 50; // example height
const perTileSize = { x: 32, y: 32 }; // example tile size
// Output map path
const outputMapPath = path.join(__dirname, 'output', 'newMaps', 'level1.tmx');
// Create the base map
await tileBaseMapForGeneration(mapType, width, height, perTileSize, outputMapPath);
// Check if the base map was created
if (!fs.existsSync(outputMapPath)) {
console.error(`Base map file does not exist: ${outputMapPath}`);
return;
}
console.log('Starting map generation...');
// Generate the map using the base map
await generateMap(outputMapPath, 0.7);
console.log('Map generation completed successfully');
} catch (error) {
console.error('Map generation failed:', error);
process.exit(1);
}
}
// Run the main function if this file is executed directly
if (require.main === module) {
main();
}
Explanation:
processTilesetImage: This function calls the process_tileset.py script (renamed from process_map for clarity) to process the tileset image and update the TSX file with collider data.
tileBaseMapForGeneration: This function calls a new Python script create_base_map.py which we'll create next. It generates a base TMX map with the specified parameters.
generateMap: This function remains mostly the same, except that it now uses the output map path from the previous step.
main: Adjusted to call these functions in the correct order. Paths and parameters are updated according to your requirements.
2. Create create_base_map.py script to generate the base TMX map.
We'll need a Python script that can generate a base TMX map file with the specified parameters.
create_base_map.py:
python
import argparse
import xml.etree.ElementTree as ET
def create_base_map(map_type, width, height, tile_width, tile_height, output):
# Create the root element
map_elem = ET.Element('map')
map_elem.set('version', '1.0')
map_elem.set('tiledversion', '1.8.2') # Adjust as needed
map_elem.set('orientation', map_type)
map_elem.set('renderorder', 'right-down')
map_elem.set('width', str(width))
map_elem.set('height', str(height))
map_elem.set('tilewidth', str(tile_width))
map_elem.set('tileheight', str(tile_height))
# Add a tileset reference (assuming you have a tileset)
tileset_elem = ET.SubElement(map_elem, 'tileset')
tileset_elem.set('firstgid', '1')
tileset_elem.set('source', 'fabrika.tmx') # Adjust the filename as needed
# Add an empty layer (you can add more layers as needed)
layer_elem = ET.SubElement(map_elem, 'layer')
layer_elem.set('name', 'Tile Layer 1')
layer_elem.set('width', str(width))
layer_elem.set('height', str(height))
data_elem = ET.SubElement(layer_elem, 'data')
data_elem.set('encoding', 'csv')
# Fill the layer with zeros (empty tiles)
tile_count = width * height
data_elem.text = ',\n'.join(['0'] * tile_count)
# Write the XML to the output file
tree = ET.ElementTree(map_elem)
tree.write(output, encoding='utf-8', xml_declaration=True)
print(f"Base map created at {output}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create base TMX map.")
parser.add_argument('--map_type', required=True, choices=['orthogonal', 'isometric', 'staggered', 'hexagonal'], help='Map orientation/type')
parser.add_argument('--width', type=int, required=True, help='Map width in tiles')
parser.add_argument('--height', type=int, required=True, help='Map height in tiles')
parser.add_argument('--tile_width', type=int, required=True, help='Tile width in pixels')
parser.add_argument('--tile_height', type=int, required=True, help='Tile height in pixels')
parser.add_argument('--output', required=True, help='Output TMX file path')
args = parser.parse_args()
# Adjust map_type to Tiled's orientation values
map_type_mapping = {
'platform': 'orthogonal',
'top-down': 'orthogonal',
'isometric': 'isometric'
}
orientation = map_type_mapping.get(args.map_type, 'orthogonal')
create_base_map(orientation, args.width, args.height, args.tile_width, args.tile_height, args.output)
Explanation:
This script generates a base TMX map file with the specified dimensions and tile sizes.
It assumes you have a tileset file named fabrika.tmx, adjust the tileset filename as needed.
The map orientation is adjusted according to the map_type parameter.
We fill the initial layer with zeros (empty tiles), you can adjust as needed.
3. Adjust the Python scripts to handle any new parameters.
No changes needed for ai_controller.py and AIMapController unless you require specific handling of the map type or tile sizes.
However, if your AI map generator needs to know about the map type or tile sizes, you should pass these parameters to the AIMapController and adjust the generate_map function.
For example, you might adjust generate_map as:
python
def generate_map(self, map_path, difficulty=0.5, map_type='orthogonal', tile_width=32, tile_height=32):
# Use map_type, tile_width, tile_height as needed
pass
And update your command-line argument parsing in ai_controller.py to accept these new parameters.
4. Ensure process_map function can be called from Node.js.
Since the process_map function is in the script you provided, we just need to adjust it to be called from the command line and accept parameters.
Adjust process_tileset.py (renamed from collision_detector.py):
python
import cv2
import logging
import numpy as np
from pytiled_parser import parse_tileset, Tile, Size
from pytiled_parser.common_types import OrderedPair
from pytiled_parser.tiled_object import TiledObject, Polygon
from pytiled_parser.layer import ObjectLayer
import xml.etree.ElementTree as ET
import traceback
from collections import OrderedDict
from pathlib import Path
import argparse
# Configure logging
logging.basicConfig(filename='process_map.log', level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
def save_tileset(tileset, tsx_path, output):
# [The function remains the same as in your original script]
pass
def process_map(image_path, tsx_path, sensitivity=100, output=None):
# [The function remains the same as in your original script]
pass
def main():
parser = argparse.ArgumentParser(description="Process tileset and add colliders.")
parser.add_argument("image_path", type=str, help="Path to the tileset image")
parser.add_argument("tsx_path", type=str, help="Path to the TSX file")
parser.add_argument("sensitivity", type=int, help="Sensitivity value for edge detection")
parser.add_argument("--output", type=str, default=None, help="Output directory path (optional)")
args = parser.parse_args()
process_map(args.image_path, args.tsx_path, args.sensitivity, args.output)
if __name__ == "__main__":
main()
Explanation:
Adjusted the script to accept command-line arguments and have a main function.
Renamed the script to process_tileset.py for clarity.
Ensure that the paths in your scripts are correct relative to where you run them.
Adjust the paths if your directory structure is different.
Make sure all the Python scripts have the proper shebang line (e.g., #!/usr/bin/env python3) if needed.
Install any required Python packages (e.g., pytiled-parser, opencv-python, numpy).
7. Testing:
Run main.js using Node.js and ensure that each step completes without errors.
Monitor the console output for any messages or errors.
Check that the fabrika.tmx file is updated with collider data.
Verify that the level1.tmx base map is created with the correct parameters.
Ensure that the final map generation completes successfully.
8. Handling Map Types:
If you need to handle different map types ('platform', 'top-down', 'isometric') differently in your generation scripts, you should adjust the scripts accordingly.
For instance, in AIMapController, you can add logic to handle different map orientations.
By following these steps and adjusting your code as shown, you should be able to incorporate the features you requested.
Please make sure to test each part thoroughly and adjust paths and parameters according to your specific setup.
If you encounter any errors or need further assistance, feel free to ask!