Created
June 15, 2024 08:24
-
-
Save SoMaCoSF/6840c085c74237b73ffff2720620337d to your computer and use it in GitHub Desktop.
ManorLords Coat Of Arms Randomizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import random | |
import shutil | |
from PIL import Image, ImageDraw, ImageFont | |
from datetime import datetime | |
import argparse | |
import sys | |
import pyimgur | |
VERSION = "1.1" | |
DESCRIPTION = """ | |
Coat Selector Script v1.1 | |
This script selects a random .png file from the /banners/ folder, resizes it to a 2048x2048 square image, | |
saves it as player_coat.png in the /coa/ directory, overwrites the parent directory's player_coat.png, | |
and updates the log. The final image is uploaded to Imgur, and an ASCII representation is generated, | |
displayed, and saved to the ascii_images folder. | |
""" | |
def resize_to_square(image_path, output_path, size=2048): | |
try: | |
with Image.open(image_path) as img: | |
img.thumbnail((size, size)) | |
new_img = Image.new('RGBA', (size, size), (255, 255, 255, 0)) | |
position = ((size - img.width) // 2, (size - img.height) // 2) | |
new_img.paste(img, position) | |
new_img.save(output_path) | |
except Exception as e: | |
print(f"Error resizing the image: {e}") | |
raise | |
def rename_existing_file(file_path): | |
base, ext = os.path.splitext(file_path) | |
counter = 1 | |
new_file_path = f"{base}.{counter:03d}{ext}" | |
while os.path.exists(new_file_path): | |
counter += 1 | |
new_file_path = f"{base}.{counter:03d}{ext}" | |
os.rename(file_path, new_file_path) | |
return new_file_path | |
def print_image_to_console(image_path): | |
try: | |
with Image.open(image_path) as img: | |
img.thumbnail((40, 40)) # Reduce size for better ASCII representation | |
img = img.convert('L') # Convert to grayscale for ASCII representation | |
ascii_chars = '@%#*+=-:. ' # ASCII characters from dense to sparse | |
ascii_image = '' | |
pixels = img.getdata() | |
width, height = img.size | |
for pixel in range(width * height): | |
ascii_image += ascii_chars[pixels[pixel] // 32] # 32 for 8-bit range to 4-bit range | |
if pixel % width == width - 1: | |
ascii_image += '\n' | |
return ascii_image | |
except Exception as e: | |
print(f"Error printing the image to console: {e}") | |
raise | |
def save_ascii_image(ascii_image, description, ascii_dir): | |
try: | |
desc = description[:40].replace(' ', '_') | |
output_path = os.path.join(ascii_dir, f"{desc}.png") | |
img_height, img_width = len(ascii_image.split('\n')), len(ascii_image.split('\n')[0]) | |
scale = 10 # Scale up for better readability | |
img = Image.new('RGB', (img_width * scale, img_height * scale), color=(255, 255, 255)) | |
d = ImageDraw.Draw(img) | |
font = ImageFont.load_default() | |
for y, line in enumerate(ascii_image.split('\n')): | |
for x, char in enumerate(line): | |
d.text((x * scale, y * scale), char, font=font, fill=(0, 0, 0)) | |
img.save(output_path) | |
print(f"ASCII image saved as {output_path}") | |
return output_path | |
except Exception as e: | |
print(f"Error saving the ASCII image: {e}") | |
raise | |
def upload_to_imgur(image_path, client_id): | |
try: | |
im = pyimgur.Imgur(client_id) | |
uploaded_image = im.upload_image(image_path, title="Coat of Arms") | |
print(f"Uploaded image URL: {uploaded_image.link}") | |
return uploaded_image.link | |
except Exception as e: | |
print(f"Error uploading the image to Imgur: {e}") | |
raise | |
def main(): | |
print(DESCRIPTION) | |
parser = argparse.ArgumentParser(description="Coat Selector Script") | |
parser.add_argument('--info', action='store_true', help="Display this help message") | |
args = parser.parse_args() | |
if args.info: | |
parser.print_help() | |
sys.exit(0) | |
coa_folder = os.getcwd() # Assuming script is being run from \SaveGames\coa\ | |
banners_folder = os.path.join(coa_folder, 'banners') | |
output_file = 'player_coat.png' | |
log_file = 'coats.log' | |
error_log_file = 'error.log' | |
ascii_dir = 'ascii_images' | |
original_dir = 'original_images' | |
final_dir = 'final_images' | |
imgur_client_id = 'YOUR_IMGUR_CLIENT_ID' # Replace with your Imgur Client ID | |
print("=== Coat Selector ===") | |
# Check if the script is being run from the correct directory | |
if not coa_folder.endswith(os.path.join('SaveGames', 'coa')): | |
print("Please run this script from the \\SaveGames\\coa directory.") | |
return | |
# Check if the banners folder exists | |
if not os.path.exists(banners_folder): | |
print(f"The /banners/ folder does not exist in the {coa_folder} directory.") | |
return | |
# Create directories if they don't exist | |
os.makedirs(ascii_dir, exist_ok=True) | |
os.makedirs(original_dir, exist_ok=True) | |
os.makedirs(final_dir, exist_ok=True) | |
# Check if the output file already exists | |
if os.path.exists(output_file): | |
renamed_file = rename_existing_file(output_file) | |
print(f"Existing file renamed to {renamed_file}") | |
# Read log file and get previously selected files | |
selected_files = set() | |
if os.path.exists(log_file): | |
with open(log_file, 'r') as log: | |
for line in log: | |
parts = line.split(" - ") | |
if len(parts) >= 2: | |
selected_files.add(parts[1].split(" ")[0].strip()) | |
else: | |
print(f"Skipping line in log file: {line.strip()}") | |
# Select a random .png file from the /banners/ folder that has not been selected before | |
png_files = [file for file in os.listdir(banners_folder) if file.lower().endswith('.png')] | |
png_files_to_select = list(set(png_files) - selected_files) | |
if not png_files_to_select: | |
print("No new .png files to select.") | |
return | |
random_file = random.choice(png_files_to_select) | |
random_file_path = os.path.join(banners_folder, random_file) | |
# Copy original file to the original directory | |
original_file_copy = os.path.join(original_dir, random_file) | |
shutil.copy2(random_file_path, original_file_copy) | |
# Copy and resize the image | |
try: | |
resize_to_square(random_file_path, output_file, size=2048) | |
except Exception as e: | |
print(f"Error processing the image: {e}") | |
log_error(error_log_file, f"{datetime.now()} - Error processing the image: {e}") | |
return | |
# Print the image to console | |
try: | |
ascii_image = print_image_to_console(output_file) | |
print(ascii_image) | |
except Exception as e: | |
print(f"Error displaying the image in the console: {e}") | |
log_error(error_log_file, f"{datetime.now()} - Error displaying the image in the console: {e}") | |
return | |
# Log the operation | |
date_stamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
coat_desc = input("Enter a Coat Description (optional, max 40 chars): ")[:40] | |
with open(log_file, 'a') as log: | |
log.write(f"{date_stamp} - {random_file} copied and resized to {output_file}. Desc: {coat_desc}\n") | |
# Ensure the log file only keeps the last 13 iterations | |
with open(log_file, 'r') as log: | |
lines = log.readlines() | |
if len(lines) > 13: | |
with open(log_file, 'w') as log: | |
log.writelines(lines[-13:]) | |
# Save player_coat.png with description in final_images directory and overwrite in parent directory | |
try: | |
desc = coat_desc[:40].replace(' ', '_') | |
final_image_path = os.path.join(final_dir, f"{desc}.png") | |
shutil.copy2(output_file, os.path.join(os.path.dirname(coa_folder), output_file)) # Overwrite in parent directory | |
shutil.copy2(output_file, final_image_path) | |
print(f"Final image saved as {final_image_path}") | |
except Exception as e: | |
print(f"Error saving the final image: {e}") | |
log_error(error_log_file, f"{datetime.now()} - Error saving the final image: {e}") | |
return | |
# Save ASCII image to PNG | |
try: | |
ascii_image_path = save_ascii_image(ascii_image, coat_desc, ascii_dir) | |
except Exception as e: | |
print(f"Error saving the ASCII image: {e}") | |
log_error(error_log_file, f"{datetime.now()} - Error saving the ASCII image: {e}") | |
return | |
# Upload final image to Imgur and get the link | |
try: | |
imgur_link = upload_to_imgur(final_image_path, imgur_client_id) | |
except Exception as e: | |
print(f"Error uploading the image to Imgur: {e}") | |
log_error(error_log_file, f"{datetime.now()} - Error uploading the image to Imgur: {e}") | |
return | |
# Log the Imgur link | |
with open(log_file, 'a') as log: | |
log.write(f"Imgur link: {imgur_link}\n") | |
# Display actions | |
print("\n=== Actions Completed ===") | |
print(f"1. Renamed existing player_coat.png (if any) to {renamed_file if os.path.exists(output_file) else 'N/A'}") | |
print(f"2. Selected random file: {random_file}") | |
print(f"3. Resized and saved to {output_file}") | |
print(f"4. Copied original to {original_file_copy}") | |
print(f"5. Final image saved as {final_image_path}") | |
print(f"6. Final image copied to parent directory as {output_file}") | |
print(f"7. ASCII image saved as {ascii_image_path}") | |
print(f"8. Uploaded final image to Imgur: {imgur_link}") | |
print("\nThank you for visiting the Tavern Kiosk!") | |
# Ask for confirmation to exit | |
while True: | |
exit_confirmation = input("Do you want to exit? (yes/no): ").strip().lower() | |
if exit_confirmation in ('yes', 'no'): | |
break | |
if exit_confirmation == 'yes': | |
print("Thank you for visiting the Tavern Kiosk!") | |
def log_error(log_file, error_message): | |
with open(log_file, 'a') as error_log: | |
error_log.write(f"{error_message}\n") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment