from unsloth import FastModel from unsloth.chat_templates import get_chat_template from unsloth import FastLanguageModel from transformers import TextStreamer from utils.create_img import convert_level_to_png import random import numpy as np game_settings = { "mario": { "empty_space": "-", "line_quantity": 16, "column_quantity": 50, "convert_function": convert_level_to_png, # "tiles_dir": './assets/mario', "tiles_dir": './assets', "add_ground": "X", "expected_output_size": 800 } } def load_model_by_type(model_path, model_type, max_seq_length=2048, dtype=None, load_in_4bit=True): """Load model based on model type""" if model_type in ["llama-3", "qwen-2.5", "llama3", "qwen2.5"]: model, tokenizer = FastLanguageModel.from_pretrained( model_name=model_path, max_seq_length=max_seq_length, dtype=dtype, load_in_4bit=load_in_4bit, ) FastLanguageModel.for_inference(model) elif model_type in ["qwen-3", "qwen3"]: model, tokenizer = FastLanguageModel.from_pretrained( model_name=model_path, max_seq_length=max_seq_length, dtype=dtype, load_in_4bit=load_in_4bit, ) FastLanguageModel.for_inference(model) elif model_type in ["gemma-3", "gemma3", "gemma"]: model, tokenizer = FastModel.from_pretrained( model_name=model_path, max_seq_length=max_seq_length, load_in_4bit=load_in_4bit, load_in_8bit=False, full_finetuning=False, ) FastModel.for_inference(model) tokenizer = get_chat_template( tokenizer, chat_template="gemma-3", ) else: raise ValueError(f"Unsupported model type: {model_type}") return model, tokenizer def generate_with_model(model, tokenizer, prompt, model_type, temperature=0.7): if model_type in ["gemma-3", "gemma3", "gemma"]: tokenizer = get_chat_template( tokenizer, chat_template = "gemma-3", ) messages = [{ "role": "user", "content": [{ "type" : "text", "text" : prompt, }] }] # text = tokenizer.apply_chat_template( # messages, # add_generation_prompt = True, # Must add for generation # ) # outputs = model.generate( # **tokenizer([text], return_tensors = "pt").to("cuda"), # max_new_tokens = 1024, # temperature = temperature, top_p = 0.95, top_k = 64, # ) inputs = tokenizer.apply_chat_template( messages, add_generation_prompt = True, tokenize = True, return_tensors = "pt", return_dict = True, ) outputs = model.generate( **inputs.to("cuda"), max_new_tokens = 1024, temperature = temperature, top_p = 0.95, top_k = 64, ) elif model_type in ["qwen-3", "qwen3"]: messages = [ {"role" : "user", "content" : prompt} ] text = tokenizer.apply_chat_template( messages, tokenize = False, add_generation_prompt = True, enable_thinking = False, ) outputs = model.generate( **tokenizer(text, return_tensors = "pt").to("cuda"), max_new_tokens = 1024, temperature = temperature, top_p = 0.8, top_k = 20, streamer = TextStreamer(tokenizer, skip_prompt = True), ) elif model_type in ["llama-3", "qwen-2.5", "llama3", "qwen2.5"]: messages = [ {"role": "user", "content": prompt}, ] inputs = tokenizer.apply_chat_template( messages, tokenize = True, add_generation_prompt = True, # Must add for generation return_tensors = "pt", ).to("cuda") outputs = model.generate(input_ids = inputs, max_new_tokens = 1024, use_cache = True, temperature = temperature, min_p = 0.1) else: raise ValueError(f"Unsupported model type: {model_type}") return tokenizer.batch_decode(outputs) def generate_prompt_addition(prompt_gen: str | int) -> tuple[str, str]: """ Generate prompt text based on prompt_gen mode. Args: prompt_gen: "full", "random", empty string, or an integer (number of classes) Returns: tuple: (full_prompt, base_prompt) where: - full_prompt: Complete prompt with prefix - base_prompt: Prompt content without prefix (empty string if prompt_gen is empty) """ if not prompt_gen or prompt_gen == "": return "", "" PREFIXES = [ "Generate a level with", "Create a level that has", "Please generate a level with", "Build a level featuring", "Create a level featuring", "Give me a level that includes", "Make a level that includes", "Produce a level featuring", "Craft a level that includes", "I need a level that has", "I want to see a level that includes", "Design a level with", "I want a level with", "Make a level with", "Design a level around", "Generate levels with", "Construct a level featuring", "I want a level that has", "I would like a level that has", ] descriptors = ["no", "a few", "some", "many"] classes = [ "coin block", "pipes", "hard blocks", "breakable blocks", "koopas", "coins", "special enemies", "goombas", "powerups", "ground blocks" ] special_descriptors = { "difficulty": ["easy", "medium", "hard"], "level": ["overworld", "underworld"], "elevation": ["high", "low"] } # Choose random prefix prefix = random.choice(PREFIXES) # Handle numeric prompt_gen (exact number of classes) if isinstance(prompt_gen, int): num_classes = prompt_gen if num_classes <= 0: return "", "" if num_classes > len(classes): num_classes = len(classes) # Randomly select exactly num_classes selected_classes = random.sample(classes, num_classes) prompt_parts = [] for class_name in selected_classes: descriptor = random.choice(descriptors) prompt_parts.append(f"{descriptor} {class_name}") # Don't include special descriptors for numeric prompts (or you can add them if needed) content = ", ".join(prompt_parts) base_prompt = content full_prompt = f"{prefix} {content}" return full_prompt, base_prompt if prompt_gen == "full": # Use all classes with random descriptors prompt_parts = [] for class_name in classes: descriptor = random.choice(descriptors) prompt_parts.append(f"{descriptor} {class_name}") # Add special descriptors prompt_parts.append(f"{random.choice(special_descriptors['level'])} level") prompt_parts.append(f"{random.choice(special_descriptors['elevation'])} elevation") prompt_parts.append(f"{random.choice(special_descriptors['difficulty'])} difficulty") content = ", ".join(prompt_parts) base_prompt = content full_prompt = f"{prefix} {content}" return full_prompt, base_prompt elif prompt_gen == "random": # Determine number of classes to include based on probability distribution rand = random.random() if rand < 0.10: num_classes = 1 elif rand < 0.40: # 0.10 + 0.30 num_classes = 2 elif rand < 0.70: # 0.10 + 0.30 + 0.30 num_classes = 3 elif rand < 0.85: num_classes = 4 elif rand < 0.95: num_classes = 5 else: num_classes = random.randint(6, len(classes)) # Randomly select classes selected_classes = random.sample(classes, min(num_classes, len(classes))) prompt_parts = [] for class_name in selected_classes: descriptor = random.choice(descriptors) prompt_parts.append(f"{descriptor} {class_name}") # Randomly include special descriptors (50% chance each) if random.random() < 0.5: prompt_parts.append(f"{random.choice(special_descriptors['level'])} level") if random.random() < 0.5: prompt_parts.append(f"{random.choice(special_descriptors['elevation'])} elevation") if random.random() < 0.5: prompt_parts.append(f"{random.choice(special_descriptors['difficulty'])} difficulty") content = ", ".join(prompt_parts) base_prompt = content full_prompt = f"{prefix} {content}" return full_prompt, base_prompt else: raise ValueError(f"Invalid prompt generation type: {prompt_gen}") def generate_prompt_addition_num(prompt_gen: str | int) -> tuple[str, str]: """ Generate prompt text where: - the MODEL sees numeric counts - the EVALUATION sees binned descriptors ("no", "a few", "some", "many") Returns: tuple: (full_prompt_numeric, base_prompt_binned) """ if not prompt_gen or prompt_gen == "": return "", "" PREFIXES = [ "Generate a level with", "Create a level that has", "Please generate a level with", "Build a level featuring", "Create a level featuring", "Give me a level that includes", "Make a level that includes", "Produce a level featuring", "Craft a level that includes", "I need a level that has", "I want to see a level that includes", "Design a level with", "I want a level with", "Make a level with", "Design a level around", "Generate levels with", "Construct a level featuring", "I want a level that has", "I would like a level that has", ] STATISTICS = { "special enemy": np.array([1.0, 2.0, 3.0]), "pipe": np.array([1.0, 2.0, 5.0]), "ground block": np.array([24.0, 87.0, 150.0]), "hard block": np.array([1.0, 11.0, 23.0]), "coin block": np.array([1.0, 2.0, 6.0]), "breakable block": np.array([1.0, 19.0, 38.0]), "coin": np.array([1.0, 5.0, 10.0]), "powerup": np.array([1.0, 2.0, 3.0]), "goomba": np.array([1.0, 2.0, 5.0]), "koopa": np.array([1.0, 3.0, 6.0]), } descriptors = ["no", "a few", "some", "many"] classes = [ "coin block", "pipes", "hard blocks", "breakable blocks", "koopas", "coins", "special enemies", "goombas", "powerups", "ground blocks", ] class_to_stats_key = { "coin block": "coin block", "pipes": "pipe", "hard blocks": "hard block", "breakable blocks": "breakable block", "koopas": "koopa", "coins": "coin", "special enemies": "special enemy", "goombas": "goomba", "powerups": "powerup", "ground blocks": "ground block", } special_descriptors = { "difficulty": ["easy", "medium", "hard"], "level": ["overworld", "underworld"], "elevation": ["high", "low"], } def descriptor_to_number(descriptor: str, stats: np.ndarray) -> int: if descriptor == "no": return 0 if descriptor == "a few": return int(stats[0]) if descriptor == "some": return int(stats[1]) if descriptor == "many": return int(stats[2]) raise ValueError(descriptor) prefix = random.choice(PREFIXES) # Determine class selection if isinstance(prompt_gen, int): num_classes = max(0, min(prompt_gen, len(classes))) if num_classes == 0: return "", "" selected_classes = random.sample(classes, num_classes) include_special = False elif prompt_gen == "full": selected_classes = classes include_special = True elif prompt_gen == "random": rand = random.random() if rand < 0.10: num_classes = 1 elif rand < 0.40: num_classes = 2 elif rand < 0.70: num_classes = 3 elif rand < 0.85: num_classes = 4 elif rand < 0.95: num_classes = 5 else: num_classes = random.randint(6, len(classes)) selected_classes = random.sample(classes, min(num_classes, len(classes))) include_special = True else: raise ValueError(f"Invalid prompt generation type: {prompt_gen}") numeric_parts = [] binned_parts = [] for class_name in selected_classes: descriptor = random.choice(descriptors) stats_key = class_to_stats_key[class_name] number = descriptor_to_number(descriptor, STATISTICS[stats_key]) numeric_parts.append(f"{number} {class_name}") binned_parts.append(f"{descriptor} {class_name}") if include_special: level_desc = random.choice(special_descriptors["level"]) elevation_desc = random.choice(special_descriptors["elevation"]) difficulty_desc = random.choice(special_descriptors["difficulty"]) numeric_parts.extend([ f"{level_desc} level", f"{elevation_desc} elevation", f"{difficulty_desc} difficulty", ]) binned_parts.extend([ f"{level_desc} level", f"{elevation_desc} elevation", f"{difficulty_desc} difficulty", ]) numeric_content = ", ".join(numeric_parts) binned_content = ", ".join(binned_parts) full_prompt_numeric = f"{prefix} {numeric_content}" full_prompt_binned = f"{prefix} {binned_content}" base_prompt_binned = binned_content return full_prompt_numeric, full_prompt_binned, base_prompt_binned def generate_prompt_addition_mariogpt(prompt_gen: str | int) -> tuple[str, str]: """ Generate prompt text based on prompt_gen mode. Args: prompt_gen: "full", "random", empty string, or an integer (number of classes) Returns: tuple: (full_prompt, base_prompt) where: - full_prompt: Complete prompt with prefix - base_prompt: Prompt content without prefix (empty string if prompt_gen is empty) """ if not prompt_gen or prompt_gen == "": return "", "" PREFIXES = [ "I want to see a level that includes", ] descriptors = ["no", "little", "some", "many"] classes = [ "pipes", "blocks", "enemies", ] special_descriptors = { "elevation": ["high", "low"] } # Choose random prefix prefix = random.choice(PREFIXES) # Handle numeric prompt_gen (exact number of classes) if isinstance(prompt_gen, int): num_classes = prompt_gen if num_classes <= 0: return "", "" if num_classes > len(classes): num_classes = len(classes) # Randomly select exactly num_classes selected_classes = random.sample(classes, num_classes) prompt_parts = [] for class_name in selected_classes: descriptor = random.choice(descriptors) prompt_parts.append(f"{descriptor} {class_name}") # Don't include special descriptors for numeric prompts (or you can add them if needed) content = ", ".join(prompt_parts) base_prompt = content full_prompt = f"{prefix} {content}" return full_prompt, base_prompt if prompt_gen == "full": # Use all classes with random descriptors prompt_parts = [] for class_name in classes: descriptor = random.choice(descriptors) prompt_parts.append(f"{descriptor} {class_name}") # Add special descriptors prompt_parts.append(f"{random.choice(special_descriptors['elevation'])} elevation") content = ", ".join(prompt_parts) base_prompt = content full_prompt = f"{prefix} {content}" return full_prompt, base_prompt elif prompt_gen == "random": # Determine number of classes to include based on probability distribution rand = random.random() if rand < 0.10: num_classes = 1 elif rand < 0.40: # 0.10 + 0.30 num_classes = 2 elif rand < 0.70: # 0.10 + 0.30 + 0.30 num_classes = 3 elif rand < 0.100: num_classes = 4 else: raise ValueError("For MarioGPT, maximum number of classes is 4.") # Randomly select classes selected_classes = random.sample(classes, min(num_classes, len(classes))) prompt_parts = [] for class_name in selected_classes: descriptor = random.choice(descriptors) prompt_parts.append(f"{descriptor} {class_name}") if random.random() < 0.5: prompt_parts.append(f"{random.choice(special_descriptors['elevation'])} elevation") content = ", ".join(prompt_parts) base_prompt = content full_prompt = f"{prefix} {content}" return full_prompt, base_prompt else: raise ValueError(f"Invalid prompt generation type: {prompt_gen}") def generate_prompt_addition_enhanced(prompt_gen: str, num_of_samples: int) -> list[str]: """ Generate prompt text from predefined dictionary based on prompt_gen mode. Args: prompt_gen: Must be "full", otherwise raises ValueError num_of_samples: Number of samples to generate (cycles through dict if > 20) Returns: list[str]: List of generated prompts (values from the dictionary) """ if prompt_gen != "full": raise ValueError(f"prompt_gen must be 'full', got: {prompt_gen}") prompts_dict = { "I want to see a level that includes a few coin block, a few pipes, a few hard blocks, no breakable blocks, some koopas, some coins, a few special enemies, many goombas, a few powerups, no ground blocks, underworld level, low elevation, hard difficulty": "I want to see a level that brings together a small number of coin blocks along with a fair amount of pipes and a small number of sturdy hard blocks, all while keeping the layout completely absent of breakable blocks. The level should feature a noticeable number of koopas and an equally noticeable number of coins, supported by a small number of special enemies and plenty of goombas. Include a small number of powerups but leave the ground blocks lacking, and place everything within an underworld setting at low elevation with a hard difficulty feel.", "I need a level that has no coin block, many pipes, many hard blocks, some breakable blocks, no koopas, many coins, many special enemies, some goombas, some powerups, no ground blocks, overworld level, high elevation, hard difficulty": "I need a level built without any coin blocks but featuring numerous pipes and an abundant amount of hard blocks. Add a noticeable number of breakable blocks but keep koopas completely lacking. Fill the space with a large number of coins and just as many special enemies, along with a balanced number of goombas and a balanced number of powerups. The ground blocks should be entirely absent, and the whole design should take place in an overworld area at high elevation with a demanding hard difficulty.", "Build a level featuring some coin block, no pipes, a few hard blocks, some breakable blocks, many koopas, some coins, some special enemies, many goombas, no powerups, a few ground blocks, underworld level, high elevation, medium difficulty": "Build a level that uses a modest amount of coin blocks while leaving pipes completely absent. Include a small number of hard blocks along with a noticeable number of breakable blocks. Fill it with plenty of koopas, a modest amount of coins, and a modest amount of special enemies, supported by plenty of goombas. Keep powerups lacking but include a small number of ground blocks. The entire design should exist in an underworld environment at high elevation with medium difficulty.", "Construct a level featuring a few coin block, no pipes, some hard blocks, some breakable blocks, many koopas, no coins, a few special enemies, some goombas, some powerups, no ground blocks, overworld level, high elevation, easy difficulty": "Construct a level that uses a small number of coin blocks while remaining completely without pipes. Bring in a modest amount of hard blocks and a modest amount of breakable blocks, and populate it with plenty of koopas but absolutely no coins. Add a small number of special enemies, a balanced number of goombas, and a balanced number of powerups, but keep ground blocks entirely absent. Place the whole scene in an overworld area at high elevation with an easy difficulty.", "Design a level around a few coin block, many pipes, no hard blocks, no breakable blocks, many koopas, many coins, some special enemies, no goombas, a few powerups, no ground blocks, underworld level, high elevation, hard difficulty": "Design a level that revolves around a small number of coin blocks while incorporating numerous pipes and leaving both hard blocks and breakable blocks completely absent. Stock it with plenty of koopas and abundant coins, backed by a modest amount of special enemies but none of the goombas. Add a small number of powerups yet keep the ground blocks lacking. Set everything in an underworld environment at high elevation with a hard difficulty.", "Create a level that has no coin block, a few pipes, no hard blocks, no breakable blocks, no koopas, many coins, a few special enemies, a few goombas, many powerups, a few ground blocks, overworld level, low elevation, hard difficulty": "Create a level built without coin blocks but with a small number of pipes, entirely lacking both hard blocks and breakable blocks. There should be no koopas at all, but a large number of coins scattered throughout, along with a small number of special enemies and a small number of goombas. Add abundant powerups and a small number of ground blocks, and place the whole area in an overworld region at low elevation with a hard difficulty.", "Give me a level that includes some coin block, a few pipes, some hard blocks, no breakable blocks, a few koopas, some coins, a few special enemies, no goombas, a few powerups, some ground blocks, overworld level, high elevation, medium difficulty": "Give me a level that incorporates a modest amount of coin blocks alongside a small number of pipes and a modest amount of hard blocks, while remaining entirely absent of breakable blocks. Add a small number of koopas, a modest amount of coins, and a small number of special enemies, all with no goombas present. Include a small number of powerups along with a modest amount of ground blocks. The setting should be an overworld region at high elevation with medium difficulty.", "Craft a level that includes some coin block, no pipes, a few hard blocks, many breakable blocks, no koopas, a few coins, some special enemies, a few goombas, no powerups, many ground blocks, overworld level, high elevation, medium difficulty": "Craft a level that uses a fair amount of coin blocks while omitting pipes completely. Add a small number of hard blocks along with plenty of breakable blocks, and keep the layout entirely without koopas. Include a small number of coins and a modest amount of special enemies, supported by a small number of goombas, but leave powerups lacking. Use numerous ground blocks throughout and place everything in an overworld setting at high elevation with medium difficulty.", "I want a level with some coin block, some pipes, many hard blocks, a few breakable blocks, many koopas, no coins, some special enemies, no goombas, some powerups, some ground blocks, underworld level, low elevation, hard difficulty": "I want a level that contains a fair amount of coin blocks and a noticeable number of pipes, paired with a large number of hard blocks and a small number of breakable blocks. Plenty of koopas should be present, but the level must have no coins whatsoever. Add a modest amount of special enemies with no goombas, plus a modest amount of powerups and a balanced number of ground blocks. The whole thing should take place in an underworld setting at low elevation with hard difficulty.", "Create a level that has some coin block, no pipes, a few hard blocks, many breakable blocks, many koopas, a few coins, some special enemies, no goombas, no powerups, a few ground blocks, overworld level, low elevation, hard difficulty": "Create a level featuring a modest amount of coin blocks but no pipes at all, supported by a small number of hard blocks and plenty of breakable blocks. Fill the area with plenty of koopas, a small number of coins, and a modest amount of special enemies, but maintain a complete lack of goombas and powerups. Add a small number of ground blocks, and situate the whole layout in an overworld region at low elevation with hard difficulty.", "Design a level with many coin block, some pipes, no hard blocks, many breakable blocks, a few koopas, a few coins, many special enemies, many goombas, no powerups, some ground blocks, overworld level, low elevation, easy difficulty": "Design a level that offers abundant coin blocks together with a noticeable number of pipes while intentionally leaving hard blocks absent. Fill it with plenty of breakable blocks as well as a small number of koopas and a small number of coins. Include many special enemies and abundant goombas, but keep powerups entirely lacking. Add a modest amount of ground blocks and place everything in an overworld environment at low elevation with an easy difficulty.", "Produce a level featuring many coin block, no pipes, many hard blocks, a few breakable blocks, a few koopas, many coins, no special enemies, no goombas, some powerups, no ground blocks, overworld level, high elevation, easy difficulty": "Produce a level that brings in plenty of coin blocks while avoiding pipes completely, supported by a large number of hard blocks and a small number of breakable blocks. Add a small number of koopas along with abundant coins, but keep special enemies and goombas entirely absent. Include a modest amount of powerups while leaving ground blocks lacking, and situate the whole area in an overworld region at high elevation with easy difficulty.", "Construct a level featuring many coin block, a few pipes, a few hard blocks, many breakable blocks, some koopas, many coins, no special enemies, no goombas, no powerups, a few ground blocks, underworld level, high elevation, medium difficulty": "Construct a level filled with numerous coin blocks, a small number of pipes, and a small number of hard blocks, paired with plenty of breakable blocks. Include a noticeable number of koopas and abundant coins but keep both special enemies and goombas completely absent. Leave powerups lacking but add a small number of ground blocks, and build the entire layout in an underworld environment at high elevation with medium difficulty.", "Design a level around many coin block, no pipes, a few hard blocks, some breakable blocks, many koopas, no coins, many special enemies, no goombas, no powerups, many ground blocks, underworld level, high elevation, easy difficulty": "Design a level centered around numerous coin blocks while keeping pipes absent. Add a small number of hard blocks and a modest amount of breakable blocks, then fill it with plenty of koopas but absolutely no coins. Include many special enemies while keeping goombas and powerups absent, and use numerous ground blocks throughout. The whole scene should take place in an underworld region at high elevation with easy difficulty.", "I want a level that has no coin block, no pipes, a few hard blocks, many breakable blocks, a few koopas, no coins, many special enemies, some goombas, many powerups, no ground blocks, underworld level, high elevation, hard difficulty": "I want a level entirely without coin blocks or pipes, but with a small number of hard blocks and plenty of breakable blocks. Add a small number of koopas while keeping coins completely absent. Include many special enemies as well as a balanced number of goombas, and support everything with abundant powerups even though ground blocks remain lacking. Place the design in an underworld environment at high elevation with hard difficulty.", "Design a level around many coin block, no pipes, no hard blocks, some breakable blocks, many koopas, many coins, no special enemies, many goombas, many powerups, some ground blocks, overworld level, high elevation, hard difficulty": "Design a level built around numerous coin blocks without any pipes or hard blocks. Add a noticeable number of breakable blocks and plenty of koopas, along with a large number of coins. Keep special enemies completely absent but include abundant goombas and abundant powerups, supported by a modest amount of ground blocks. Set this area in an overworld environment at high elevation with hard difficulty.", "I want a level that has no coin block, a few pipes, no hard blocks, no breakable blocks, many koopas, many coins, some special enemies, some goombas, many powerups, no ground blocks, underworld level, low elevation, hard difficulty": "I want a level without coin blocks but with a small number of pipes, and entirely lacking both hard blocks and breakable blocks. Populate it with plenty of koopas and a large number of coins, backed by a modest amount of special enemies and a balanced number of goombas. Add abundant powerups while leaving out ground blocks completely. The full design should be set in an underworld environment at low elevation with hard difficulty.", "I want a level with no coin block, no pipes, no hard blocks, many breakable blocks, many koopas, a few coins, a few special enemies, some goombas, a few powerups, many ground blocks, underworld level, high elevation, easy difficulty": "I want a level that contains no coin blocks, no pipes, and no hard blocks, but features plenty of breakable blocks and plenty of koopas. Add a small number of coins and a small number of special enemies, supported by a balanced number of goombas and a small number of powerups. Fill the space with numerous ground blocks and situate the entire design in an underworld setting at high elevation with easy difficulty.", "Build a level featuring no coin block, no pipes, many hard blocks, no breakable blocks, some koopas, a few coins, many special enemies, some goombas, no powerups, no ground blocks, overworld level, high elevation, easy difficulty": "Build a level that has no coin blocks or pipes but a large number of hard blocks while keeping breakable blocks absent. Add a noticeable number of koopas and a small number of coins, along with many special enemies and a balanced number of goombas. Keep powerups and ground blocks entirely lacking, and place everything in an overworld region at high elevation with easy difficulty.", "Design a level with some coin block, a few pipes, a few hard blocks, a few breakable blocks, many koopas, no coins, a few special enemies, a few goombas, some powerups, no ground blocks, underworld level, low elevation, hard difficulty": "Design a level that uses a modest amount of coin blocks together with a small number of pipes and a small number of hard blocks, plus a small number of breakable blocks. Fill it with plenty of koopas but no coins at all, and add a small number of special enemies along with a small number of goombas. Include a modest amount of powerups but keep ground blocks lacking. Set the scene in an underworld area at low elevation with hard difficulty." } items = list(prompts_dict.items()) max_prompts = 20 idx = num_of_samples % max_prompts raw_prompt, full_prompt = items[idx] return full_prompt, raw_prompt ################################################################### def extract_level_representation(llm_output, model_type="llama-3", orientation="horizontal", separator="\n", empty_space='-'): if isinstance(llm_output, list): llm_output = llm_output[0] level_content = "" if model_type in ["llama-3", "llama3"]: parts = llm_output.split("<|start_header_id|>assistant<|end_header_id|>") if len(parts) > 1: assistant_section = parts[-1] if "<|eot_id|>" in assistant_section: level_content = assistant_section.split("<|eot_id|>")[0].strip() else: level_content = assistant_section.strip() else: level_content = llm_output.strip() elif model_type in ["gemma-3", "gemma3", "gemma"]: parts = llm_output.split("model") if len(parts) > 1: model_section = parts[-1] if "" in model_section: level_content = model_section.split("")[0].strip() else: level_content = model_section.strip() else: level_content = llm_output.strip() elif model_type in ["qwen-2.5", "qwen2.5"]: parts = llm_output.split("<|im_start|>assistant") if len(parts) > 1: assistant_block = parts[-1] if "<|im_end|>" in assistant_block: level_content = assistant_block.split("<|im_end|>")[0].strip() else: level_content = assistant_block.strip() else: level_content = llm_output.strip() elif model_type in ["qwen-3", "qwen3"]: parts = llm_output.split("<|im_start|>assistant") if len(parts) > 1: assistant_block = parts[-1] if "<|im_end|>" in assistant_block: content = assistant_block.split("<|im_end|>")[0].strip() if "" in content and "" in content: think_parts = content.split("") if len(think_parts) > 1: level_content = think_parts[-1].strip() else: level_content = content else: level_content = content else: level_content = assistant_block.strip() else: level_content = llm_output.strip() else: raise ValueError(f"Unsupported model type: {model_type}") # print("New level content:") # print(level_content) if "|" in level_content and "\n" not in level_content: separator = "|" elif "\n" in level_content and "|" not in level_content: separator = "\n" if orientation == "vertical": level_content = VerticalLevel.reconstruct_level_from_vertical_bar(level_content, separator) return level_content def fix_level_format(level_str, orientation="horizontal", separator="\n", empty_space='-'): if orientation == "vertical": level_str = VerticalLevel.reconstruct_level_from_vertical_bar(level_str, separator) lines = level_str.split('\n') line_lengths = [len(line) for line in lines] changed = True while changed: changed = False max_length = max(line_lengths) longest_lines_indices = [i for i, length in enumerate(line_lengths) if length == max_length] lines_trimmed = False for idx in longest_lines_indices: line = lines[idx] if line and line[-1] == empty_space: lines[idx] = line[:-1] line_lengths[idx] -= 1 lines_trimmed = True changed = True if not lines_trimmed: break max_length = max(line_lengths) for i in range(len(lines)): if line_lengths[i] < max_length: padding_char = empty_space lines[i] = lines[i] + (padding_char * (max_length - line_lengths[i])) return '\n'.join(lines) ############################################################################################## def fix_level_format_extra(level_str, orientation="horizontal", separator="\n", empty_space='-', line_quantity=None, column_quantity=None, enforce_shape=None, add_ground=None, use_original_logic_on_column=False): if "|" in level_str and "\n" not in level_str: separator = "|" elif "\n" in level_str and "|" not in level_str: separator = "\n" if orientation == "vertical": level_str = VerticalLevel.reconstruct_level_from_vertical_bar(level_str, separator) lines = level_str.split(separator) # Handle line quantity enforcement if enforce_shape in ["line", "both"] and line_quantity is not None: if len(lines) > line_quantity: # Remove from top (beginning of list) lines = lines[-line_quantity:] elif len(lines) < line_quantity: # Add empty lines at top empty_line = empty_space * (max(len(line) for line in lines) if lines else column_quantity or 0) lines = [empty_line] * (line_quantity - len(lines)) + lines # Handle column quantity enforcement column_adjusted = False if enforce_shape in ["column", "both"] and column_quantity is not None: column_adjusted = True for i in range(len(lines)): if len(lines[i]) > column_quantity: lines[i] = lines[i][:column_quantity] elif len(lines[i]) < column_quantity: if i == len(lines) - 1 and add_ground is not None: lines[i] = lines[i] + (add_ground * (column_quantity - len(lines[i]))) else: lines[i] = lines[i] + (empty_space * (column_quantity - len(lines[i]))) if (enforce_shape is None or use_original_logic_on_column) and not column_adjusted: line_lengths = [len(line) for line in lines] changed = True while changed: changed = False max_length = max(line_lengths) longest_lines_indices = [i for i, length in enumerate(line_lengths) if length == max_length] lines_trimmed = False for idx in longest_lines_indices: line = lines[idx] if line and line[-1] == empty_space: lines[idx] = line[:-1] line_lengths[idx] -= 1 lines_trimmed = True changed = True if not lines_trimmed: break max_length = max(line_lengths) for i in range(len(lines)): if line_lengths[i] < max_length: padding_char = add_ground if i == len(lines) - 1 and add_ground is not None else empty_space lines[i] = lines[i] + (padding_char * (max_length - line_lengths[i])) return separator.join(lines) ############################################################################################## class VerticalLevel: @staticmethod def reconstruct_level_from_vertical_bar(vertical_bar_str, separator="\n"): if not vertical_bar_str: return None vertical_columns = vertical_bar_str.split(separator) num_cols = len(vertical_columns) if num_cols == 0 or not vertical_columns[0]: return None num_rows = len(vertical_columns[0]) if num_rows == 0: return None reconstructed_rows = [] for i in range(num_rows): current_row_chars = [] for j in range(num_cols): vertical_char_index = num_rows - 1 - i if j < len(vertical_columns) and vertical_char_index < len(vertical_columns[j]): char = vertical_columns[j][vertical_char_index] current_row_chars.append(char) reconstructed_rows.append("".join(current_row_chars)) return "\n".join(reconstructed_rows) def determine_game_and_orientation(path: str) -> tuple[str, str]: path = path.lower() game_type = None # if "mario" in path: # game_type = "mario" # elif "icarus" in path or "kid" in path: # game_type = "kidicarus" # elif "runner" in path or "lode" in path: # game_type = "loderunner" # elif "rainbow" in path or "island" in path: # game_type = "rainbowisland" # orientation = "horizontal" # if "vertical" in path: # orientation = "vertical" orientation = "vertical" game_type = "mario" return game_type, orientation