From 02f0960de1602a9984716151e5014d50288614f1 Mon Sep 17 00:00:00 2001 From: Dabomstew Date: Tue, 26 Apr 2016 19:41:10 +1200 Subject: [PATCH] Refactor custom names system completely. This combines everything into one binary file (customnames.rncn for now). The GUI will now ask if you want to convert your old text files into a new file, if they exist. Still TODO: * Create a GUI editor for custom names, since they are no longer in plaintext files * Refactor ROM-side detection of doubles classes/trainers to no longer use the dumb string tests that only (barely) work for English language. Even constant value arrays of which classes are doubles classes will be better. This also fixes a minor bug with the new moveset randomization code. --- .gitignore | 7 +- .../dabomstew/pkrandom/CustomNamesSet.java | 189 ++++++++++++++++ src/com/dabomstew/pkrandom/FileFunctions.java | 18 +- src/com/dabomstew/pkrandom/Randomizer.java | 14 +- src/com/dabomstew/pkrandom/Settings.java | 44 +--- .../dabomstew/pkrandom/SettingsUpdater.java | 12 +- src/com/dabomstew/pkrandom/SysConstants.java | 6 + src/com/dabomstew/pkrandom/Utils.java | 33 +-- .../pkrandom/config/customnames.rncn | Bin 0 -> 1709 bytes .../dabomstew/pkrandom/config/nicknames.txt | 20 -- .../pkrandom/config/trainerclasses.txt | 83 ------- .../pkrandom/config/trainernames.txt | 84 -------- .../InvalidSupplementFilesException.java | 7 +- .../dabomstew/pkrandom/gui/Bundle.properties | 6 +- .../pkrandom/gui/PresetLoadDialog.java | 32 +-- .../pkrandom/gui/PresetMakeDialog.java | 12 +- .../dabomstew/pkrandom/gui/RandomizerGUI.java | 124 +++++------ .../romhandlers/AbstractRomHandler.java | 203 +++++++----------- .../pkrandom/romhandlers/RomHandler.java | 11 +- 19 files changed, 397 insertions(+), 508 deletions(-) create mode 100644 src/com/dabomstew/pkrandom/CustomNamesSet.java create mode 100644 src/com/dabomstew/pkrandom/config/customnames.rncn delete mode 100755 src/com/dabomstew/pkrandom/config/nicknames.txt delete mode 100755 src/com/dabomstew/pkrandom/config/trainerclasses.txt delete mode 100755 src/com/dabomstew/pkrandom/config/trainernames.txt diff --git a/.gitignore b/.gitignore index d075c881b..4c26a482c 100755 --- a/.gitignore +++ b/.gitignore @@ -26,10 +26,11 @@ bin nbproject build.xml manifest.mf -nicknames.txt -trainerclasses.txt -trainernames.txt +/nicknames.txt +/trainerclasses.txt +/trainernames.txt /build/ *.dsm *.dsv build_eclipse.xml +/customnames.rncn diff --git a/src/com/dabomstew/pkrandom/CustomNamesSet.java b/src/com/dabomstew/pkrandom/CustomNamesSet.java new file mode 100644 index 000000000..dbde6b523 --- /dev/null +++ b/src/com/dabomstew/pkrandom/CustomNamesSet.java @@ -0,0 +1,189 @@ +package com.dabomstew.pkrandom; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Scanner; + +public class CustomNamesSet { + + private List trainerNames; + private List trainerClasses; + private List doublesTrainerNames; + private List doublesTrainerClasses; + private List pokemonNicknames; + + private static final int CUSTOM_NAMES_VERSION = 1; + + // Standard constructor: read binary data from an input stream. + public CustomNamesSet(InputStream data) throws IOException { + + if (data.read() != CUSTOM_NAMES_VERSION) { + throw new IOException("Invalid custom names file provided."); + } + + trainerNames = readNamesBlock(data); + trainerClasses = readNamesBlock(data); + doublesTrainerNames = readNamesBlock(data); + doublesTrainerClasses = readNamesBlock(data); + pokemonNicknames = readNamesBlock(data); + } + + // Private constructor: blank all lists. + // Used for importing old names. + private CustomNamesSet() { + trainerNames = new ArrayList(); + trainerClasses = new ArrayList(); + doublesTrainerNames = new ArrayList(); + doublesTrainerClasses = new ArrayList(); + pokemonNicknames = new ArrayList(); + } + + private List readNamesBlock(InputStream in) throws IOException { + // Read the size of the block to come. + byte[] szData = FileFunctions.readFullyIntoBuffer(in, 4); + int size = FileFunctions.readFullInt(szData, 0); + if (in.available() < size) { + throw new IOException("Invalid size specified."); + } + + // Read the block and translate it into a list of names. + byte[] namesData = FileFunctions.readFullyIntoBuffer(in, size); + List names = new ArrayList(); + Scanner sc = new Scanner(new ByteArrayInputStream(namesData), "UTF-8"); + while (sc.hasNextLine()) { + String name = sc.nextLine().trim(); + if (!name.isEmpty()) { + names.add(name); + } + } + sc.close(); + + return names; + } + + public byte[] getBytes() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + baos.write(CUSTOM_NAMES_VERSION); + + writeNamesBlock(baos, trainerNames); + writeNamesBlock(baos, trainerClasses); + writeNamesBlock(baos, doublesTrainerNames); + writeNamesBlock(baos, doublesTrainerClasses); + writeNamesBlock(baos, pokemonNicknames); + + return baos.toByteArray(); + } + + private void writeNamesBlock(OutputStream out, List names) throws IOException { + String newln = System.getProperty("line.separator"); + StringBuffer outNames = new StringBuffer(); + boolean first = true; + for (String name : names) { + if (!first) { + outNames.append(newln); + } + first = false; + outNames.append(name); + } + byte[] namesData = outNames.toString().getBytes("UTF-8"); + byte[] szData = new byte[4]; + FileFunctions.writeFullInt(szData, 0, namesData.length); + out.write(szData); + out.write(namesData); + } + + public List getTrainerNames() { + return Collections.unmodifiableList(trainerNames); + } + + public List getTrainerClasses() { + return Collections.unmodifiableList(trainerClasses); + } + + public List getDoublesTrainerNames() { + return Collections.unmodifiableList(doublesTrainerNames); + } + + public List getDoublesTrainerClasses() { + return Collections.unmodifiableList(doublesTrainerClasses); + } + + public List getPokemonNicknames() { + return Collections.unmodifiableList(pokemonNicknames); + } + + public static CustomNamesSet importOldNames() throws FileNotFoundException { + CustomNamesSet cns = new CustomNamesSet(); + + // Trainer Names + if (FileFunctions.configExists(SysConstants.tnamesFile)) { + Scanner sc = new Scanner(FileFunctions.openConfig(SysConstants.tnamesFile), "UTF-8"); + while (sc.hasNextLine()) { + String trainername = sc.nextLine().trim(); + if (trainername.isEmpty()) { + continue; + } + if (trainername.startsWith("\uFEFF")) { + trainername = trainername.substring(1); + } + if (trainername.contains("&")) { + cns.doublesTrainerNames.add(trainername); + } else { + cns.trainerNames.add(trainername); + } + } + sc.close(); + } + + // Trainer Classes + if (FileFunctions.configExists(SysConstants.tclassesFile)) { + Scanner sc = new Scanner(FileFunctions.openConfig(SysConstants.tclassesFile), "UTF-8"); + while (sc.hasNextLine()) { + String trainerClassName = sc.nextLine().trim(); + if (trainerClassName.isEmpty()) { + continue; + } + if (trainerClassName.startsWith("\uFEFF")) { + trainerClassName = trainerClassName.substring(1); + } + String checkName = trainerClassName.toLowerCase(); + int idx = (checkName.endsWith("couple") || checkName.contains(" and ") || checkName.endsWith("kin") + || checkName.endsWith("team") || checkName.contains("&") || (checkName.endsWith("s") && !checkName + .endsWith("ss"))) ? 1 : 0; + if (idx == 1) { + cns.doublesTrainerClasses.add(trainerClassName); + } else { + cns.trainerClasses.add(trainerClassName); + } + } + sc.close(); + } + + // Nicknames + if (FileFunctions.configExists(SysConstants.nnamesFile)) { + Scanner sc = new Scanner(FileFunctions.openConfig(SysConstants.nnamesFile), "UTF-8"); + while (sc.hasNextLine()) { + String nickname = sc.nextLine().trim(); + if (nickname.isEmpty()) { + continue; + } + if (nickname.startsWith("\uFEFF")) { + nickname = nickname.substring(1); + } + cns.pokemonNicknames.add(nickname); + } + sc.close(); + } + + return cns; + } + +} diff --git a/src/com/dabomstew/pkrandom/FileFunctions.java b/src/com/dabomstew/pkrandom/FileFunctions.java index 14bf674d9..402070ec9 100755 --- a/src/com/dabomstew/pkrandom/FileFunctions.java +++ b/src/com/dabomstew/pkrandom/FileFunctions.java @@ -28,6 +28,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -66,8 +67,8 @@ public static File fixFilename(File original, String defaultExtension, List overrideFiles = Arrays.asList(new String[] { "trainerclasses.txt", "trainernames.txt", - "nicknames.txt" }); + private static List overrideFiles = Arrays.asList(new String[] { SysConstants.customNamesFile, + SysConstants.tclassesFile, SysConstants.tnamesFile, SysConstants.nnamesFile }); public static boolean configExists(String filename) { if (overrideFiles.contains(filename)) { @@ -97,6 +98,13 @@ public static InputStream openConfig(String filename) throws FileNotFoundExcepti return FileFunctions.class.getResourceAsStream("/com/dabomstew/pkrandom/config/" + filename); } + public static CustomNamesSet getCustomNames() throws IOException { + InputStream is = openConfig(SysConstants.customNamesFile); + CustomNamesSet cns = new CustomNamesSet(is); + is.close(); + return cns; + } + public static int readFullInt(byte[] data, int offset) { ByteBuffer buf = ByteBuffer.allocate(4).put(data, offset, 4); buf.rewind(); @@ -140,6 +148,12 @@ public static void readFully(InputStream in, byte[] buf, int offset, int length) } } + public static void writeBytesToFile(String filename, byte[] data) throws IOException { + FileOutputStream fos = new FileOutputStream(filename); + fos.write(data); + fos.close(); + } + public static byte[] getConfigAsBytes(String filename) throws IOException { InputStream in = openConfig(filename); byte[] buf = readFullyIntoBuffer(in, in.available()); diff --git a/src/com/dabomstew/pkrandom/Randomizer.java b/src/com/dabomstew/pkrandom/Randomizer.java index bec8bd487..6775c4739 100644 --- a/src/com/dabomstew/pkrandom/Randomizer.java +++ b/src/com/dabomstew/pkrandom/Randomizer.java @@ -311,11 +311,11 @@ public int randomize(final String filename, final PrintStream log, long seed) { if (romHandler.canChangeTrainerText()) { if (settings.isRandomizeTrainerClassNames()) { - romHandler.randomizeTrainerClassNames(settings.getTrainerClasses()); + romHandler.randomizeTrainerClassNames(settings.getCustomNames()); } if (settings.isRandomizeTrainerNames()) { - romHandler.randomizeTrainerNames(settings.getTrainerNames()); + romHandler.randomizeTrainerNames(settings.getCustomNames()); } } @@ -480,15 +480,13 @@ public int randomize(final String filename, final PrintStream log, long seed) { // In-game trades List oldTrades = romHandler.getIngameTrades(); if (settings.getInGameTradesMod() == Settings.InGameTradesMod.RANDOMIZE_GIVEN) { - romHandler.randomizeIngameTrades(false, settings.getNicknames(), - settings.isRandomizeInGameTradesNicknames(), settings.getTrainerNames(), + romHandler.randomizeIngameTrades(false, settings.isRandomizeInGameTradesNicknames(), settings.isRandomizeInGameTradesOTs(), settings.isRandomizeInGameTradesIVs(), - settings.isRandomizeInGameTradesItems()); + settings.isRandomizeInGameTradesItems(), settings.getCustomNames()); } else if (settings.getInGameTradesMod() == Settings.InGameTradesMod.RANDOMIZE_GIVEN_AND_REQUESTED) { - romHandler.randomizeIngameTrades(true, settings.getNicknames(), - settings.isRandomizeInGameTradesNicknames(), settings.getTrainerNames(), + romHandler.randomizeIngameTrades(true, settings.isRandomizeInGameTradesNicknames(), settings.isRandomizeInGameTradesOTs(), settings.isRandomizeInGameTradesIVs(), - settings.isRandomizeInGameTradesItems()); + settings.isRandomizeInGameTradesItems(), settings.getCustomNames()); } if (!(settings.getInGameTradesMod() == Settings.InGameTradesMod.UNCHANGED)) { diff --git a/src/com/dabomstew/pkrandom/Settings.java b/src/com/dabomstew/pkrandom/Settings.java index f4fd0ff0a..2dbd5419a 100644 --- a/src/com/dabomstew/pkrandom/Settings.java +++ b/src/com/dabomstew/pkrandom/Settings.java @@ -46,13 +46,11 @@ public class Settings { - public static final int VERSION = 171; + public static final int VERSION = 172; public static final int LENGTH_OF_SETTINGS_DATA = 35; - private byte[] trainerClasses; - private byte[] trainerNames; - private byte[] nicknames; + private CustomNamesSet customNames; private String romName; private boolean updatedFromOldVersion = false; @@ -397,9 +395,7 @@ public String toString() { try { writeFullInt(out, (int) checksum.getValue()); - writeFullInt(out, FileFunctions.getFileChecksum("trainerclasses.txt")); - writeFullInt(out, FileFunctions.getFileChecksum("trainernames.txt")); - writeFullInt(out, FileFunctions.getFileChecksum("nicknames.txt")); + writeFullInt(out, FileFunctions.getFileChecksum(SysConstants.customNamesFile)); } catch (IOException e) { } @@ -703,31 +699,13 @@ public TweakForROMFeedback tweakForRom(RomHandler rh) { } // getters and setters - - public byte[] getTrainerClasses() { - return trainerClasses; - } - - public Settings setTrainerClasses(byte[] trainerClasses) { - this.trainerClasses = trainerClasses; - return this; - } - - public byte[] getTrainerNames() { - return trainerNames; + + public CustomNamesSet getCustomNames() { + return customNames; } - - public Settings setTrainerNames(byte[] trainerNames) { - this.trainerNames = trainerNames; - return this; - } - - public byte[] getNicknames() { - return nicknames; - } - - public Settings setNicknames(byte[] nicknames) { - this.nicknames = nicknames; + + public Settings setCustomNames(CustomNamesSet customNames) { + this.customNames = customNames; return this; } @@ -1576,12 +1554,12 @@ private static int getSetEnum(String type, boolean... bools) { private static void checkChecksum(byte[] data) { // Check the checksum - ByteBuffer buf = ByteBuffer.allocate(4).put(data, data.length - 16, 4); + ByteBuffer buf = ByteBuffer.allocate(4).put(data, data.length - 8, 4); buf.rewind(); int crc = buf.getInt(); CRC32 checksum = new CRC32(); - checksum.update(data, 0, data.length - 16); + checksum.update(data, 0, data.length - 8); if ((int) checksum.getValue() != crc) { throw new IllegalArgumentException("Malformed input string"); diff --git a/src/com/dabomstew/pkrandom/SettingsUpdater.java b/src/com/dabomstew/pkrandom/SettingsUpdater.java index 43c41fd7d..196cf1aa1 100644 --- a/src/com/dabomstew/pkrandom/SettingsUpdater.java +++ b/src/com/dabomstew/pkrandom/SettingsUpdater.java @@ -48,7 +48,7 @@ public class SettingsUpdater { */ public String update(int oldVersion, String configString) { byte[] data = DatatypeConverter.parseBase64Binary(configString); - this.dataBlock = new byte[100]; + this.dataBlock = new byte[200]; this.actualDataLength = data.length; System.arraycopy(data, 0, this.dataBlock, 0, this.actualDataLength); @@ -228,14 +228,20 @@ public String update(int oldVersion, String configString) { insertExtraByte(20, (byte) 0); insertExtraByte(22, (byte) 0); } + + if(oldVersion < 172) { + // 171 to 172: removed separate names files in favor of one unified file + // so two of the trailing checksums are gone + actualDataLength -= 8; + } // fix checksum CRC32 checksum = new CRC32(); - checksum.update(dataBlock, 0, actualDataLength - 16); + checksum.update(dataBlock, 0, actualDataLength - 8); // convert crc32 to int bytes byte[] crcBuf = ByteBuffer.allocate(4).putInt((int) checksum.getValue()).array(); - System.arraycopy(crcBuf, 0, dataBlock, actualDataLength - 16, 4); + System.arraycopy(crcBuf, 0, dataBlock, actualDataLength - 8, 4); // have to make a new byte array to convert to base64 byte[] finalConfigString = new byte[actualDataLength]; diff --git a/src/com/dabomstew/pkrandom/SysConstants.java b/src/com/dabomstew/pkrandom/SysConstants.java index fd1f2d66e..3af63969f 100644 --- a/src/com/dabomstew/pkrandom/SysConstants.java +++ b/src/com/dabomstew/pkrandom/SysConstants.java @@ -33,6 +33,12 @@ public class SysConstants { public static final String WEBSITE_URL = "http://pokehacks.dabomstew.com/randomizer/"; public static final int UPDATE_VERSION = 1710; public static final String ROOT_PATH = getRootPath(); + public static final String customNamesFile = "customnames.rncn"; + + // OLD custom names files + public static final String tnamesFile = "trainernames.txt"; + public static final String tclassesFile = "trainerclasses.txt"; + public static final String nnamesFile = "nicknames.txt"; private static String getRootPath() { try { diff --git a/src/com/dabomstew/pkrandom/Utils.java b/src/com/dabomstew/pkrandom/Utils.java index d0155af2e..1825802df 100644 --- a/src/com/dabomstew/pkrandom/Utils.java +++ b/src/com/dabomstew/pkrandom/Utils.java @@ -79,8 +79,7 @@ public static void testForRequiredConfigs() throws FileNotFoundException { String[] required = new String[] { "gameboy_jap.tbl", "rby_english.tbl", "rby_freger.tbl", "rby_espita.tbl", "green_translation.tbl", "gsc_english.tbl", "gsc_freger.tbl", "gsc_espita.tbl", "gba_english.tbl", "gba_jap.tbl", "Generation4.tbl", "Generation5.tbl", "gen1_offsets.ini", "gen2_offsets.ini", - "gen3_offsets.ini", "gen4_offsets.ini", "gen5_offsets.ini", "trainerclasses.txt", "trainernames.txt", - "nicknames.txt" }; + "gen3_offsets.ini", "gen4_offsets.ini", "gen5_offsets.ini", SysConstants.customNamesFile }; for (String filename : required) { if (!FileFunctions.configExists(filename)) { throw new FileNotFoundException(filename); @@ -88,42 +87,30 @@ public static void testForRequiredConfigs() throws FileNotFoundException { } } - public static void validatePresetSupplementFiles(String config, byte[] trainerClasses, byte[] trainerNames, - byte[] nicknames) throws UnsupportedEncodingException, InvalidSupplementFilesException { + public static void validatePresetSupplementFiles(String config, CustomNamesSet customNames) + throws UnsupportedEncodingException, InvalidSupplementFilesException { byte[] data = DatatypeConverter.parseBase64Binary(config); - if (data.length < Settings.LENGTH_OF_SETTINGS_DATA + 17) { - throw new InvalidSupplementFilesException(InvalidSupplementFilesException.Type.TOO_SHORT, + if (data.length < Settings.LENGTH_OF_SETTINGS_DATA + 9) { + throw new InvalidSupplementFilesException(InvalidSupplementFilesException.Type.UNKNOWN, "The preset config is too short to be valid"); } // Check the checksum - ByteBuffer buf = ByteBuffer.allocate(4).put(data, data.length - 16, 4); + ByteBuffer buf = ByteBuffer.allocate(4).put(data, data.length - 8, 4); buf.rewind(); int crc = buf.getInt(); CRC32 checksum = new CRC32(); - checksum.update(data, 0, data.length - 16); + checksum.update(data, 0, data.length - 8); if ((int) checksum.getValue() != crc) { throw new IllegalArgumentException("Checksum failure."); } // Check the trainerclass & trainernames & nicknames crc - if (trainerClasses == null && !FileFunctions.checkOtherCRC(data, 0, 6, "trainerclasses.txt", data.length - 12)) { - throw new InvalidSupplementFilesException(InvalidSupplementFilesException.Type.NICKNAMES, - "Can't use this preset because you have a different set " - + "of random trainer class names to the creator."); - } - if (trainerNames == null - && (!FileFunctions.checkOtherCRC(data, 0, 5, "trainernames.txt", data.length - 8) || !FileFunctions - .checkOtherCRC(data, 16, 5, "trainernames.txt", data.length - 8))) { - throw new InvalidSupplementFilesException(InvalidSupplementFilesException.Type.NICKNAMES, - "Can't use this preset because you have a different set " - + "of random trainer names to the creator."); - } - if (nicknames == null && !FileFunctions.checkOtherCRC(data, 16, 4, "nicknames.txt", data.length - 4)) { - throw new InvalidSupplementFilesException(InvalidSupplementFilesException.Type.NICKNAMES, - "Can't use this preset because you have a different set " + "of random nicknames to the creator."); + if (customNames == null && !FileFunctions.checkOtherCRC(data, 16, 4, SysConstants.customNamesFile, data.length - 4)) { + throw new InvalidSupplementFilesException(InvalidSupplementFilesException.Type.CUSTOM_NAMES, + "Can't use this preset because you have a different set " + "of custom names to the creator."); } } diff --git a/src/com/dabomstew/pkrandom/config/customnames.rncn b/src/com/dabomstew/pkrandom/config/customnames.rncn new file mode 100644 index 0000000000000000000000000000000000000000..7f1cafff9c01d1d2f878e00761c1672a8ce9b85c GIT binary patch literal 1709 zcmY*aOOD${5S6nOpgVBIrSBk8GXgY{Eer(<_O8^dAscFT$<5|yq_0iiQ1~FyxJO4&fAGd6ts}%8_m!T4f|g4d^<=m95iUEAbximG~Qe_T+o` zRzvL+Yen8N(6;1jQ97-3)B~4HtM*UA&M9&vqwytmorV4=A#jge4}Ihl;pC2-5r-0v ze1a{cDy+M~wV}SV%5TGcZw*+K;nqh2{zg2-c03>Ymb9`hT?2cA_(QOLw0CqTK{G!k zo1%T;AU?rWhJs@)y}X}5d(lJ#@&l^bqGN#3HlWKVMlfnQ!fSmKweCltvyax};D*fi zf#E`qrH=w3YOl*y!R6A9#l6{Xgq_WP`ButBGXiNXHQ-b#TYf>qg~4k}Kag=tHNI;k z(uwH7tiXMvRb^{6wsfo)|7i$4@*SvC-%3mr{BD_Q)t4cHhF-l%XK{r_?Z;qK+m}OZ zHNG;zo&fV``^2~+iz4-EeWURehgVW2hd?M1mhxs?f?nS`Pnsj;(pr|D9Igz_8JY$x z!8|Z0KGhZDrWTY>3HkGd10~KY?roE>S2pliM}HFnf-r$j5$inx;=yA#X)`u(^6D!-y)HZ3M6P1bmz zN$3v_EzBNe0A>|2T}?LLX)Ara-ut`9;HM;-d1*L%?_V)ASxFHu2c8EX179#ytY}BJ zO>kNmo>YVjR1k$o)?Tzr^DnFq_T(!Q#l%-oPhMTLk+gPx}L(JS`XOhCHnhd~zt@ z=G-mEgT=*Cm#YTkt|K5o!Y5Y^<7Uk{ui~IJ54mdUearG}$_a7G3USH{amoyF$_?>7 zJLD-p#GeeHOdKHoWC3O30a2Nt`acg>>+w`}l<&c|3i$>NEoHdqV%iZRM>_=d6hZRJ zrUU9q4^z5()NYj2ScQ-2#K#1(^mT$M?~{o0pIx0zX#k44>ns761Eys1=-s_5UuD3| zyt`Tqw@c5qM=*$`!@XCr|T%phSRclMNMz8IU z4hss4Wpr0J_j(t1$fW-SRVQa%Zot$1y|cB~$-@LCheck this to randomize the class RandomizerGUI.cantWriteConfigFile=WARNING: The randomizer is unable to write its config file to the directory it is in.\nThis means that it will probably be unable to save the randomized ROMs it creates.\nPlease run the randomizer from a directory where you can write files.\nYou can try to use the randomizer as-is, but it will probably not work and the auto-updater will be disabled. RandomizerGUI.copyNameFilesDialog.text=You appear to have customized name files in the config directory left over from an old version of the randomizer.\nWould you like these files to be copied to the main program directory so they are used in this version? RandomizerGUI.copyNameFilesDialog.title=Copy custom names? +RandomizerGUI.convertNameFilesDialog.text=You appear to have customized name files in the randomizer directory left over from an old version of the randomizer.\nWould you like these files to be converted to the new custom names format so they are used in this version? +RandomizerGUI.convertNameFilesDialog.title=Convert custom names? RandomizerGUI.copyNameFilesFailed=At least one file was not able to be copied. +RandomizerGUI.convertNameFilesFailed=Could not convert custom names to the new format. RandomizerGUI.configFileMissing=The file %s is missing from the configuration and so this program cannot start.\nPlease make sure you extract the program from the ZIP file before running it. RandomizerGUI.noRomLoaded=NO ROM LOADED RandomizerGUI.loadingText=Loading... @@ -137,6 +140,7 @@ RandomizerGUI.invalidSettingsFile=Settings file is not valid. RandomizerGUI.settingsLoaded=Settings loaded from %s. RandomizerGUI.settingsLoadFailed=Settings file load failed. Please try again. RandomizerGUI.settingsSaveFailed=Settings file save failed. Please try again. +RandomizerGUI.cantLoadCustomNames=Could not initialise custom names data.\nPlease redownload the randomizer and try again. RandomizerGUI.abilitiesPanel.border.title=Pokemon Abilities RandomizerGUI.paUnchangedRB.text=Unchanged RandomizerGUI.paUnchangedRB.toolTipText=Don't change Pokemon abilities from the base at all. @@ -263,7 +267,7 @@ RandomizerGUI.tmHmTutorPanel.TabConstraints.tabTitle=TM/HMs & Tutors RandomizerGUI.startersInnerPanel.TabConstraints.tabTitle=Starters, Statics & Trades RandomizerGUI.trainersInnerPanel.TabConstraints.tabTitle=Trainer Pokemon RandomizerGUI.fieldItemsInnerPanel.TabConstraints.tabTitle=Field Items -RandomizerGUI.versionLabel.text=Randomizer Version 1.7.1 +RandomizerGUI.versionLabel.text=Randomizer Version 1.7.2-dev RandomizerGUI.websiteLinkLabel.text=http://pokehacks.dabomstew.com/randomizer RandomizerGUI.peUnchangedRB.text=Unchanged RandomizerGUI.peRandomRB.text=Randomize diff --git a/src/com/dabomstew/pkrandom/gui/PresetLoadDialog.java b/src/com/dabomstew/pkrandom/gui/PresetLoadDialog.java index bf26c10a1..829caa161 100755 --- a/src/com/dabomstew/pkrandom/gui/PresetLoadDialog.java +++ b/src/com/dabomstew/pkrandom/gui/PresetLoadDialog.java @@ -42,7 +42,7 @@ import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; -import com.dabomstew.pkrandom.FileFunctions; +import com.dabomstew.pkrandom.CustomNamesSet; import com.dabomstew.pkrandom.RandomSource; import com.dabomstew.pkrandom.Settings; import com.dabomstew.pkrandom.exceptions.InvalidSupplementFilesException; @@ -63,7 +63,7 @@ public class PresetLoadDialog extends javax.swing.JDialog { private boolean completed = false; private String requiredName = null; private volatile boolean changeFieldsWithoutCheck = false; - private byte[] trainerClasses = null, trainerNames = null, nicknames = null; + private CustomNamesSet customNames; java.util.ResourceBundle bundle; /** @@ -123,6 +123,7 @@ protected boolean checkValues() { invalidValues(); return false; } + // 161 onwards: look for version number String configString = this.configStringField.getText(); if (configString.length() < 3) { @@ -144,8 +145,7 @@ protected boolean checkValues() { } try { - name = this.parentGUI.getValidRequiredROMName(configString.substring(3), trainerClasses, trainerNames, - nicknames); + name = this.parentGUI.getValidRequiredROMName(configString.substring(3), customNames); } catch (InvalidSupplementFilesException ex) { safelyClearFields(); invalidValues(); @@ -206,6 +206,8 @@ private void promptForDifferentRandomizerVersion(int presetVN) { versionWanted = "1.6.3b"; } else if (presetVN == 170) { versionWanted = "1.7.0b"; + } else if (presetVN == 171) { + versionWanted = "1.7.1"; } JOptionPane.showMessageDialog(this, String.format(bundle.getString("PresetLoadDialog.olderVersionRequired"), versionWanted)); @@ -250,16 +252,8 @@ public String getConfigString() { return this.configStringField.getText().substring(3); } - public byte[] getTrainerClasses() { - return trainerClasses; - } - - public byte[] getTrainerNames() { - return trainerNames; - } - - public byte[] getNicknames() { - return nicknames; + public CustomNamesSet getCustomNames() { + return customNames; } private void presetFileButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_presetFileButtonActionPerformed @@ -277,12 +271,7 @@ private void presetFileButtonActionPerformed(java.awt.event.ActionEvent evt) {// } long seed = dis.readLong(); String preset = dis.readUTF(); - int tclen = dis.readInt(); - trainerClasses = FileFunctions.readFullyIntoBuffer(dis, tclen); - int tnlen = dis.readInt(); - trainerNames = FileFunctions.readFullyIntoBuffer(dis, tnlen); - int nnlen = dis.readInt(); - nicknames = FileFunctions.readFullyIntoBuffer(dis, nnlen); + customNames = new CustomNamesSet(dis); changeFieldsWithoutCheck = true; this.randomSeedField.setText(Long.toString(seed)); this.configStringField.setText(checkByte + "" + preset); @@ -297,8 +286,7 @@ private void presetFileButtonActionPerformed(java.awt.event.ActionEvent evt) {// this.randomSeedField.setEnabled(true); this.configStringField.setEnabled(true); this.presetFileField.setText(""); - trainerClasses = null; - trainerNames = null; + customNames = null; JOptionPane.showMessageDialog(this, bundle.getString("PresetLoadDialog.invalidSeedFile")); } dis.close(); diff --git a/src/com/dabomstew/pkrandom/gui/PresetMakeDialog.java b/src/com/dabomstew/pkrandom/gui/PresetMakeDialog.java index 6ffbe1e3e..9fa098b5c 100755 --- a/src/com/dabomstew/pkrandom/gui/PresetMakeDialog.java +++ b/src/com/dabomstew/pkrandom/gui/PresetMakeDialog.java @@ -44,6 +44,7 @@ import com.dabomstew.pkrandom.FileFunctions; import com.dabomstew.pkrandom.Settings; +import com.dabomstew.pkrandom.SysConstants; /** * @@ -203,15 +204,8 @@ private void produceFileButtonActionPerformed(java.awt.event.ActionEvent evt) {/ dos.writeByte((byte) Settings.VERSION); dos.writeLong(seed); dos.writeUTF(configString); - byte[] trainerclasses = readFile(FileFunctions.openConfig("trainerclasses.txt")); - dos.writeInt(trainerclasses.length); - dos.write(trainerclasses); - byte[] trainernames = readFile(FileFunctions.openConfig("trainernames.txt")); - dos.writeInt(trainernames.length); - dos.write(trainernames); - byte[] nicknames = readFile(FileFunctions.openConfig("nicknames.txt")); - dos.writeInt(nicknames.length); - dos.write(nicknames); + byte[] customnames = readFile(FileFunctions.openConfig(SysConstants.customNamesFile)); + dos.write(customnames); dos.close(); JOptionPane.showMessageDialog(this, "Preset file saved to\n" + fh.getAbsolutePath()); } catch (IOException ex) { diff --git a/src/com/dabomstew/pkrandom/gui/RandomizerGUI.java b/src/com/dabomstew/pkrandom/gui/RandomizerGUI.java index 462793a57..ac5f7817b 100755 --- a/src/com/dabomstew/pkrandom/gui/RandomizerGUI.java +++ b/src/com/dabomstew/pkrandom/gui/RandomizerGUI.java @@ -66,6 +66,7 @@ import javax.swing.border.TitledBorder; import javax.xml.bind.DatatypeConverter; +import com.dabomstew.pkrandom.CustomNamesSet; import com.dabomstew.pkrandom.FileFunctions; import com.dabomstew.pkrandom.MiscTweak; import com.dabomstew.pkrandom.RandomSource; @@ -554,52 +555,33 @@ private GroupLayout makeTweaksLayout(List tweaks) { return gl; } + /** + * Repurposed: now checks for converting old custom names format to new + */ private void checkCustomNames() { - String[] cnamefiles = new String[] { "trainerclasses.txt", "trainernames.txt", "nicknames.txt" }; - int[] defaultcsums = new int[] { -1442281799, -1499590809, 1641673648 }; + String[] cnamefiles = new String[] { SysConstants.tnamesFile, SysConstants.tclassesFile, + SysConstants.nnamesFile }; - boolean foundCustom = false; + boolean foundFile = false; for (int file = 0; file < 3; file++) { - File oldFile = new File(SysConstants.ROOT_PATH + "/config/" + cnamefiles[file]); File currentFile = new File(SysConstants.ROOT_PATH + cnamefiles[file]); - if (oldFile.exists() && oldFile.canRead() && !currentFile.exists()) { - try { - int crc = FileFunctions.getFileChecksum(new FileInputStream(oldFile)); - if (crc != defaultcsums[file]) { - foundCustom = true; - break; - } - } catch (FileNotFoundException e) { - } + if (currentFile.exists()) { + foundFile = true; + break; } } - if (foundCustom) { + if (foundFile) { int response = JOptionPane.showConfirmDialog(RandomizerGUI.this, - bundle.getString("RandomizerGUI.copyNameFilesDialog.text"), - bundle.getString("RandomizerGUI.copyNameFilesDialog.title"), JOptionPane.YES_NO_OPTION); - boolean onefailed = false; + bundle.getString("RandomizerGUI.convertNameFilesDialog.text"), + bundle.getString("RandomizerGUI.convertNameFilesDialog.title"), JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) { - for (String filename : cnamefiles) { - if (new File(SysConstants.ROOT_PATH + "/config/" + filename).canRead()) { - try { - FileInputStream fis = new FileInputStream(new File(SysConstants.ROOT_PATH + "config/" - + filename)); - FileOutputStream fos = new FileOutputStream(new File(SysConstants.ROOT_PATH + filename)); - byte[] buf = new byte[1024]; - int len; - while ((len = fis.read(buf)) > 0) { - fos.write(buf, 0, len); - } - fos.close(); - fis.close(); - } catch (IOException ex) { - onefailed = true; - } - } - } - if (onefailed) { - JOptionPane.showMessageDialog(this, bundle.getString("RandomizerGUI.copyNameFilesFailed")); + try { + CustomNamesSet newNamesData = CustomNamesSet.importOldNames(); + byte[] data = newNamesData.getBytes(); + FileFunctions.writeBytesToFile(SysConstants.customNamesFile, data); + } catch (IOException ex) { + JOptionPane.showMessageDialog(this, bundle.getString("RandomizerGUI.convertNameFilesFailed")); } } } @@ -627,7 +609,7 @@ private void attemptReadConfig() { String key = tokens[0].trim(); if (key.equalsIgnoreCase("autoupdate")) { autoUpdateEnabled = Boolean.parseBoolean(tokens[1].trim()); - } else if (key.equalsIgnoreCase("checkedcustomnames")) { + } else if (key.equalsIgnoreCase("checkedcustomnames172")) { haveCheckedCustomNames = Boolean.parseBoolean(tokens[1].trim()); } else if (key.equalsIgnoreCase("usescrollpane")) { useScrollPaneMode = Boolean.parseBoolean(tokens[1].trim()); @@ -650,7 +632,8 @@ private boolean attemptWriteConfig() { try { PrintStream ps = new PrintStream(new FileOutputStream(fh), true, "UTF-8"); ps.println("autoupdate=" + autoUpdateEnabled); - ps.println("checkedcustomnames=" + haveCheckedCustomNames); + ps.println("checkedcustomnames=true"); + ps.println("checkedcustomnames172=" + haveCheckedCustomNames); ps.println("usescrollpane=" + useScrollPaneMode); ps.close(); return true; @@ -1588,42 +1571,32 @@ private void saveROM() { // Apply it RandomSource.seed(seed); presetMode = false; - performRandomization(fh.getAbsolutePath(), seed, null, null, null); - } - } - } - private Settings getCurrentSettings() { - byte[] trainerClasses = null; - byte[] trainerNames = null; - byte[] nicknames = null; + try { + CustomNamesSet cns = FileFunctions.getCustomNames(); + performRandomization(fh.getAbsolutePath(), seed, cns); + } catch (IOException ex) { + JOptionPane.showMessageDialog(this, bundle.getString("RandomizerGUI.cantLoadCustomNames")); + } - try { - trainerClasses = FileFunctions.getConfigAsBytes("trainerclasses.txt"); - trainerNames = FileFunctions.getConfigAsBytes("trainernames.txt"); - nicknames = FileFunctions.getConfigAsBytes("nicknames.txt"); - } catch (IOException e) { + } } + } - Settings settings = createSettingsFromState(trainerClasses, trainerNames, nicknames); + private Settings getCurrentSettings() throws IOException { + Settings settings = createSettingsFromState(FileFunctions.getCustomNames()); return settings; } - public String getValidRequiredROMName(String config, byte[] trainerClasses, byte[] trainerNames, byte[] nicknames) + public String getValidRequiredROMName(String config, CustomNamesSet customNames) throws UnsupportedEncodingException, InvalidSupplementFilesException { try { - Utils.validatePresetSupplementFiles(config, trainerClasses, trainerNames, nicknames); + Utils.validatePresetSupplementFiles(config, customNames); } catch (InvalidSupplementFilesException e) { switch (e.getType()) { - case TRAINER_CLASSES: - JOptionPane.showMessageDialog(null, bundle.getString("RandomizerGUI.presetFailTrainerClasses")); - throw e; - case TRAINER_NAMES: + case CUSTOM_NAMES: JOptionPane.showMessageDialog(null, bundle.getString("RandomizerGUI.presetFailTrainerNames")); throw e; - case NICKNAMES: - JOptionPane.showMessageDialog(null, bundle.getString("RandomizerGUI.presetFailNicknames")); - throw e; default: throw e; } @@ -1631,7 +1604,7 @@ public String getValidRequiredROMName(String config, byte[] trainerClasses, byte byte[] data = DatatypeConverter.parseBase64Binary(config); int nameLength = data[Settings.LENGTH_OF_SETTINGS_DATA] & 0xFF; - if (data.length != Settings.LENGTH_OF_SETTINGS_DATA + 17 + nameLength) { + if (data.length != Settings.LENGTH_OF_SETTINGS_DATA + 9 + nameLength) { return null; // not valid length } String name = new String(data, Settings.LENGTH_OF_SETTINGS_DATA + 1, nameLength, "US-ASCII"); @@ -1798,7 +1771,7 @@ private void restoreStateFromSettings(Settings settings) { this.enableOrDisableSubControls(); } - private Settings createSettingsFromState(byte[] trainerClasses, byte[] trainerNames, byte[] nicknames) { + private Settings createSettingsFromState(CustomNamesSet customNames) { Settings settings = new Settings(); settings.setRomName(this.romHandler.getROMName()); settings.setChangeImpossibleEvolutions(goRemoveTradeEvosCheckBox.isSelected()); @@ -1921,16 +1894,13 @@ private Settings createSettingsFromState(byte[] trainerClasses, byte[] trainerNa settings.setCurrentMiscTweaks(currentMiscTweaks); - settings.setTrainerNames(trainerNames); - settings.setTrainerClasses(trainerClasses); - settings.setNicknames(nicknames); + settings.setCustomNames(customNames); return settings; } - private void performRandomization(final String filename, final long seed, byte[] trainerClasses, - byte[] trainerNames, byte[] nicknames) { - final Settings settings = createSettingsFromState(trainerClasses, trainerNames, nicknames); + private void performRandomization(final String filename, final long seed, CustomNamesSet customNames) { + final Settings settings = createSettingsFromState(customNames); final boolean raceMode = settings.isRaceMode(); // Setup verbose log final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -2016,9 +1986,14 @@ public void run() { initialFormState(); } else { // Compile a config string - String configString = getCurrentSettings().toString(); - // Show the preset maker - new PresetMakeDialog(RandomizerGUI.this, seed, configString); + try { + String configString = getCurrentSettings().toString(); + // Show the preset maker + new PresetMakeDialog(RandomizerGUI.this, seed, configString); + } catch (IOException ex) { + JOptionPane.showMessageDialog(RandomizerGUI.this, + bundle.getString("RandomizerGUI.cantLoadCustomNames")); + } // Done RandomizerGUI.this.romHandler = null; @@ -2085,8 +2060,7 @@ private void presetLoader() { // Apply the seed we were given RandomSource.seed(seed); presetMode = true; - performRandomization(fh.getAbsolutePath(), seed, pld.getTrainerClasses(), pld.getTrainerNames(), - pld.getNicknames()); + performRandomization(fh.getAbsolutePath(), seed, pld.getCustomNames()); } else { this.romHandler = null; initialFormState(); diff --git a/src/com/dabomstew/pkrandom/romhandlers/AbstractRomHandler.java b/src/com/dabomstew/pkrandom/romhandlers/AbstractRomHandler.java index c58938150..d1df479d3 100755 --- a/src/com/dabomstew/pkrandom/romhandlers/AbstractRomHandler.java +++ b/src/com/dabomstew/pkrandom/romhandlers/AbstractRomHandler.java @@ -27,8 +27,6 @@ /*-- along with this program. If not, see . --*/ /*----------------------------------------------------------------------------*/ -import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; @@ -41,13 +39,12 @@ import java.util.Map; import java.util.Queue; import java.util.Random; -import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; -import com.dabomstew.pkrandom.FileFunctions; +import com.dabomstew.pkrandom.CustomNamesSet; import com.dabomstew.pkrandom.MiscTweak; import com.dabomstew.pkrandom.RomFunctions; import com.dabomstew.pkrandom.constants.GlobalConstants; @@ -70,10 +67,6 @@ public abstract class AbstractRomHandler implements RomHandler { - private static final String tnamesFile = "trainernames.txt"; - private static final String tclassesFile = "trainerclasses.txt"; - private static final String nnamesFile = "nicknames.txt"; - private boolean restrictionsSet; protected List mainPokemonList; protected List noLegendaryList, onlyLegendaryList; @@ -1757,7 +1750,7 @@ public void randomizeMovesLearnt(boolean typeThemed, boolean noBroken, boolean f List pickList = validMoves; if (attemptDamaging) { if (typeOfMove != null) { - if (checkForUnusedMove(validTypeDamagingMoves.get(typeOfMove), learnt)) { + if (validTypeDamagingMoves.containsKey(typeOfMove) && checkForUnusedMove(validTypeDamagingMoves.get(typeOfMove), learnt)) { pickList = validTypeDamagingMoves.get(typeOfMove); } else if (checkForUnusedMove(validDamagingMoves, learnt)) { pickList = validDamagingMoves; @@ -1766,7 +1759,7 @@ public void randomizeMovesLearnt(boolean typeThemed, boolean noBroken, boolean f pickList = validDamagingMoves; } } else if (typeOfMove != null) { - if (checkForUnusedMove(validTypeMoves.get(typeOfMove), learnt)) { + if (validTypeMoves.containsKey(typeOfMove) && checkForUnusedMove(validTypeMoves.get(typeOfMove), learnt)) { pickList = validTypeMoves.get(typeOfMove); } } @@ -2261,47 +2254,42 @@ public void ensureMoveTutorCompatSanity() { @SuppressWarnings("unchecked") @Override - public void randomizeTrainerNames(byte[] presetNames) { + public void randomizeTrainerNames(CustomNamesSet customNames) { if (!this.canChangeTrainerText()) { return; } + // index 0 = singles, 1 = doubles List[] allTrainerNames = new List[] { new ArrayList(), new ArrayList() }; Map> trainerNamesByLength[] = new Map[] { new TreeMap>(), new TreeMap>() }; - // Check for the file - if (FileFunctions.configExists(tnamesFile)) { - try { - Scanner sc = null; - if (presetNames == null) { - sc = new Scanner(FileFunctions.openConfig(tnamesFile), "UTF-8"); + + // Read name lists + for (String trainername : customNames.getTrainerNames()) { + int len = this.internalStringLength(trainername); + if (len <= 10) { + allTrainerNames[0].add(trainername); + if (trainerNamesByLength[0].containsKey(len)) { + trainerNamesByLength[0].get(len).add(trainername); } else { - sc = new Scanner(new ByteArrayInputStream(presetNames), "UTF-8"); - } - while (sc.hasNextLine()) { - String trainername = sc.nextLine().trim(); - if (trainername.isEmpty()) { - continue; - } - if (trainername.startsWith("\uFEFF")) { - trainername = trainername.substring(1); - } - int idx = trainername.contains("&") ? 1 : 0; - int len = this.internalStringLength(trainername); - if (len <= 10) { - allTrainerNames[idx].add(trainername); - if (trainerNamesByLength[idx].containsKey(len)) { - trainerNamesByLength[idx].get(len).add(trainername); - } else { - List namesOfThisLength = new ArrayList(); - namesOfThisLength.add(trainername); - trainerNamesByLength[idx].put(len, namesOfThisLength); - } - } + List namesOfThisLength = new ArrayList(); + namesOfThisLength.add(trainername); + trainerNamesByLength[0].put(len, namesOfThisLength); + } + } + } + + for (String trainername : customNames.getDoublesTrainerNames()) { + int len = this.internalStringLength(trainername); + if (len <= 10) { + allTrainerNames[1].add(trainername); + if (trainerNamesByLength[1].containsKey(len)) { + trainerNamesByLength[1].get(len).add(trainername); + } else { + List namesOfThisLength = new ArrayList(); + namesOfThisLength.add(trainername); + trainerNamesByLength[1].put(len, namesOfThisLength); } - sc.close(); - } catch (FileNotFoundException e) { - // Can't read, just don't load anything } } @@ -2380,7 +2368,7 @@ public void randomizeTrainerNames(byte[] presetNames) { if (!success) { throw new RandomizationException("Could not randomize trainer names in a reasonable amount of attempts." - + "\nPlease add some shorter names to your trainer names file."); + + "\nPlease add some shorter names to your custom trainer names."); } // Done choosing, save @@ -2389,48 +2377,38 @@ public void randomizeTrainerNames(byte[] presetNames) { @SuppressWarnings("unchecked") @Override - public void randomizeTrainerClassNames(byte[] presetNames) { + public void randomizeTrainerClassNames(CustomNamesSet customNames) { if (!this.canChangeTrainerText()) { return; } + // index 0 = singles, index 1 = doubles List allTrainerClasses[] = new List[] { new ArrayList(), new ArrayList() }; Map> trainerClassesByLength[] = new Map[] { new HashMap>(), new HashMap>() }; - // Check for the file - if (FileFunctions.configExists(tclassesFile)) { - try { - Scanner sc = null; - if (presetNames == null) { - sc = new Scanner(FileFunctions.openConfig(tclassesFile), "UTF-8"); - } else { - sc = new Scanner(new ByteArrayInputStream(presetNames), "UTF-8"); - } - while (sc.hasNextLine()) { - String trainerClassName = sc.nextLine().trim(); - if (trainerClassName.isEmpty()) { - continue; - } - if (trainerClassName.startsWith("\uFEFF")) { - trainerClassName = trainerClassName.substring(1); - } - String checkName = trainerClassName.toLowerCase(); - int idx = (checkName.endsWith("couple") || checkName.contains(" and ") || checkName.endsWith("kin") - || checkName.endsWith("team") || checkName.contains("&") || (checkName.endsWith("s") && !checkName - .endsWith("ss"))) ? 1 : 0; - allTrainerClasses[idx].add(trainerClassName); - int len = this.internalStringLength(trainerClassName); - if (trainerClassesByLength[idx].containsKey(len)) { - trainerClassesByLength[idx].get(len).add(trainerClassName); - } else { - List namesOfThisLength = new ArrayList(); - namesOfThisLength.add(trainerClassName); - trainerClassesByLength[idx].put(len, namesOfThisLength); - } - } - sc.close(); - } catch (FileNotFoundException e) { - // Can't read, just don't load anything + + // Read names data + for (String trainerClassName : customNames.getTrainerClasses()) { + allTrainerClasses[0].add(trainerClassName); + int len = this.internalStringLength(trainerClassName); + if (trainerClassesByLength[0].containsKey(len)) { + trainerClassesByLength[0].get(len).add(trainerClassName); + } else { + List namesOfThisLength = new ArrayList(); + namesOfThisLength.add(trainerClassName); + trainerClassesByLength[0].put(len, namesOfThisLength); + } + } + + for (String trainerClassName : customNames.getDoublesTrainerClasses()) { + allTrainerClasses[1].add(trainerClassName); + int len = this.internalStringLength(trainerClassName); + if (trainerClassesByLength[1].containsKey(len)) { + trainerClassesByLength[1].get(len).add(trainerClassName); + } else { + List namesOfThisLength = new ArrayList(); + namesOfThisLength.add(trainerClassName); + trainerClassesByLength[1].put(len, namesOfThisLength); } } @@ -2635,69 +2613,32 @@ public void randomizeFieldItems(boolean banBadItems) { } @Override - public void randomizeIngameTrades(boolean randomizeRequest, byte[] presetNicknames, boolean randomNickname, - byte[] presetTrainerNames, boolean randomOT, boolean randomStats, boolean randomItem) { + public void randomizeIngameTrades(boolean randomizeRequest, boolean randomNickname, boolean randomOT, + boolean randomStats, boolean randomItem, CustomNamesSet customNames) { checkPokemonRestrictions(); // Process trainer names - List singleTrainerNames = new ArrayList(); + List trainerNames = new ArrayList(); // Check for the file - if (FileFunctions.configExists(tnamesFile) && randomOT) { + if (randomOT) { int maxOT = this.maxTradeOTNameLength(); - try { - Scanner sc = null; - if (presetTrainerNames == null) { - sc = new Scanner(FileFunctions.openConfig(tnamesFile), "UTF-8"); - } else { - sc = new Scanner(new ByteArrayInputStream(presetTrainerNames), "UTF-8"); - } - while (sc.hasNextLine()) { - String trainername = sc.nextLine().trim(); - if (trainername.isEmpty()) { - continue; - } - if (trainername.startsWith("\uFEFF")) { - trainername = trainername.substring(1); - } - int idx = trainername.contains("&") ? 1 : 0; - int len = this.internalStringLength(trainername); - if (len <= maxOT && idx == 0 && !singleTrainerNames.contains(trainername)) { - singleTrainerNames.add(trainername); - } + for (String trainername : customNames.getTrainerNames()) { + int len = this.internalStringLength(trainername); + if (len <= maxOT && !trainerNames.contains(trainername)) { + trainerNames.add(trainername); } - sc.close(); - } catch (FileNotFoundException e) { - // Can't read, just don't load anything } } // Process nicknames List nicknames = new ArrayList(); // Check for the file - if (FileFunctions.configExists(nnamesFile) && randomNickname) { + if (randomNickname) { int maxNN = this.maxTradeNicknameLength(); - try { - Scanner sc = null; - if (presetNicknames == null) { - sc = new Scanner(FileFunctions.openConfig(nnamesFile), "UTF-8"); - } else { - sc = new Scanner(new ByteArrayInputStream(presetNicknames), "UTF-8"); - } - while (sc.hasNextLine()) { - String nickname = sc.nextLine().trim(); - if (nickname.isEmpty()) { - continue; - } - if (nickname.startsWith("\uFEFF")) { - nickname = nickname.substring(1); - } - int len = this.internalStringLength(nickname); - if (len <= maxNN && !nicknames.contains(nickname)) { - nicknames.add(nickname); - } + for (String nickname : customNames.getPokemonNicknames()) { + int len = this.internalStringLength(nickname); + if (len <= maxNN && !nicknames.contains(nickname)) { + nicknames.add(nickname); } - sc.close(); - } catch (FileNotFoundException e) { - // Can't read, just don't load anything } } @@ -2710,7 +2651,7 @@ public void randomizeIngameTrades(boolean randomizeRequest, byte[] presetNicknam ItemList possibleItems = this.getAllowedItems(); int nickCount = nicknames.size(); - int trnameCount = singleTrainerNames.size(); + int trnameCount = trainerNames.size(); for (IngameTrade trade : trades) { // pick new given pokemon @@ -2749,9 +2690,9 @@ public void randomizeIngameTrades(boolean randomizeRequest, byte[] presetNicknam } if (randomOT && trnameCount > usedOTs.size()) { - String ot = singleTrainerNames.get(this.random.nextInt(trnameCount)); + String ot = trainerNames.get(this.random.nextInt(trnameCount)); while (usedOTs.contains(ot)) { - ot = singleTrainerNames.get(this.random.nextInt(trnameCount)); + ot = trainerNames.get(this.random.nextInt(trnameCount)); } usedOTs.add(ot); trade.otName = ot; diff --git a/src/com/dabomstew/pkrandom/romhandlers/RomHandler.java b/src/com/dabomstew/pkrandom/romhandlers/RomHandler.java index 5120b5908..c4bf96573 100755 --- a/src/com/dabomstew/pkrandom/romhandlers/RomHandler.java +++ b/src/com/dabomstew/pkrandom/romhandlers/RomHandler.java @@ -30,6 +30,7 @@ import java.util.Map; import java.util.Random; +import com.dabomstew.pkrandom.CustomNamesSet; import com.dabomstew.pkrandom.MiscTweak; import com.dabomstew.pkrandom.pokemon.EncounterSet; import com.dabomstew.pkrandom.pokemon.GenRestrictions; @@ -292,7 +293,7 @@ public void randomizeMovesLearnt(boolean typeThemed, boolean noBroken, boolean f public void ensureMoveTutorCompatSanity(); // Randomizer: trainer names - + public boolean canChangeTrainerText(); public List getTrainerNames(); @@ -315,7 +316,7 @@ public enum TrainerNameMode { // Only needed if above mode is "MAX LENGTH WITH CLASS" public List getTCNameLengthsByTrainer(); - public void randomizeTrainerNames(byte[] presetNames); + public void randomizeTrainerNames(CustomNamesSet customNames); // Randomizer: trainer class names @@ -327,7 +328,7 @@ public enum TrainerNameMode { public int maxTrainerClassNameLength(); - public void randomizeTrainerClassNames(byte[] presetNames); + public void randomizeTrainerClassNames(CustomNamesSet customNames); // Items @@ -373,8 +374,8 @@ public enum TrainerNameMode { public void setIngameTrades(List trades); - public void randomizeIngameTrades(boolean randomizeRequest, byte[] presetNicknames, boolean randomNickname, - byte[] presetTrainerNames, boolean randomOT, boolean randomStats, boolean randomItem); + public void randomizeIngameTrades(boolean randomizeRequest, boolean randomNickname, boolean randomOT, + boolean randomStats, boolean randomItem, CustomNamesSet customNames); public boolean hasDVs();