├── LICENSE ├── README.md ├── changelog.txt ├── plugin.yml └── src ├── example ├── blackjack_helper │ ├── BlackJackHelper.java │ └── QuickBlackJackHandler.java ├── bot_guesser │ └── BotGuesser.java ├── logical │ ├── LogicalAND.java │ ├── LogicalInverted.java │ ├── LogicalNAND.java │ ├── LogicalNOR.java │ ├── LogicalOR.java │ ├── LogicalXNOR.java │ └── LogicalXOR.java ├── music_bot │ └── MusicBot.java ├── number_adder │ └── NumberAdder.java ├── prime_number_guesser │ └── PrimeNumberBot.java └── swearfilter │ ├── ExampleSwearListener.java │ └── SwearBot.java └── me └── zombie_striker ├── neuralnetwork ├── Controler.java ├── Layer.java ├── NNAI.java ├── NNBaseEntity.java ├── NeuralNetwork.java ├── SIOMemoryHolder.java ├── grapher │ └── Grapher.java ├── neurons │ ├── BiasNeuron.java │ ├── Neuron.java │ ├── OutputNeuron.java │ └── input │ │ ├── InputBlockNeuron.java │ │ ├── InputBooleanNeuron.java │ │ ├── InputLetterNeuron.java │ │ ├── InputMobNeuron.java │ │ ├── InputNeuron.java │ │ ├── InputNumberNeuron.java │ │ └── InputTickNeuron.java ├── senses │ ├── Senses.java │ ├── Senses2D.java │ ├── Senses3D.java │ ├── Sensory2D_Booleans.java │ ├── Sensory2D_Letters.java │ ├── Sensory2D_Numbers.java │ ├── Sensory3D_Booleans.java │ └── Sensory3D_Numbers.java └── util │ ├── Accuracy.java │ ├── DeepReinforcementUtil.java │ ├── LossHolder.java │ ├── MutationUtil.java │ └── SigmoidUtil.java └── nnmain ├── GithubDependDownloader.java ├── GithubUpdater.java ├── HelpPages.java ├── Main.java ├── Metrics.java ├── Save_Config.java └── Updater.java /README.md: -------------------------------------------------------------------------------- 1 | # NeuralNetworkAPI 2 | A bukkit plugin for adding neural networks into minecraft. 3 | 4 | ## How to use (Basic-Demo) 5 | * To start, use `/nn cnn` or `/nn createNewNN` to see the list of all neural network types. I would recommend selecting `LogicalOR` to start off with 6 | * Then, use `/nn startlearning` to start training the NN. 7 | * Almost immediately after sending that command, use `/nn stoplearning` to stop training. Within the seconds of sending these two commands, the bot has gone through over a thousand scenarios, and should be 100% accurate. (For other NNs, you can check the accuracy by checking the console.) 8 | * Now, to test it, use `/nn test` to test two inputs, either true or false. (example: `/nn test true false`) 9 | * For LogicalOR, it should print out true if either the first and/or the second input is true. 10 | 11 | 12 | ### For non-developers 13 | This plugin provides nothing on its own besides a few demos of what this API can achieve. If you do not plan on developing your own NeuralNetwork plugin or using another plugin the uses this API, this plugin may be useless to you. 14 | 15 | ### For plugin developers 16 | There are a few things that you should know before attempting to make a new Neural network type 17 | * The `example` package gives a number of examples of how to create NNs. The logic gate NNs should be the easiest to understand. 18 | * By default, all NNs that extends NNBaseEntity automatically implement ConfigurationSerializable. However, in order for bukkit to be able to load these values from the config, you will need to create a new construcor for the class like so: 19 | ````java 20 | public CustomNeuralNetwork(Map map){ 21 | super(map); 22 | } 23 | ```` 24 | ...and let the ConfigurationSerialization class register the object in the onEnable or onLoad of the main class like so: 25 | ````java 26 | public void onEnable(){ 27 | ConfigurationSerialization.registerClass(CustomNeuralNetwork.class); 28 | } 29 | ```` 30 | After this, you should be able to save and load the `NNBaseEntity` to and from the config. Note that you cannot save the `NeuralNetwork` instance to the config. 31 | * Ideally, no other part of your plugin should directly reference your custom neural network object. Instead, all calls to that object should be done through the NeuralNetwork object. 32 | * For best results, only call `DeepReinformentUtil.instantaneousReinforce` when the NN failed in any way. Calling it when it returned the correct value tends to make it "forget" what it may have already learned. 33 | * This API is still in development. Some aspects of this plugin may change in future updates. Continually to check the github page for updates and make sure your project always references the newest version. 34 | * When traing your NeuralNetwork, if you do not want the console to fill up with debug messages, use `NeuralNetwork#setBroadcasting(false);` to disable console debugging. 35 | * If your AI is not return the values you expect, or want to know what your NN is "thinking" given an input, you can open the grapher to have a visualisation of what is happening. Use `NeuralNetwork#openGrapher();` to open the grapher instance. Once you are done, you can use `NeuralNetwork#closeGrapher();` to propperly shut down the window. 36 | * Adding more hidden layers to your neural network increases the complexity of patterns that it can learn. 37 | * In certain cases, having a BiasNeuron can increase or decrease the ability for the network to learn. For situations where certain outputs are needed if there are no inputs (XNOR,NAND, Inverted, for example), then it is better to have atleast 1 bias neuron in the inputs. 38 | * Having BiasNeurons on the hidden layers may or may not help with certain situations. 39 | 40 | 41 | ### How this works 42 | NeuralNetworks start with three basic components, a Sensory array, an AI object, and a Controler object. 43 | * The Sensory array determins the inputs. This could be booleans, representing a true or false value, or numbers which represent possible states the for the input. 44 | * The AI is what converts the inputs into outputs. Through a series of neurons, each with their own values and thresholds, the information is passed from the input into outputs based on how the NN has been trained. 45 | * The Controler is how you convert the outputs into data that you can use. For example, the controler can convert the outputs into a boolean, determining if the AI detected a swear word for a swear filter, or determining the sum of two integers. 46 | 47 | #### GithubPage: 48 | https://github.com/ZombieStriker/NeuralNetworkAPI -------------------------------------------------------------------------------- /changelog.txt: -------------------------------------------------------------------------------- 1 | 1.0.6 2 | Added multi-Scenario-Reinforcement, which should help for non-linear/binary responses 3 | CHANGED WAY NN LEARN. A "learn" method is now called when learning. 4 | CHANGED WAY startLearning.... works. You now need to use startingRepeatinglyLearning.... to repeat the learning. 5 | Added ability to rely on last value for isTriggered. This should reduce the amount of operations done when checking if a neuron is triggered. However, this means you can't change the input on the same tick. Instead, you will need to tick every time you change the input. 6 | Added ability to turn off Thresholds. Best if used for non-binary options of multi-layer NNs 7 | Added activation read-outs for output neurons 8 | Adjusted TriggerStength==0 in grapher so there is an easier distinction between non-triggered neurons and neurons with 0 strength 9 | Added color changes to output neuron text that signifies if the neuron is active, positive, or negitive 10 | Added backPropConnections. In case you want to add new neurons to an existing NN, use this method to connect the neurons from the previous layer to the new neuron. 11 | Added ability to disable negative numbers for neurons, including BiasNeurons and OutputNeurons. Output neurons that do not have negative numbers will have their activation points raised to 0.5 12 | 13 | 1.0.4 14 | Added osB to reduce the config saves even more. 15 | 16 | 1.0.3 17 | Added code-reduction for neuron classes. Config files storing NNs should be 1/3rd the size after this update. 18 | 19 | 1.0.2 20 | Slight change to DRutil. Should increase preformace slightly. 21 | 22 | 1.0.1 23 | Fixed inputletterneuron. 24 | 25 | 1.0.0 26 | init -------------------------------------------------------------------------------- /plugin.yml: -------------------------------------------------------------------------------- 1 | main: me.zombie_striker.nnmain.Main 2 | version: 1.0.6 3 | name: NeuralNetworkAPI 4 | commands: 5 | nn: 6 | description: Test the network 7 | author: 8 | Zombie_Striker -------------------------------------------------------------------------------- /src/example/blackjack_helper/QuickBlackJackHandler.java: -------------------------------------------------------------------------------- 1 | package example.blackjack_helper; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Random; 6 | import java.util.concurrent.ThreadLocalRandom; 7 | 8 | public class QuickBlackJackHandler { 9 | 10 | /** 11 | * This is a small class for handling the decks. You don't really need to see this to understand what is happening. 12 | */ 13 | 14 | 15 | public Card[] cardsInDeck = new Card[52]; 16 | public int currentIndex = 0; 17 | 18 | public QuickBlackJackHandler() { 19 | newDeck(); 20 | } 21 | 22 | //26 :45 or 26/71 ~~ 37% 23 | //Human trials 24 | 25 | public void newDeck(){ 26 | currentIndex=0; 27 | List usedSlots = new ArrayList<>(); 28 | List originDeck = Card.newOrderedDeck(); 29 | cardsInDeck = new Card[52]; 30 | Random r = ThreadLocalRandom.current(); 31 | 32 | //Shuffle 33 | for(int i = 0; i < originDeck.size();i++){ 34 | int newGoodIndex = r.nextInt(cardsInDeck.length); 35 | while(true){ 36 | if(usedSlots.contains(newGoodIndex)){ 37 | newGoodIndex=(newGoodIndex+1)%originDeck.size(); 38 | }else{ 39 | usedSlots.add(newGoodIndex); 40 | cardsInDeck[newGoodIndex] = originDeck.get(i); 41 | break; 42 | } 43 | } 44 | } 45 | } 46 | 47 | 48 | 49 | public static class Card{ 50 | int number; 51 | int value; 52 | int type; 53 | public Card(int number, int type) { 54 | this.number = number; 55 | this.value = number>11?10:number; 56 | this.type = type; 57 | } 58 | public static List newOrderedDeck(){ 59 | Card[] c = new Card[52]; 60 | for(int type = 0; type < 4; type++){ 61 | for(int number = 2; number < 15; number++){ 62 | c[(type*13)+(number-2)]=new Card(number,type); 63 | } 64 | } 65 | List cc = new ArrayList<>(); 66 | for(int i = 0; i < c.length;i++){ 67 | cc.add(c[i]); 68 | } 69 | return cc; 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/example/bot_guesser/BotGuesser.java: -------------------------------------------------------------------------------- 1 | package example.bot_guesser; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | 22 | import org.bukkit.ChatColor; 23 | import org.bukkit.command.CommandSender; 24 | 25 | import me.zombie_striker.neuralnetwork.*; 26 | import me.zombie_striker.neuralnetwork.neurons.*; 27 | import me.zombie_striker.neuralnetwork.neurons.input.InputLetterNeuron; 28 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Letters; 29 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 30 | 31 | public class BotGuesser extends NNBaseEntity implements Controler { 32 | 33 | /** 34 | * This bot checks to see if a user name is a "real account" based on its 35 | * username. Gibberish or random usernames will return false. 36 | */ 37 | 38 | public static char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 39 | 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_' }; 40 | 41 | public Sensory2D_Letters word = new Sensory2D_Letters("none"); 42 | 43 | public BotGuesser base; 44 | 45 | public boolean wasCorrect = true; 46 | 47 | public HashMap ifNameIsValid = new HashMap<>(); 48 | 49 | public BotGuesser(boolean createAI) { 50 | super(false); 51 | this.base = this; 52 | initValidNames(); 53 | 54 | if (createAI) { 55 | // Generates an ai with ONE output, which is equal to whether it is 56 | // a player 57 | this.ai = NNAI.generateAI(this, 1, 4, "Is a real player"); 58 | 59 | for (int index = 0; index < 16; index++) { 60 | for (int character = 0; character < letters.length; character++) { 61 | // 1st one is what index, the next is the actual character 62 | InputLetterNeuron.generateNeuronStatically(ai, index, letters[character], this.word); 63 | } 64 | } 65 | // Creates the neurons for layer 1. 66 | for (int neurons = 0; neurons < 30; neurons++) 67 | Neuron.generateNeuronStatically(ai, 1); 68 | // Create neurons for layer 2 69 | for (int neurons = 0; neurons < 20; neurons++) 70 | Neuron.generateNeuronStatically(ai, 2); 71 | 72 | BiasNeuron.generateNeuronStatically(ai, 0); 73 | BiasNeuron.generateNeuronStatically(ai, 1); 74 | 75 | connectNeurons(); 76 | } 77 | this.controler = this; 78 | 79 | this.setNeuronsPerRow(0, letters.length); 80 | } 81 | 82 | public String learn() { 83 | this.word.changeWord( 84 | (String) ifNameIsValid.keySet().toArray()[(int) ((ifNameIsValid.keySet().size() - 1) * Math.random())]); 85 | boolean result = tickAndThink()[0]; 86 | boolean ishuman = ifNameIsValid.get(base.word.getWord()); 87 | this.getAccuracy().addEntry(result == ishuman); 88 | float accuracy = (float) this.getAccuracy().getAccuracy(); 89 | wasCorrect = result == ishuman; 90 | 91 | // IMPROVE IT 92 | Neuron[] array = new Neuron[1]; 93 | if (ishuman) 94 | array[0] = base.ai.getNeuronFromId(0); 95 | DeepReinforcementUtil.instantaneousReinforce(base, array, (wasCorrect ? 1 : 3)); 96 | return ((result == ishuman ? ChatColor.GREEN : ChatColor.RED) + "acc " + ((int) (100 * accuracy)) + "|=" 97 | + base.word.getWord() + "| " + result + "|Human-Score " 98 | + ((int) (100 * (base.ai.getNeuronFromId(0).getTriggeredStength())))); 99 | } 100 | 101 | @Override 102 | public String update() { 103 | /** 104 | * 1) If it should learn, select a random entry from the map. Based on the way 105 | * we propogate the map, it has a 50% chance of being a valid name. 106 | * 107 | * 2) Tick and think. 108 | * 109 | * 3) If it is not learning, return if it was correct, the word used, and its 110 | * "score". 111 | * 112 | * 4) else, check if the name was a real name, and compare if the NN gave the 113 | * same answer 114 | * 115 | * 5) if it did not, improve it. 116 | */ 117 | boolean result = tickAndThink()[0]; 118 | 119 | return ((result ? ChatColor.DARK_GREEN : ChatColor.DARK_RED) + "|=" + base.word.getWord() + "| " + result 120 | + "|Human-Score " + ((int) (100 * (base.ai.getNeuronFromId(0).getTriggeredStength())))); 121 | 122 | } 123 | 124 | @Override 125 | public void setInputs(CommandSender initiator, String[] args) { 126 | if (this.shouldLearn) { 127 | initiator.sendMessage("Stop the learning before testing. use /nn stoplearning"); 128 | return; 129 | } 130 | if (args.length > 1) { 131 | String username = args[1]; 132 | 133 | this.word.changeWord(username); 134 | return; 135 | } else { 136 | initiator.sendMessage("Provide an id"); 137 | } 138 | } 139 | 140 | private void initValidNames() { 141 | 142 | // This is just a small sample. The more valid names you give it, the 143 | // more accurate it will be. 144 | 145 | // Player names 146 | a("Zombie_Striker", "kermit_23", "Notch", "xephos", "lividcoffee", "dinnerbone", "timtowers", "bfwalshy", 147 | "nvider", "kittengirl", "Cooldude", "Meowgirl", "blabeblade", "coolio3000", "aintnobodygottime", 148 | "cablebox", "Iamhopingyou", "terminator", "gizmo", "snake", "mario", "theotherbrother", "theyellowone", 149 | "peach", "yoshi", "otheryoshi", "sparticus", "neo", "gooby", "loopy", "hewhoshallnot", "benamed", 150 | "harrypotter", "ronweeezl", "hermione", "true", "false", "almond", "putin", "the_donald", "donut", 151 | "lab_guy100", "Killer", "healer", "p90x", "L3375p33k", "up_arrow", "down_arrow", "up", "down", "left", 152 | "right", "foward", "back", "move", "look", "booster", "batman", "joker", "arandomname", 153 | "isthisavailable", "itseemsitis", "iamgod", "thelegend27", "iamtheone", "headphone", 154 | "idontwantittothink", "thatesareagood", "thing", "thang", "ThangsNStuff", "Zombie_killer", "Weezard", 155 | "towny", "worldedit", "lobbyapi", "vault", "vaultboy", "chestprotect", "anticheatplus", 156 | "anticheataulta", "multiworld", "protcollib", "waitIhavetoLetThisthing", "Runforallthese", "options", 157 | "mickey_mouse", "goofy", "pluto", "zues", "WhyDoInotlike_", "_xxSlayerxx_", "Cringelord", 158 | "whatamIDoing", "Ineedtostop", "someonesendhelp", "ihavenotbeendoingthis", "forthatlong", "portal", 159 | "glados", "shell", "chell", "space_core", "cake_core", "fact_core", "imanerd", "nerd", "cave_johnson", 160 | "causeimapotatoe", "lemons", "damnyoulemons", "burninglemons", "wheat", "seeds", "corn", "plow", 161 | "someshortword", "somelongword", "something", "idrk", "itsjustsomething", "aretheserealnames", 162 | "whywouldtheypickthis", "whyareYOUreadingthis", "youcanjuststophere", "thereisnothingelse", 163 | "thatwillbeinteresting", "afterthispoint", "itsnotlikeim", "tired", "omg", "stopit", "noreally", 164 | "cashmeoutside", "howaboutdat", "allhailhypnotoad", "hypnotoad", "thinkthisistoolong", 165 | "ishouldstophere", "ornot", "notlikeanyonewillsee", "this", "wink_Wink", "goodjob", "youmadeit", 166 | "to_the_end", "hereissomecake", "the_cake_is_alie"); 167 | 168 | // Bot names (the chance that one of them will be an actual name is too 169 | // slim to take into account) 170 | // Generates a name from 3 to 16 characters. 171 | for (int i = 0; i < ifNameIsValid.size(); i++) { 172 | StringBuilder sb = new StringBuilder(); 173 | int size = (int) (3 + (13 * Math.random())); 174 | for (int letters = 0; letters < size; letters++) { 175 | sb.append(BotGuesser.letters[(int) (BotGuesser.letters.length * Math.random())]); 176 | } 177 | ifNameIsValid.put(sb.toString(), false); 178 | } 179 | } 180 | 181 | @Override 182 | public NNBaseEntity clone() { 183 | BotGuesser clone = new BotGuesser(false); 184 | clone.ai = this.ai.clone(clone); 185 | return clone; 186 | } 187 | 188 | // Not needed, since the controler is in the same class as the base. 189 | public void setBase(NNBaseEntity t) { 190 | this.base = (BotGuesser) t; 191 | } 192 | 193 | /** 194 | * Adds string B to the hashmap with value true 195 | * 196 | * @param b 197 | */ 198 | public void a(String... b) { 199 | for (String c : b) 200 | ifNameIsValid.put(c, true); 201 | 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/example/logical/LogicalAND.java: -------------------------------------------------------------------------------- 1 | package example.logical; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.concurrent.ThreadLocalRandom; 23 | 24 | import org.bukkit.ChatColor; 25 | import org.bukkit.command.CommandSender; 26 | 27 | import me.zombie_striker.neuralnetwork.*; 28 | import me.zombie_striker.neuralnetwork.neurons.*; 29 | import me.zombie_striker.neuralnetwork.neurons.input.InputBooleanNeuron; 30 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Booleans; 31 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 32 | 33 | public class LogicalAND extends NNBaseEntity implements Controler { 34 | 35 | public Sensory2D_Booleans binary = new Sensory2D_Booleans(1, 2); 36 | 37 | public LogicalAND(boolean createAI) { 38 | this.controler = this; 39 | 40 | if (createAI) { 41 | /** 42 | * If createAI is true, then generate the AI with 3 layers (i.e, 1 43 | * hidden layer), 2 inputs, 3 neurons, and 2 bias neurons. After 44 | * that, connect all the neurons. 45 | * 46 | * If you want to test using random inputs (what should be done, but 47 | * makes replication and understanding a bit hander), add 48 | * randomizeNeurons() after connecting then. 49 | */ 50 | this.ai = NNAI.generateAI(this, 1, 3, "output"); 51 | for (int binaryIndex = 0; binaryIndex < 2; binaryIndex++) { 52 | InputBooleanNeuron.generateNeuronStatically(ai, 0, binaryIndex, 53 | this.binary); 54 | } 55 | 56 | for (int neurons = 0; neurons < 3; neurons++) { 57 | Neuron.generateNeuronStatically(ai, 1); 58 | } 59 | BiasNeuron.generateNeuronStatically(ai, 0); 60 | BiasNeuron.generateNeuronStatically(ai, 1); 61 | 62 | connectNeurons(); 63 | } 64 | } 65 | 66 | 67 | public String learn() { 68 | /** 69 | * Simple explanation of these steps: 70 | * 71 | * 1) If it is currently learning, change the inputs to either true or false. 72 | * 73 | * 2) Let the NN tick and think. This will return the outputs from the OutpuitNeurons 74 | * 75 | * 3) If it is not learning, just return the answer. 76 | * 77 | * 4) Else, do the logic and see if the answer it gave (thought[0]) was correct. 78 | * 79 | * 5) If it was not correct, use the DeepReinforcementUtil to improve it. 80 | * 81 | * 6) After inprovement, return a message with if it was correct, the accuracy, the inputs, and what it thought was the output, 82 | */ 83 | binary.changeValueAt(0, 0, 84 | ThreadLocalRandom.current().nextBoolean()); 85 | binary.changeValueAt(0, 1, 86 | ThreadLocalRandom.current().nextBoolean()); 87 | boolean[] thought = tickAndThink(); 88 | boolean logic = (binary.getBooleanAt(0, 0) && binary.getBooleanAt(0, 1)); 89 | boolean wasCorrect = (logic == thought[0]); 90 | this.getAccuracy().addEntry(wasCorrect); 91 | 92 | // IMPROVE IT 93 | HashMap map = new HashMap<>(); 94 | for (int i = 0; i < thought.length; i++) 95 | map.put(ai.getNeuronFromId(i), logic ? 1.0 : -1.0); 96 | if (!wasCorrect) 97 | DeepReinforcementUtil.instantaneousReinforce(this, map,1); 98 | 99 | return (wasCorrect ? ChatColor.GREEN : ChatColor.RED) + "acc " 100 | + getAccuracy().getAccuracyAsInt() + "|" 101 | + binary.getBooleanAt(0, 0) + " + " + binary.getBooleanAt(0, 1) 102 | + " ~~ " + thought[0]; 103 | 104 | } 105 | 106 | @Override 107 | public String update() { 108 | boolean[] thought = tickAndThink(); 109 | return ("|" + binary.getBooleanAt(0, 0) + " + " 110 | + binary.getBooleanAt(0, 1) + " ~~ " + thought[0]); 111 | } 112 | 113 | @Override 114 | public void setInputs(CommandSender initiator, String[] args) { 115 | if (this.shouldLearn) { 116 | initiator 117 | .sendMessage("Stop the learning before testing. use /nn stoplearning"); 118 | return; 119 | } 120 | if (args.length > 2) { 121 | boolean test = false; 122 | try { 123 | test = Boolean.parseBoolean(args[1]); 124 | } catch (Exception e) { 125 | } 126 | boolean test2 = false; 127 | try { 128 | test2 = Boolean.parseBoolean(args[2]); 129 | } catch (Exception e) { 130 | } 131 | binary.changeValueAt(0, 0, test); 132 | binary.changeValueAt(0, 1, test2); 133 | 134 | } else { 135 | initiator.sendMessage("Provide two values (True or false)"); 136 | } 137 | } 138 | 139 | @Override 140 | public NNBaseEntity clone() { 141 | LogicalAND thi = new LogicalAND(false); 142 | thi.ai = this.ai; 143 | return thi; 144 | } 145 | 146 | @Override 147 | public void setBase(NNBaseEntity t) { 148 | } 149 | 150 | public LogicalAND(Map map) { 151 | super(map); 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /src/example/logical/LogicalInverted.java: -------------------------------------------------------------------------------- 1 | package example.logical; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.concurrent.ThreadLocalRandom; 23 | 24 | import org.bukkit.ChatColor; 25 | import org.bukkit.command.CommandSender; 26 | 27 | import me.zombie_striker.neuralnetwork.*; 28 | import me.zombie_striker.neuralnetwork.neurons.*; 29 | import me.zombie_striker.neuralnetwork.neurons.input.InputBooleanNeuron; 30 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Booleans; 31 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 32 | 33 | public class LogicalInverted extends NNBaseEntity implements Controler { 34 | 35 | public Sensory2D_Booleans binary = new Sensory2D_Booleans(1, 1); 36 | 37 | public LogicalInverted(boolean createAI) { 38 | this.controler = this; 39 | 40 | if (createAI) { 41 | /** 42 | * If createAI is true, then generate the AI with 3 layers (i.e, 1 hidden 43 | * layer), 1 input, 2 neurons, and 1 bias neuron. After that, connect all the 44 | * neurons. 45 | * 46 | * If you want to test using random inputs (what should be done, but makes 47 | * replication and understanding a bit hander), add randomizeNeurons() after 48 | * connecting then. 49 | */ 50 | this.ai = NNAI.generateAI(this, 1, 3, "output"); 51 | for (int binaryIndex = 0; binaryIndex < 1; binaryIndex++) { 52 | InputBooleanNeuron.generateNeuronStatically(ai, 0, binaryIndex, this.binary); 53 | } 54 | 55 | for (int neurons = 0; neurons < 2; neurons++) { 56 | Neuron.generateNeuronStatically(ai, 1); 57 | } 58 | // For some reason, it needs a bias neuron at the bottom in order to work. Look 59 | // into it. 60 | BiasNeuron.generateNeuronStatically(ai, 0); 61 | 62 | connectNeurons(); 63 | } 64 | } 65 | 66 | public String learn() { 67 | /** 68 | * Simple explanation of these steps: 69 | * 70 | * 1) If it is currently learning, change the input to either true or false. 71 | * 72 | * 2) Let the NN tick and think. This will return the outputs from the 73 | * OutpuitNeurons 74 | * 75 | * 3) If it is not learning, just return the answer. 76 | * 77 | * 4) Else, do the logic and see if the answer it gave (thought[0]) was correct. 78 | * 79 | * 5) If it was not correct, use the DeepReinforcementUtil to improve it. 80 | * 81 | * 6) After inprovement, return a message with if it was correct, the accuracy, 82 | * the inputs, and what it thought was the output, 83 | */ 84 | binary.changeValueAt(0, 0, ThreadLocalRandom.current().nextBoolean()); 85 | boolean[] thought = tickAndThink(); 86 | boolean logic = !(binary.getBooleanAt(0, 0)); 87 | boolean result = (logic == thought[0]); 88 | this.getAccuracy().addEntry(result); 89 | 90 | // IMPROVE IT 91 | HashMap map = new HashMap<>(); 92 | for (int i = 0; i < thought.length; i++) 93 | map.put(ai.getNeuronFromId(i), logic ? 1 : -1.0); 94 | if (!result) 95 | DeepReinforcementUtil.instantaneousReinforce(this, map, 1); 96 | return ((result ? ChatColor.GREEN : ChatColor.RED) + "acc " + getAccuracy().getAccuracyAsInt() + "|" 97 | + binary.getBooleanAt(0, 0) + " ~~ " + thought[0]); 98 | } 99 | 100 | @Override 101 | public String update() { 102 | boolean[] thought = tickAndThink(); 103 | return ("|" + binary.getBooleanAt(0, 0) + " ~~ " + thought[0]); 104 | } 105 | 106 | @Override 107 | public void setInputs(CommandSender initiator, String[] args) { 108 | if (this.shouldLearn) { 109 | initiator.sendMessage("Stop the learning before testing. use /nn stoplearning"); 110 | return; 111 | } 112 | if (args.length > 1) { 113 | boolean test = false; 114 | try { 115 | test = Boolean.parseBoolean(args[1]); 116 | } catch (Exception e) { 117 | } 118 | binary.changeValueAt(0, 0, test); 119 | 120 | } else { 121 | initiator.sendMessage("Provide one value (True or false)"); 122 | } 123 | } 124 | 125 | @Override 126 | public NNBaseEntity clone() { 127 | LogicalInverted thi = new LogicalInverted(false); 128 | thi.ai = this.ai; 129 | return thi; 130 | } 131 | 132 | @Override 133 | public void setBase(NNBaseEntity t) { 134 | } 135 | 136 | public LogicalInverted(Map map) { 137 | super(map); 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /src/example/logical/LogicalNAND.java: -------------------------------------------------------------------------------- 1 | package example.logical; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.concurrent.ThreadLocalRandom; 23 | 24 | import org.bukkit.ChatColor; 25 | import org.bukkit.command.CommandSender; 26 | 27 | import me.zombie_striker.neuralnetwork.*; 28 | import me.zombie_striker.neuralnetwork.neurons.*; 29 | import me.zombie_striker.neuralnetwork.neurons.input.InputBooleanNeuron; 30 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Booleans; 31 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 32 | 33 | public class LogicalNAND extends NNBaseEntity implements Controler { 34 | 35 | public Sensory2D_Booleans binary = new Sensory2D_Booleans(1, 2); 36 | 37 | public LogicalNAND(boolean createAI) { 38 | this.controler = this; 39 | 40 | if (createAI) { 41 | /** 42 | * If createAI is true, then generate the AI with 3 layers (i.e, 1 43 | * hidden layer), 2 inputs, 3 neurons, and 2 bias neurons. After 44 | * that, connect all the neurons. 45 | * 46 | * If you want to test using random inputs (what should be done, but 47 | * makes replication and understanding a bit hander), add 48 | * randomizeNeurons() after connecting then. 49 | */ 50 | this.ai = NNAI.generateAI(this, 1, 3, "output"); 51 | for (int binaryIndex = 0; binaryIndex < 2; binaryIndex++) { 52 | InputBooleanNeuron.generateNeuronStatically(ai, 0, binaryIndex, 53 | this.binary); 54 | } 55 | 56 | for (int neurons = 0; neurons < 3; neurons++) { 57 | Neuron.generateNeuronStatically(ai, 1); 58 | } 59 | BiasNeuron.generateNeuronStatically(ai, 0); 60 | BiasNeuron.generateNeuronStatically(ai, 1); 61 | 62 | connectNeurons(); 63 | } 64 | } 65 | 66 | 67 | public String learn() { 68 | /** 69 | * Simple explanation of these steps: 70 | * 71 | * 1) If it is currently learning, change the inputs to either true or false. 72 | * 73 | * 2) Let the NN tick and think. This will return the outputs from the OutpuitNeurons 74 | * 75 | * 3) If it is not learning, just return the answer. 76 | * 77 | * 4) Else, do the logic and see if the answer it gave (thought[0]) was correct. 78 | * 79 | * 5) If it was not correct, use the DeepReinforcementUtil to improve it. 80 | * 81 | * 6) After inprovement, return a message with if it was correct, the accuracy, the inputs, and what it thought was the output, 82 | */ 83 | binary.changeValueAt(0, 0, 84 | ThreadLocalRandom.current().nextBoolean()); 85 | binary.changeValueAt(0, 1, 86 | ThreadLocalRandom.current().nextBoolean()); 87 | boolean[] thought = tickAndThink(); 88 | boolean logic = !(binary.getBooleanAt(0, 0)&& binary.getBooleanAt(0, 1)); 89 | boolean wasCorrect = (logic == thought[0]); 90 | this.getAccuracy().addEntry(wasCorrect); 91 | 92 | // IMPROVE IT 93 | HashMap map = new HashMap<>(); 94 | for (int i = 0; i < thought.length; i++) 95 | map.put(ai.getNeuronFromId(i), logic ? 1.0 : -1.0); 96 | if (!wasCorrect) 97 | DeepReinforcementUtil.instantaneousReinforce(this, map,1); 98 | 99 | return (wasCorrect ? ChatColor.GREEN : ChatColor.RED) + "acc " 100 | + getAccuracy().getAccuracyAsInt() + "|" 101 | + binary.getBooleanAt(0, 0) + " + " + binary.getBooleanAt(0, 1) 102 | + " ~~ " + thought[0]; 103 | 104 | } 105 | 106 | @Override 107 | public String update() { 108 | boolean[] thought = tickAndThink(); 109 | return ("|" + binary.getBooleanAt(0, 0) + " + " 110 | + binary.getBooleanAt(0, 1) + " ~~ " + thought[0]); 111 | } 112 | 113 | @Override 114 | public void setInputs(CommandSender initiator, String[] args) { 115 | if (this.shouldLearn) { 116 | initiator 117 | .sendMessage("Stop the learning before testing. use /nn stoplearning"); 118 | return; 119 | } 120 | if (args.length > 2) { 121 | boolean test = false; 122 | try { 123 | test = Boolean.parseBoolean(args[1]); 124 | } catch (Exception e) { 125 | } 126 | boolean test2 = false; 127 | try { 128 | test2 = Boolean.parseBoolean(args[2]); 129 | } catch (Exception e) { 130 | } 131 | binary.changeValueAt(0, 0, test); 132 | binary.changeValueAt(0, 1, test2); 133 | 134 | } else { 135 | initiator.sendMessage("Provide two values (True or false)"); 136 | } 137 | } 138 | 139 | @Override 140 | public NNBaseEntity clone() { 141 | LogicalNAND thi = new LogicalNAND(false); 142 | thi.ai = this.ai; 143 | return thi; 144 | } 145 | 146 | @Override 147 | public void setBase(NNBaseEntity t) { 148 | } 149 | 150 | public LogicalNAND(Map map) { 151 | super(map); 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /src/example/logical/LogicalNOR.java: -------------------------------------------------------------------------------- 1 | package example.logical; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.concurrent.ThreadLocalRandom; 23 | 24 | import org.bukkit.ChatColor; 25 | import org.bukkit.command.CommandSender; 26 | 27 | import me.zombie_striker.neuralnetwork.*; 28 | import me.zombie_striker.neuralnetwork.neurons.*; 29 | import me.zombie_striker.neuralnetwork.neurons.input.InputBooleanNeuron; 30 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Booleans; 31 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 32 | 33 | public class LogicalNOR extends NNBaseEntity implements Controler { 34 | 35 | public Sensory2D_Booleans binary = new Sensory2D_Booleans(1, 2); 36 | 37 | public LogicalNOR(boolean createAI) { 38 | this.controler = this; 39 | 40 | if (createAI) { 41 | /** 42 | * If createAI is true, then generate the AI with 3 layers (i.e, 1 43 | * hidden layer), 2 inputs, 3 neurons, and 2 bias neurons. After 44 | * that, connect all the neurons. 45 | * 46 | * If you want to test using random inputs (what should be done, but 47 | * makes replication and understanding a bit hander), add 48 | * randomizeNeurons() after connecting then. 49 | */ 50 | this.ai = NNAI.generateAI(this, 1, 3, "output"); 51 | for (int binaryIndex = 0; binaryIndex < 2; binaryIndex++) { 52 | InputBooleanNeuron.generateNeuronStatically(ai, 0, binaryIndex, 53 | this.binary); 54 | } 55 | for (int neurons = 0; neurons < 3; neurons++) { 56 | Neuron.generateNeuronStatically(ai, 1); 57 | } 58 | BiasNeuron.generateNeuronStatically(ai, 0); 59 | BiasNeuron.generateNeuronStatically(ai, 1); 60 | 61 | connectNeurons(); 62 | } 63 | } 64 | 65 | public String learn() { 66 | /** 67 | * Simple explanation of these steps: 68 | * 69 | * 1) If it is currently learning, change the inputs to either true or false. 70 | * 71 | * 2) Let the NN tick and think. This will return the outputs from the OutpuitNeurons 72 | * 73 | * 3) If it is not learning, just return the answer. 74 | * 75 | * 4) Else, do the logic and see if the answer it gave (thought[0]) was correct. 76 | * 77 | * 5) If it was not correct, use the DeepReinforcementUtil to improve it. 78 | * 79 | * 6) After inprovement, return a message with if it was correct, the accuracy, the inputs, and what it thought was the output, 80 | */ 81 | binary.changeValueAt(0, 0, 82 | ThreadLocalRandom.current().nextBoolean()); 83 | binary.changeValueAt(0, 1, 84 | ThreadLocalRandom.current().nextBoolean()); 85 | boolean[] thought = tickAndThink(); 86 | boolean logic = !(binary.getBooleanAt(0, 0) || binary.getBooleanAt(0, 1)); 87 | boolean wasCorrect = (logic == thought[0]); 88 | this.getAccuracy().addEntry(wasCorrect); 89 | 90 | // IMPROVE IT 91 | HashMap map = new HashMap<>(); 92 | for (int i = 0; i < thought.length; i++) 93 | map.put(ai.getNeuronFromId(i), logic ? 1.0 : -1.0); 94 | if (!wasCorrect) 95 | DeepReinforcementUtil.instantaneousReinforce(this, map,1); 96 | 97 | return (wasCorrect ? ChatColor.GREEN : ChatColor.RED) + "acc " 98 | + getAccuracy().getAccuracyAsInt() + "|" 99 | + binary.getBooleanAt(0, 0) + " + " + binary.getBooleanAt(0, 1) 100 | + " ~~ " + thought[0]; 101 | 102 | } 103 | 104 | @Override 105 | public String update() { 106 | boolean[] thought = tickAndThink(); 107 | return ("|" + binary.getBooleanAt(0, 0) + " + " 108 | + binary.getBooleanAt(0, 1) + " ~~ " + thought[0]); 109 | } 110 | 111 | @Override 112 | public void setInputs(CommandSender initiator, String[] args) { 113 | if (this.shouldLearn) { 114 | initiator 115 | .sendMessage("Stop the learning before testing. use /nn stoplearning"); 116 | return; 117 | } 118 | if (args.length > 2) { 119 | boolean test = false; 120 | try { 121 | test = Boolean.parseBoolean(args[1]); 122 | } catch (Exception e) { 123 | } 124 | boolean test2 = false; 125 | try { 126 | test2 = Boolean.parseBoolean(args[2]); 127 | } catch (Exception e) { 128 | } 129 | binary.changeValueAt(0, 0, test); 130 | binary.changeValueAt(0, 1, test2); 131 | 132 | } else { 133 | initiator.sendMessage("Provide two values (True or false)"); 134 | } 135 | } 136 | 137 | @Override 138 | public NNBaseEntity clone() { 139 | LogicalNOR thi = new LogicalNOR(false); 140 | thi.ai = this.ai; 141 | return thi; 142 | } 143 | 144 | @Override 145 | public void setBase(NNBaseEntity base) { 146 | } 147 | public LogicalNOR(Map map) { 148 | super(map); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/example/logical/LogicalOR.java: -------------------------------------------------------------------------------- 1 | package example.logical; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.concurrent.ThreadLocalRandom; 23 | 24 | import org.bukkit.ChatColor; 25 | import org.bukkit.command.CommandSender; 26 | 27 | import me.zombie_striker.neuralnetwork.*; 28 | import me.zombie_striker.neuralnetwork.neurons.*; 29 | import me.zombie_striker.neuralnetwork.neurons.input.InputBooleanNeuron; 30 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Booleans; 31 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 32 | 33 | public class LogicalOR extends NNBaseEntity implements Controler { 34 | 35 | public Sensory2D_Booleans binary = new Sensory2D_Booleans(1, 2); 36 | 37 | public LogicalOR(boolean createAI) { 38 | this.controler = this; 39 | 40 | if (createAI) { 41 | /** 42 | * If createAI is true, then generate the AI with 3 layers (i.e, 1 43 | * hidden layer), 2 inputs, 3 neurons, and 2 bias neurons. After 44 | * that, connect all the neurons. 45 | * 46 | * If you want to test using random inputs (what should be done, but 47 | * makes replication and understanding a bit hander), add 48 | * randomizeNeurons() after connecting then. 49 | */ 50 | this.ai = NNAI.generateAI(this, 1, 3, "output"); 51 | for (int binaryIndex = 0; binaryIndex < 2; binaryIndex++) { 52 | InputBooleanNeuron.generateNeuronStatically(ai, 0, binaryIndex, 53 | this.binary); 54 | } 55 | for (int neurons = 0; neurons < 3; neurons++) { 56 | Neuron.generateNeuronStatically(ai, 1); 57 | } 58 | BiasNeuron.generateNeuronStatically(ai, 0); 59 | BiasNeuron.generateNeuronStatically(ai, 1); 60 | 61 | connectNeurons(); 62 | } 63 | } 64 | 65 | 66 | public String learn() { 67 | /** 68 | * Simple explanation of these steps: 69 | * 70 | * 1) If it is currently learning, change the inputs to either true or false. 71 | * 72 | * 2) Let the NN tick and think. This will return the outputs from the OutpuitNeurons 73 | * 74 | * 3) If it is not learning, just return the answer. 75 | * 76 | * 4) Else, do the logic and see if the answer it gave (thought[0]) was correct. 77 | * 78 | * 5) If it was not correct, use the DeepReinforcementUtil to improve it. 79 | * 80 | * 6) After inprovement, return a message with if it was correct, the accuracy, the inputs, and what it thought was the output, 81 | */ 82 | binary.changeValueAt(0, 0, 83 | ThreadLocalRandom.current().nextBoolean()); 84 | binary.changeValueAt(0, 1, 85 | ThreadLocalRandom.current().nextBoolean()); 86 | boolean[] thought = tickAndThink(); 87 | boolean logic = (binary.getBooleanAt(0, 0) || binary.getBooleanAt(0, 1)); 88 | boolean wasCorrect = (logic == thought[0]); 89 | this.getAccuracy().addEntry(wasCorrect); 90 | 91 | // IMPROVE IT 92 | HashMap map = new HashMap<>(); 93 | for (int i = 0; i < thought.length; i++) 94 | map.put(ai.getNeuronFromId(i), logic ? 1.0 : -1.0); 95 | if (!wasCorrect) 96 | DeepReinforcementUtil.instantaneousReinforce(this, map,1); 97 | 98 | return (wasCorrect ? ChatColor.GREEN : ChatColor.RED) + "acc " 99 | + getAccuracy().getAccuracyAsInt() + "|" 100 | + binary.getBooleanAt(0, 0) + " + " + binary.getBooleanAt(0, 1) 101 | + " ~~ " + thought[0]; 102 | 103 | } 104 | 105 | @Override 106 | public String update() { 107 | boolean[] thought = tickAndThink(); 108 | return ("|" + binary.getBooleanAt(0, 0) + " + " 109 | + binary.getBooleanAt(0, 1) + " ~~ " + thought[0]); 110 | } 111 | 112 | @Override 113 | public void setInputs(CommandSender initiator, String[] args) { 114 | if (this.shouldLearn) { 115 | initiator 116 | .sendMessage("Stop the learning before testing. use /nn stoplearning"); 117 | return; 118 | } 119 | if (args.length > 2) { 120 | boolean test = false; 121 | try { 122 | test = Boolean.parseBoolean(args[1]); 123 | } catch (Exception e) { 124 | } 125 | boolean test2 = false; 126 | try { 127 | test2 = Boolean.parseBoolean(args[2]); 128 | } catch (Exception e) { 129 | } 130 | binary.changeValueAt(0, 0, test); 131 | binary.changeValueAt(0, 1, test2); 132 | 133 | } else { 134 | initiator.sendMessage("Provide two values (True or false)"); 135 | } 136 | } 137 | 138 | @Override 139 | public NNBaseEntity clone() { 140 | LogicalOR thi = new LogicalOR(false); 141 | thi.ai = this.ai; 142 | return thi; 143 | } 144 | 145 | @Override 146 | public void setBase(NNBaseEntity base) { 147 | } 148 | public LogicalOR(Map map) { 149 | super(map); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/example/logical/LogicalXNOR.java: -------------------------------------------------------------------------------- 1 | package example.logical; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.concurrent.ThreadLocalRandom; 23 | 24 | import org.bukkit.ChatColor; 25 | import org.bukkit.command.CommandSender; 26 | 27 | import me.zombie_striker.neuralnetwork.*; 28 | import me.zombie_striker.neuralnetwork.neurons.*; 29 | import me.zombie_striker.neuralnetwork.neurons.input.InputBooleanNeuron; 30 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Booleans; 31 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 32 | 33 | public class LogicalXNOR extends NNBaseEntity implements Controler { 34 | 35 | public Sensory2D_Booleans binary = new Sensory2D_Booleans(1, 2); 36 | 37 | public LogicalXNOR(boolean createAI) { 38 | this.controler = this; 39 | 40 | if (createAI) { 41 | /** 42 | * If createAI is true, then generate the AI with 3 layers (i.e, 1 hidden 43 | * layer), 2 inputs, 3 neurons, and 2 bias neurons. After that, connect all the 44 | * neurons. 45 | * 46 | * If you want to test using random inputs (what should be done, but makes 47 | * replication and understanding a bit hander), add randomizeNeurons() after 48 | * connecting then. 49 | */ 50 | this.ai = NNAI.generateAI(this, 1, 3, "output"); 51 | for (int binaryIndex = 0; binaryIndex < 2; binaryIndex++) { 52 | InputBooleanNeuron.generateNeuronStatically(ai, 0, binaryIndex, this.binary); 53 | } 54 | 55 | // Creates the neurons for layer 1. 56 | for (int neurons = 0; neurons < 3; neurons++) { 57 | Neuron.generateNeuronStatically(ai, 1); 58 | } 59 | // BiasNeuron.generateNeuronStatically(ai, 0); 60 | // BiasNeuron.generateNeuronStatically(ai, 1); 61 | connectNeurons(); 62 | } 63 | } 64 | 65 | public String learn() { 66 | 67 | /** 68 | * Simple explanation of these steps: 69 | * 70 | * 1) If it is currently learning, change the inputs to either true or false. 71 | * 72 | * 2) Let the NN tick and think. This will return the outputs from the 73 | * OutpuitNeurons 74 | * 75 | * 3) If it is not learning, just return the answer. 76 | * 77 | * 4) Else, do the logic and see if the answer it gave (thought[0]) was correct. 78 | * 79 | * 5) If it was not correct, use the DeepReinforcementUtil to improve it. 80 | * 81 | * 6) After inprovement, return a message with if it was correct, the accuracy, 82 | * the inputs, and what it thought was the output, 83 | */ 84 | binary.changeValueAt(0, 0, ThreadLocalRandom.current().nextBoolean()); 85 | binary.changeValueAt(0, 1, ThreadLocalRandom.current().nextBoolean()); 86 | boolean[] thought = tickAndThink(); 87 | boolean logic = (binary.getBooleanAt(0, 0) == binary.getBooleanAt(0, 1)); 88 | boolean result = logic == thought[0]; 89 | this.getAccuracy().addEntry(result); 90 | 91 | // IMPROVE IT 92 | HashMap map = new HashMap<>(); 93 | for (int i = 0; i < thought.length; i++) 94 | map.put(ai.getNeuronFromId(i), logic ? 1 : -1.0); 95 | if (!result) 96 | DeepReinforcementUtil.instantaneousReinforce(this, map, 1); 97 | return ((result ? ChatColor.GREEN : ChatColor.RED) + "acc " + getAccuracy().getAccuracyAsInt() + "|" 98 | + binary.getBooleanAt(0, 0) + " + " + binary.getBooleanAt(0, 1) + " ~~ " + thought[0]); 99 | 100 | } 101 | 102 | @Override 103 | public String update() { 104 | 105 | boolean[] thought = tickAndThink(); 106 | 107 | return ("|" + binary.getBooleanAt(0, 0) + " + " + binary.getBooleanAt(0, 1) + " ~~ " + thought[0]); 108 | } 109 | 110 | @Override 111 | public void setInputs(CommandSender initiator, String[] args) { 112 | if (this.shouldLearn) { 113 | initiator.sendMessage("Stop the learning before testing. use /nn stoplearning"); 114 | return; 115 | } 116 | if (args.length > 2) { 117 | boolean test = false; 118 | try { 119 | test = Boolean.parseBoolean(args[1]); 120 | } catch (Exception e) { 121 | } 122 | boolean test2 = false; 123 | try { 124 | test2 = Boolean.parseBoolean(args[2]); 125 | } catch (Exception e) { 126 | } 127 | binary.changeValueAt(0, 0, test); 128 | binary.changeValueAt(0, 1, test2); 129 | 130 | } else { 131 | initiator.sendMessage("Provide two values (True or false)"); 132 | } 133 | } 134 | 135 | @Override 136 | public NNBaseEntity clone() { 137 | LogicalXNOR thi = new LogicalXNOR(false); 138 | thi.ai = this.ai; 139 | return thi; 140 | } 141 | 142 | @Override 143 | public void setBase(NNBaseEntity base) { 144 | } 145 | 146 | public LogicalXNOR(Map map) { 147 | super(map); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/example/logical/LogicalXOR.java: -------------------------------------------------------------------------------- 1 | package example.logical; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.concurrent.ThreadLocalRandom; 23 | 24 | import org.bukkit.ChatColor; 25 | import org.bukkit.command.CommandSender; 26 | 27 | import me.zombie_striker.neuralnetwork.*; 28 | import me.zombie_striker.neuralnetwork.neurons.*; 29 | import me.zombie_striker.neuralnetwork.neurons.input.InputBooleanNeuron; 30 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Booleans; 31 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 32 | 33 | public class LogicalXOR extends NNBaseEntity implements Controler { 34 | 35 | public Sensory2D_Booleans binary = new Sensory2D_Booleans(1, 2); 36 | 37 | public LogicalXOR(boolean createAI) { 38 | this.controler = this; 39 | 40 | if (createAI) { 41 | /** 42 | * If createAI is true, then generate the AI with 3 layers (i.e, 1 43 | * hidden layer), 2 inputs, 5 neurons, and 2 bias neurons. After 44 | * that, connect all the neurons. 45 | * 46 | * If you want to test using random inputs (what should be done, but 47 | * makes replication and understanding a bit hander), add 48 | * randomizeNeurons() after connecting then. 49 | */ 50 | this.ai = NNAI.generateAI(this, 1, 3, "output"); 51 | for (int binaryIndex = 0; binaryIndex < 2; binaryIndex++) { 52 | InputBooleanNeuron.generateNeuronStatically(ai, 0, binaryIndex, 53 | this.binary); 54 | } 55 | 56 | for (int neurons = 0; neurons < 5; neurons++) { 57 | Neuron.generateNeuronStatically(ai, 1); 58 | } 59 | BiasNeuron.generateNeuronStatically(ai, 0); 60 | BiasNeuron.generateNeuronStatically(ai, 1); 61 | 62 | connectNeurons(); 63 | } 64 | } 65 | 66 | public String learn() { 67 | /** 68 | * Simple explanation of these steps: 69 | * 70 | * 1) If it is currently learning, change the inputs to either true or false. 71 | * 72 | * 2) Let the NN tick and think. This will return the outputs from the OutpuitNeurons 73 | * 74 | * 3) If it is not learning, just return the answer. 75 | * 76 | * 4) Else, do the logic and see if the answer it gave (thought[0]) was correct. 77 | * 78 | * 5) If it was not correct, use the DeepReinforcementUtil to improve it. 79 | * 80 | * 6) After inprovement, return a message with if it was correct, the accuracy, the inputs, and what it thought was the output, 81 | */ 82 | binary.changeValueAt(0, 0, 83 | ThreadLocalRandom.current().nextBoolean()); 84 | binary.changeValueAt(0, 1, 85 | ThreadLocalRandom.current().nextBoolean()); 86 | boolean[] thought = tickAndThink(); 87 | boolean logic = (binary.getBooleanAt(0, 0) != binary.getBooleanAt(0, 1)); 88 | boolean wasCorrect = (logic == thought[0]); 89 | this.getAccuracy().addEntry(wasCorrect); 90 | 91 | // IMPROVE IT 92 | HashMap map = new HashMap<>(); 93 | for (int i = 0; i < thought.length; i++) 94 | map.put(ai.getNeuronFromId(i), logic ? 1.0 : -1.0); 95 | if (!wasCorrect) 96 | DeepReinforcementUtil.instantaneousReinforce(this, map,1); 97 | 98 | return (wasCorrect ? ChatColor.GREEN : ChatColor.RED) + "acc " 99 | + getAccuracy().getAccuracyAsInt() + "|" 100 | + binary.getBooleanAt(0, 0) + " + " + binary.getBooleanAt(0, 1) 101 | + " ~~ " + thought[0]; 102 | 103 | } 104 | 105 | @Override 106 | public String update() { 107 | boolean[] thought = tickAndThink(); 108 | return ("|" + binary.getBooleanAt(0, 0) + " + " 109 | + binary.getBooleanAt(0, 1) + " ~~ " + thought[0]); 110 | } 111 | 112 | @Override 113 | public void setInputs(CommandSender initiator, String[] args) { 114 | if (this.shouldLearn) { 115 | initiator 116 | .sendMessage("Stop the learning before testing. use /nn stoplearning"); 117 | return; 118 | } 119 | if (args.length > 2) { 120 | boolean test = false; 121 | try { 122 | test = Boolean.parseBoolean(args[1]); 123 | } catch (Exception e) { 124 | } 125 | boolean test2 = false; 126 | try { 127 | test2 = Boolean.parseBoolean(args[2]); 128 | } catch (Exception e) { 129 | } 130 | binary.changeValueAt(0, 0, test); 131 | binary.changeValueAt(0, 1, test2); 132 | 133 | } else { 134 | initiator.sendMessage("Provide two values (True or false)"); 135 | } 136 | } 137 | 138 | @Override 139 | public NNBaseEntity clone() { 140 | LogicalXOR thi = new LogicalXOR(false); 141 | thi.ai = this.ai; 142 | return thi; 143 | } 144 | 145 | @Override 146 | public void setBase(NNBaseEntity t) { 147 | } 148 | 149 | public LogicalXOR(Map map) { 150 | super(map); 151 | } 152 | 153 | } 154 | -------------------------------------------------------------------------------- /src/example/music_bot/MusicBot.java: -------------------------------------------------------------------------------- 1 | package example.music_bot; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.*; 21 | 22 | import org.bukkit.*; 23 | import org.bukkit.block.NoteBlock; 24 | import org.bukkit.command.CommandSender; 25 | import org.bukkit.entity.Player; 26 | import org.bukkit.scheduler.BukkitRunnable; 27 | 28 | import me.zombie_striker.neuralnetwork.*; 29 | import me.zombie_striker.neuralnetwork.neurons.*; 30 | import me.zombie_striker.neuralnetwork.neurons.input.*; 31 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Numbers; 32 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 33 | import me.zombie_striker.nnmain.Main; 34 | 35 | public class MusicBot extends NNBaseEntity implements Controler { 36 | 37 | /** 38 | * I have not actually updated this class, as this was one of the first bots 39 | * I made and there is a lot of improvements that could be made. I'll update 40 | * it later (maybe). 41 | * 42 | * For now, do not use this as an example of how a NN should be made/used. 43 | */ 44 | 45 | public Sensory2D_Numbers numbers = new Sensory2D_Numbers(10, 90); 46 | 47 | public static final int PITCHES = 24; 48 | 49 | // public boolean wasCorrect = true; 50 | // Different than should learn. This erases the inputs so the trained 51 | // outputs are not what it is starting off of 52 | public boolean wasLearning = false; 53 | 54 | public double[][] trainingValues; 55 | int training_step = 0; 56 | 57 | public MusicBot base; 58 | 59 | public MusicBot(boolean createAI) { 60 | super(false); 61 | addMusicTrainingData(this); 62 | if (createAI) { 63 | // Creates a new AI with (Pitches) amount of output neurons and with 64 | // three layers (which includes the input and output layers). 65 | this.ai = NNAI.generateAI(this, PITCHES, 3); 66 | numbers.changeMatrix(new double[PITCHES][90]); 67 | 68 | // Creates input number neurons for the Pitches (rows) and the 69 | // memory (columns) 70 | for (int rows = 0; rows < numbers.getMatrix().length; rows++) { 71 | for (int col1 = 0; col1 < numbers.getMatrix()[0].length; col1++) { 72 | InputNumberNeuron.generateNeuronStatically(ai, rows, col1, 73 | numbers); 74 | } 75 | } 76 | 77 | // Generates neurons for layer 1. 78 | for (int neurons = 0; neurons < 38; neurons++) { 79 | Neuron.generateNeuronStatically(ai, 1); 80 | } 81 | 82 | // Generate 10 tick rates, hopefully one of them will help with the 83 | // rhythm. 84 | for (int tickrate = 1; tickrate <= 10; tickrate++) 85 | InputTickNeuron.generateNeuronStatically(ai, tickrate); 86 | 87 | // Generate a bia neuron for each layer. 88 | BiasNeuron.generateNeuronStatically(ai, 0); 89 | BiasNeuron.generateNeuronStatically(ai, 1); 90 | 91 | connectNeurons(); 92 | } 93 | this.controler = this; 94 | } 95 | 96 | // TODO: This is used for denoting pitch. All conversions from decimal to 97 | // whole number should use this value. 98 | 99 | public String learn() { 100 | 101 | // This takes the training data (the music sheet), increments the 102 | // training step tick, and updates the sensors to the notes. 103 | int highestlength = 0; 104 | for (int i = 0; i < trainingValues.length; i++) { 105 | if (highestlength < trainingValues[i].length) { 106 | highestlength = trainingValues[i].length; 107 | } 108 | } 109 | training_step = (training_step + 1); 110 | if (training_step >= highestlength) { 111 | base.ai.setCurrentTick(0); 112 | training_step = 0; 113 | } 114 | double[][] values = new double[base.numbers.getMatrix().length][base.numbers 115 | .getMatrix()[0].length]; 116 | for (int row = 0; row < values.length; row++) { // Pitchstamp 117 | for (int col = 0; col < values[row].length; col++) { // Timestamp 118 | for (int channels = 0; channels < trainingValues.length; channels++) 119 | if ((training_step - values[row].length + col >= 0) 120 | && (trainingValues[channels].length > training_step 121 | - values[row].length + col && (training_step 122 | - values[row].length + col >= 0 && (trainingValues[channels][training_step 123 | - values[row].length + col] * PITCHES) == row))) { 124 | values[row][col] = 1; 125 | } 126 | } 127 | } 128 | base.numbers.changeMatrix(values); 129 | 130 | 131 | boolean[] actions = base.tickAndThink(); 132 | wasLearning = true; 133 | 134 | // Loops through all the outputs. If the output was correct, set the 135 | // desired value to 1. If not, set it to -1. 136 | HashMap desiredTriggerStrengths = new HashMap<>(); 137 | for (int i = 0; i < actions.length; i++) { 138 | boolean wasCorrect = false; 139 | for (int channel = 0; channel < trainingValues.length; channel++) { 140 | if (training_step < trainingValues[channel].length) 141 | if (wasCorrect = (i == (int) (trainingValues[channel][training_step] * PITCHES))) 142 | break; 143 | } 144 | desiredTriggerStrengths.put(base.ai.getNeuronFromId(i), 145 | (wasCorrect ? 1 : -1.0)); 146 | } 147 | 148 | // This determines if the output is equal to the training data. 149 | boolean playedRightNotes = true; 150 | for (int i = 0; i < actions.length; i++) { 151 | boolean wasToldToBeTrue = false; 152 | 153 | for (int channel = 0; channel < trainingValues.length; channel++) { 154 | if (training_step < trainingValues[channel].length) { 155 | if ((int) (trainingValues[channel][training_step] * PITCHES) == i) { 156 | wasToldToBeTrue = true; 157 | break; 158 | } 159 | } 160 | } 161 | if (wasToldToBeTrue != actions[i]) { 162 | playedRightNotes = false; 163 | break; 164 | } 165 | } 166 | 167 | // Adds weather the notes were played correctly to the accuracy 168 | // list. 169 | this.getAccuracy().addEntry(playedRightNotes); 170 | int total_accuracy = this.getAccuracy().getAccuracyAsInt(); 171 | 172 | // Make corrections so outputs are what they should be. If it made a 173 | // mistake, do this three times. 174 | DeepReinforcementUtil.instantaneousReinforce(base, 175 | desiredTriggerStrengths, ((playedRightNotes) ? 1 : 3)); 176 | 177 | // Logger: Print out all the triggered neurons. If the output was 178 | // correct, the message will be green. 179 | StringBuilder activeNeurons = new StringBuilder(); 180 | for (Neuron omn : base.ai.getOutputNeurons()) { 181 | if (omn.isTriggered()) 182 | activeNeurons.append(omn.getID() + ", "); 183 | } 184 | return (((playedRightNotes) ? ChatColor.GREEN : ChatColor.RED) + "" 185 | + total_accuracy + "% : Active neurons = " + activeNeurons 186 | .toString()); 187 | } 188 | 189 | 190 | @Override 191 | public String update() { 192 | boolean[] actions = base.tickAndThink(); 193 | 194 | if (wasLearning) { 195 | base.ai.setCurrentTick(0); 196 | wasLearning = false; 197 | } 198 | // Clears all the sensors if it was training the previous tick 199 | 200 | // Moves all the notes back 201 | // TODO: Change code so that it moves the notes back by 1 in the ROW 202 | // direction, not the COL direction 203 | double[][] previousNotes = base.numbers.getMatrix(); 204 | for (int row = 0; row < previousNotes.length; row++) { 205 | for (int col = 1; col < previousNotes[row].length; col++) { 206 | previousNotes[row][col - 1] = previousNotes[row][col]; 207 | } 208 | } 209 | 210 | // If the output neuron was triggered, add the neuron to the matrix. 211 | for (Neuron n : base.ai.getOutputNeurons()) { 212 | previousNotes[n.getID()][previousNotes[n.getID()].length - 1] = n 213 | .isTriggered() ? n.getTriggeredStength() : 0; 214 | } 215 | base.numbers.changeMatrix(previousNotes); 216 | return null; 217 | } 218 | 219 | @Override 220 | public void setInputs(CommandSender initiator, String[] args) { 221 | // 222 | final Player player = (Player) initiator; 223 | final int ticksMax = (args.length > 1) ? Integer.parseInt(args[1]) : 20; 224 | 225 | final Location base = player.getLocation().clone(); 226 | 227 | final int channels = this.trainingValues.length; 228 | 229 | for (int i = 0; i < channels; i++) { 230 | base.clone().add(i, 0, 0).getBlock().setType(Material.NOTE_BLOCK); 231 | } 232 | new BukkitRunnable() { 233 | int tick = 0; 234 | 235 | @SuppressWarnings("deprecation") 236 | @Override 237 | public void run() { 238 | tick++; 239 | int row = 0; 240 | for (Neuron n : ai.getOutputNeurons()) { 241 | if (n.isTriggered()) { 242 | ((NoteBlock) base.clone().add(row, 0, 0).getBlock() 243 | .getState()).setRawNote((byte) n.getID()); 244 | ((NoteBlock) base.clone().add(row, 0, 0).getBlock() 245 | .getState()).play(); 246 | row++; 247 | 248 | } 249 | } 250 | 251 | if (tick > ticksMax) 252 | cancel(); 253 | } 254 | }.runTaskTimer(Main.getMainClass(), 30, 9); 255 | 256 | } 257 | 258 | public double[] convertToDoubles(String pitches) { 259 | List values = new ArrayList<>(); 260 | // int offset =0; 261 | for (int index = 0; index < pitches.length(); index++) { 262 | char c = pitches.charAt(index); 263 | if (c == '.') { 264 | // offset++; 265 | continue; 266 | } 267 | double d = c == ' ' ? -1 268 | : c == 'a' ? 10 269 | : c == 'b' ? 11 270 | : c == 'c' ? 12 271 | : c == 'd' ? 13 272 | : c == 'e' ? 14 273 | : c == 'f' ? 15 274 | : c == 'g' ? 16 275 | : c == 'h' ? 17 276 | : c == 'i' ? 18 277 | : c == 'j' ? 19 278 | : c == 'k' ? 20 279 | : c == 'l' ? 21 280 | : c == 'm' ? 22 281 | : c == 'n' ? 23 282 | : c == '0' ? 24 283 | : Double.parseDouble("" 284 | + c); 285 | values.add(d / PITCHES); 286 | } 287 | double[] array = new double[values.size()]; 288 | for (int i = 0; i < array.length; i++) 289 | array[i] = values.get(i); 290 | return array; 291 | } 292 | 293 | private void addMusicTrainingData(NNBaseEntity base) { 294 | 295 | // TODO: Move this into the NNMusicBot class. 296 | 297 | /** 298 | * Each section, the two values are on the same line. Each one is a 1/2 299 | * higher than the last. 0 1 2 3 4 - In the top line of the bottom row 5 300 | * 6 6 7-- Now on the top section, not touching the bottom line 8 9 10 - 301 | * In the bottom line of the top row 11 12 13 14 15 16 17 18 19 20 21 22 302 | * 23 24 -- IN the top line of the top row. 303 | */ 304 | 305 | /** 306 | * Every 8 characters last for 3 seconds. That means 307 | */ 308 | // TODO: Moonlight Sonata 309 | // https://www.8notes.com/scores/1754.asp 310 | double[][] song = { 311 | convertToDoubles("68a68a68a68a.68a68a68a68a.68a68a68b68b.68b68a689688.11568a68ad d.68b68b68b68bd.68a68a68b68b.68b68b68a68a.68a68a68a68a."), 312 | convertToDoubles("1 .1 .1 .1 .1 68a .1 d .1 1 .1 1 h .a ."), 313 | convertToDoubles("1 .1 .1 .1 .1 .f .f f .f f .0 .") }; 314 | 315 | this.setTrainingSong(song); 316 | } 317 | 318 | @Override 319 | public NNBaseEntity clone() { 320 | MusicBot thi = new MusicBot(false); 321 | thi.ai = this.ai; 322 | return thi; 323 | } 324 | 325 | public void setBase(NNBaseEntity t) { 326 | this.base = (MusicBot) t; 327 | } 328 | 329 | public void setTrainingSong(double[][] data) { 330 | this.trainingValues = data; 331 | } 332 | } 333 | -------------------------------------------------------------------------------- /src/example/number_adder/NumberAdder.java: -------------------------------------------------------------------------------- 1 | package example.number_adder; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | 22 | import org.bukkit.Bukkit; 23 | import org.bukkit.ChatColor; 24 | import org.bukkit.command.CommandSender; 25 | 26 | import me.zombie_striker.neuralnetwork.*; 27 | import me.zombie_striker.neuralnetwork.neurons.*; 28 | import me.zombie_striker.neuralnetwork.neurons.input.InputBooleanNeuron; 29 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Booleans; 30 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 31 | 32 | public class NumberAdder extends NNBaseEntity implements Controler { 33 | 34 | public Sensory2D_Booleans binary = new Sensory2D_Booleans(4, 10); 35 | 36 | public NumberAdder base; 37 | 38 | private final int max_bytes = 4; 39 | 40 | public NumberAdder(boolean createAI) { 41 | base = this; 42 | 43 | if (createAI) { 44 | this.ai = NNAI.generateAI(this, max_bytes + 1, 4, "1", "2", "4", "8", "16", "32", "64", "128", "256", "512", 45 | "1024"); 46 | 47 | for (int trueOrFalse = 0; trueOrFalse < 4; trueOrFalse++) { 48 | for (int binaryIndex = 0; binaryIndex < max_bytes; binaryIndex++) { 49 | InputBooleanNeuron.generateNeuronStatically(ai, trueOrFalse, binaryIndex, this.binary); 50 | } 51 | } 52 | 53 | for (int neurons = 0; neurons < 50; neurons++) { 54 | Neuron.generateNeuronStatically(ai, 1); 55 | } 56 | for (int neurons = 0; neurons < 40; neurons++) { 57 | Neuron.generateNeuronStatically(ai, 2); 58 | } 59 | BiasNeuron.generateNeuronStatically(ai, 0); 60 | BiasNeuron.generateNeuronStatically(ai, 1); 61 | 62 | connectNeurons(); 63 | setNeuronsPerRow(0, max_bytes); 64 | } 65 | this.controler = this; 66 | } 67 | 68 | public String learn() { 69 | boolean[] bbb = numberToBinaryBooleans((int) (Math.random() * (Math.pow(2, max_bytes)))); 70 | boolean[] bbb2 = numberToBinaryBooleans((int) (Math.random() * (Math.pow(2, max_bytes)))); 71 | for (int i = 0; i < bbb.length; i++) { 72 | this.binary.changeValueAt(0, i, (bbb[i])); 73 | ((NumberAdder) base).binary.changeValueAt(1, i, (!bbb[i])); 74 | } 75 | for (int i = 0; i < bbb2.length; i++) { 76 | ((NumberAdder) base).binary.changeValueAt(2, i, (bbb2[i])); 77 | ((NumberAdder) base).binary.changeValueAt(3, i, (!bbb2[i])); 78 | } 79 | boolean[] thought = tickAndThink(); 80 | 81 | boolean[] booleanBase = new boolean[10]; 82 | for (int i = 0; i < 10; i++) { 83 | booleanBase[i] = base.binary.getBooleanAt(0, i); 84 | } 85 | 86 | boolean[] booleanBase2 = new boolean[10]; 87 | for (int i = 0; i < 10; i++) { 88 | booleanBase2[i] = base.binary.getBooleanAt(2, i); 89 | } 90 | int number = binaryBooleansToNumber(booleanBase); 91 | int number2 = binaryBooleansToNumber(booleanBase2); 92 | int number3 = binaryBooleansToNumber(thought); 93 | 94 | boolean result = number + number2 == number3; 95 | boolean[] correctvalues = numberToBinaryBooleans(number + number2); 96 | 97 | this.getAccuracy().addEntry(result); 98 | 99 | StringBuilder sb = new StringBuilder(); 100 | int amountOfMistakes = 0; 101 | for (int i = 0; i < Math.max(correctvalues.length, thought.length); i++) { 102 | if (i < thought.length && thought[i]) { 103 | sb.append((correctvalues.length > i && correctvalues[i] ? ChatColor.DARK_GREEN : ChatColor.DARK_RED) 104 | + "+" + ((int) Math.pow(2, i))); 105 | if (!(correctvalues.length > i && correctvalues[i])) 106 | amountOfMistakes++; 107 | } else if (i < correctvalues.length && correctvalues[i]) { 108 | sb.append(ChatColor.GRAY + "+" + ((int) Math.pow(2, i))); 109 | amountOfMistakes++; 110 | } 111 | } 112 | 113 | // IMPROVE IT 114 | HashMap map = new HashMap<>(); 115 | for (int i = 0; i < thought.length; i++) { 116 | map.put(base.ai.getNeuronFromId(i), correctvalues.length > i && correctvalues[i] ? 1 : -1.0); 117 | } 118 | 119 | // amountOfMistakes = (int) Math.pow(2,amountOfMistakes); 120 | if (!result) 121 | DeepReinforcementUtil.instantaneousReinforce(base, map, amountOfMistakes); 122 | return ((result ? ChatColor.GREEN : ChatColor.RED) + "acc " + getAccuracy().getAccuracyAsInt() + "|" + number 123 | + " + " + number2 + " = " + number3 + "| " + sb.toString()); 124 | } 125 | 126 | @Override 127 | public String update() { 128 | boolean[] thought = tickAndThink(); 129 | 130 | boolean[] booleanBase = new boolean[10]; 131 | for (int i = 0; i < 10; i++) { 132 | booleanBase[i] = base.binary.getBooleanAt(0, i); 133 | } 134 | 135 | boolean[] booleanBase2 = new boolean[10]; 136 | for (int i = 0; i < 10; i++) { 137 | booleanBase2[i] = base.binary.getBooleanAt(2, i); 138 | } 139 | int number = binaryBooleansToNumber(booleanBase); 140 | int number2 = binaryBooleansToNumber(booleanBase2); 141 | int number3 = binaryBooleansToNumber(thought); 142 | 143 | StringBuilder sb = new StringBuilder(); 144 | for (int i = 0; i < thought.length; i++) { 145 | if (thought[i]) { 146 | sb.append("+" + ((int) Math.pow(2, i))); 147 | } 148 | } 149 | Bukkit.getConsoleSender().sendMessage("Byte Values = " + sb.toString()); 150 | return ("|" + number + " + " + number2 + " ~~ " + number3); 151 | } 152 | 153 | @Override 154 | public void setInputs(CommandSender initiator, String[] args) { 155 | if (this.shouldLearn) { 156 | initiator.sendMessage("Stop the learning before testing. use /nn stoplearning"); 157 | return; 158 | } 159 | 160 | if (args.length > 2) { 161 | int test = 0; 162 | try { 163 | test = Integer.parseInt(args[1]); 164 | } catch (Exception e) { 165 | return; 166 | } 167 | int test2 = 0; 168 | try { 169 | test2 = Integer.parseInt(args[2]); 170 | } catch (Exception e) { 171 | return; 172 | } 173 | int tempnumber = test; 174 | for (int power = 9; power >= 0; power--) { 175 | if (tempnumber - Math.pow(2, power) >= 0) { 176 | this.binary.changeValueAt(0, power, true); 177 | this.binary.changeValueAt(1, power, false); 178 | tempnumber -= Math.pow(2, power); 179 | } else { 180 | this.binary.changeValueAt(0, power, false); 181 | this.binary.changeValueAt(1, power, true); 182 | } 183 | } 184 | int tempnumber2 = test2; 185 | for (int power = 9; power >= 0; power--) { 186 | if (tempnumber2 - Math.pow(2, power) >= 0) { 187 | this.binary.changeValueAt(2, power, true); 188 | this.binary.changeValueAt(3, power, false); 189 | tempnumber2 -= Math.pow(2, power); 190 | } else { 191 | this.binary.changeValueAt(2, power, false); 192 | this.binary.changeValueAt(3, power, true); 193 | } 194 | } 195 | 196 | } else { 197 | initiator.sendMessage("Provide two numbers to add"); 198 | } 199 | 200 | } 201 | 202 | @Override 203 | public NNBaseEntity clone() { 204 | NumberAdder thi = new NumberAdder(false); 205 | thi.ai = this.ai; 206 | return thi; 207 | } 208 | 209 | @Override 210 | public void setBase(NNBaseEntity t) { 211 | this.base = (NumberAdder) t; 212 | } 213 | 214 | private boolean[] numberToBinaryBooleans(int i) { 215 | int mathlog = 0; 216 | for (int k = 0; k < 20; k++) { 217 | if (Math.pow(2, k) > i) { 218 | mathlog = k; 219 | break; 220 | } 221 | } 222 | boolean[] k = new boolean[mathlog]; 223 | 224 | int tempnumber = i; 225 | for (int power = mathlog - 1; power >= 0; power--) { 226 | if (tempnumber - Math.pow(2, power) >= 0) { 227 | k[power] = true; 228 | tempnumber -= Math.pow(2, power); 229 | 230 | } else { 231 | k[power] = false; 232 | } 233 | } 234 | return k; 235 | } 236 | 237 | private int binaryBooleansToNumber(boolean[] b) { 238 | int k = 0; 239 | for (int i = 0; i < b.length; i++) { 240 | if (b[i]) 241 | k += Math.pow(2, i); 242 | } 243 | return k; 244 | } 245 | 246 | } 247 | -------------------------------------------------------------------------------- /src/example/prime_number_guesser/PrimeNumberBot.java: -------------------------------------------------------------------------------- 1 | package example.prime_number_guesser; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | 22 | import org.bukkit.ChatColor; 23 | import org.bukkit.command.CommandSender; 24 | 25 | import me.zombie_striker.neuralnetwork.*; 26 | import me.zombie_striker.neuralnetwork.neurons.BiasNeuron; 27 | import me.zombie_striker.neuralnetwork.neurons.Neuron; 28 | import me.zombie_striker.neuralnetwork.neurons.input.InputNumberNeuron; 29 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Numbers; 30 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 31 | 32 | public class PrimeNumberBot extends NNBaseEntity implements Controler { 33 | 34 | public Sensory2D_Numbers binary = new Sensory2D_Numbers(2, 10); 35 | 36 | public boolean wasCorrect = true; 37 | 38 | public HashMap ifNumberIsPrime = new HashMap<>(); 39 | 40 | public PrimeNumberBot(boolean createAI) { 41 | super(false, 2000); 42 | // We want to store the last 2000 entries, so we know how accurate it is. 43 | initValidPrimes(); 44 | // this.senses.add(binary); 45 | 46 | if (createAI) { 47 | this.ai = NNAI.generateAI(this, 1, 5, "is A Prime"); 48 | 49 | for (int trueOrFalse = 0; trueOrFalse < 1; trueOrFalse++) { 50 | // Change 1 to 2 if you also want to include if bit is false 51 | for (int binaryIndex = 0; binaryIndex < 10; binaryIndex++) { 52 | InputNumberNeuron.generateNeuronStatically(ai, trueOrFalse, binaryIndex, this.binary); 53 | } 54 | } 55 | BiasNeuron.generateNeuronStatically(ai, 0); 56 | 57 | // Creates the neurons for layer 1. 58 | for (int neurons = 0; neurons < 40; neurons++) 59 | Neuron.generateNeuronStatically(ai, 1); 60 | for (int neurons = 0; neurons < 20; neurons++) 61 | Neuron.generateNeuronStatically(ai, 2); 62 | for (int neurons = 0; neurons < 10; neurons++) 63 | Neuron.generateNeuronStatically(ai, 3); 64 | 65 | connectNeurons(); 66 | } 67 | this.setNeuronsPerRow(0, 10); 68 | this.controler = this; 69 | } 70 | 71 | private int lastNumber = 0; 72 | 73 | public String learn() { 74 | boolean[] bbb = numberToBinaryBooleans((lastNumber++ % 1023)/* (int) (Math.random() * 1023) */); 75 | for (int i = 0; i < bbb.length; i++) { 76 | binary.changeNumberAt(0, i, (bbb[i]) ? 1 : 0); 77 | binary.changeNumberAt(1, i, (bbb[i]) ? 0 : 1); 78 | } 79 | 80 | boolean[] thought = tickAndThink(); 81 | float accuracy = 0; 82 | 83 | // If it isprime: 84 | 85 | boolean[] booleanBase = new boolean[10]; 86 | for (int i = 0; i < 10; i++) { 87 | booleanBase[i] = binary.getNumberAt(0, i) != 0; 88 | } 89 | int number = binaryBooleansToNumber(booleanBase); 90 | boolean result = ifNumberIsPrime.get(number); 91 | 92 | wasCorrect = (result == thought[0]); 93 | 94 | this.getAccuracy().addEntry(wasCorrect); 95 | accuracy = (float) this.getAccuracy().getAccuracy(); 96 | 97 | // IMPROVE IT 98 | HashMap map = new HashMap<>(); 99 | map.put(ai.getNeuronFromId(0), result ? 1 : -1.0); 100 | if (!wasCorrect) 101 | DeepReinforcementUtil.instantaneousReinforce(this, map, 1); 102 | return ((wasCorrect ? ChatColor.GREEN : ChatColor.RED) + "acc " + ((int) (100 * accuracy)) + "|=" + number 103 | + "|correctResp=" + result + "|WasPrime-Score " 104 | + ((int) (100 * (ai.getNeuronFromId(0).getTriggeredStength())))); 105 | } 106 | 107 | @Override 108 | public String update() { 109 | boolean[] thought = tickAndThink(); 110 | float accuracy = 0; 111 | 112 | // If it isprime: 113 | 114 | boolean[] booleanBase = new boolean[10]; 115 | for (int i = 0; i < 10; i++) { 116 | booleanBase[i] = binary.getNumberAt(0, i) != 0; 117 | } 118 | int number = binaryBooleansToNumber(booleanBase); 119 | boolean result = ifNumberIsPrime.get(number); 120 | 121 | return ((thought[0] ? ChatColor.DARK_GREEN : ChatColor.DARK_RED) + "|=" + number + "|WasPrime-Score " 122 | + ((int) (100 * (ai.getNeuronFromId(0).getTriggeredStength())))); 123 | 124 | } 125 | 126 | @Override 127 | public NNBaseEntity clone() { 128 | PrimeNumberBot thi = new PrimeNumberBot(false); 129 | thi.ai = this.ai; 130 | return thi; 131 | } 132 | 133 | public void setBase(NNBaseEntity t) { 134 | // this.base = (PrimeNumberGuesser) t; 135 | } 136 | 137 | /** 138 | * Adds string B to the hashmap with value true 139 | * 140 | * @param b 141 | */ 142 | public void a(Integer... b) { 143 | for (int c : b) 144 | ifNumberIsPrime.put(c, true); 145 | 146 | } 147 | 148 | private boolean[] numberToBinaryBooleans(int i) { 149 | boolean[] k = new boolean[10]; 150 | 151 | int tempnumber = i; 152 | for (int power = 9; power >= 0; power--) { 153 | if (tempnumber - Math.pow(2, power) >= 0) { 154 | k[power] = true; 155 | // System.out.println(tempnumber+" - "+(tempnumber-Math.pow(2,power))); 156 | tempnumber -= Math.pow(2, power); 157 | 158 | } else { 159 | k[power] = false; 160 | } 161 | } 162 | return k; 163 | } 164 | 165 | private int binaryBooleansToNumber(boolean[] b) { 166 | int k = 0; 167 | for (int i = 0; i < b.length; i++) { 168 | if (b[i]) 169 | k += Math.pow(2, i); 170 | } 171 | return k; 172 | } 173 | 174 | private boolean isPrime(int n) { 175 | // check if n is a multiple of 2 176 | if (n % 2 == 0) 177 | return false; 178 | // if not, then just check the odds 179 | for (int i = 3; i * i <= n; i += 2) { 180 | if (n % i == 0) 181 | return false; 182 | } 183 | return true; 184 | } 185 | 186 | private void initValidPrimes() { 187 | for (int i = 0; i < 1023; i++) { 188 | ifNumberIsPrime.put(i, isPrime(i)); 189 | // ifNumberIsPrime.put(i, i%2==0); 190 | } 191 | } 192 | 193 | @Override 194 | public void setInputs(CommandSender initiator, String[] args) { 195 | if (this.shouldLearn) { 196 | initiator.sendMessage("Stop the learning before testing. use /nn stoplearning"); 197 | return; 198 | } 199 | 200 | if (args.length > 1) { 201 | int test = 0; 202 | try { 203 | test = Integer.parseInt(args[1]); 204 | } catch (Exception e) { 205 | return; 206 | } 207 | int tempnumber = test; 208 | for (int power = 9; power >= 0; power--) { 209 | if (tempnumber - Math.pow(2, power) >= 0) { 210 | this.binary.changeNumberAt(0, power, 1); 211 | this.binary.changeNumberAt(1, power, 0); 212 | tempnumber -= Math.pow(2, power); 213 | } else { 214 | this.binary.changeNumberAt(0, power, 0); 215 | this.binary.changeNumberAt(1, power, 1); 216 | } 217 | } 218 | } else { 219 | initiator.sendMessage("Provide a number"); 220 | } 221 | 222 | } 223 | 224 | } 225 | -------------------------------------------------------------------------------- /src/example/swearfilter/ExampleSwearListener.java: -------------------------------------------------------------------------------- 1 | package example.swearfilter; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import me.zombie_striker.neuralnetwork.NeuralNetwork; 21 | import me.zombie_striker.nnmain.Main; 22 | 23 | import org.bukkit.Bukkit; 24 | import org.bukkit.ChatColor; 25 | import org.bukkit.event.*; 26 | import org.bukkit.event.player.AsyncPlayerChatEvent; 27 | import org.bukkit.scheduler.BukkitRunnable; 28 | 29 | public class ExampleSwearListener implements Listener { 30 | 31 | private NeuralNetwork currentNN; 32 | /** 33 | * This does not actually do anything. All this is meant for is to check if the main 34 | * NN for the demo is set to SwearFilter, and if so, create 5 more swearbots that will actually 35 | * train to listen for swear words. 36 | */ 37 | 38 | private NeuralNetwork[] swearbots = new NeuralNetwork[5]; 39 | 40 | private boolean training = false; 41 | 42 | public ExampleSwearListener(NeuralNetwork n) { 43 | currentNN = n; 44 | 45 | //Creating runnable so it only starts training the NN when the main NN is set to a swearbot 46 | new BukkitRunnable() { 47 | @Override 48 | public void run() { 49 | if (!(currentNN.getCurrentNeuralNetwork() instanceof SwearBot)) 50 | return; 51 | // Every second, check if swearbot has been set. If it has not, return. At the very end, cancel the task so this only runs once. 52 | 53 | Bukkit.broadcastMessage(ChatColor.GOLD 54 | + "Training the swear bots. Please wait"); 55 | for (int i = 0; i < swearbots.length; i++) { 56 | swearbots[i] = new NeuralNetwork(Main.getMainClass()); 57 | swearbots[i].setBroadcasting(false); 58 | // Cleans up the command prompt 59 | } 60 | swearbots[0] 61 | .setCurrentNeuralNetwork(new SwearBot(true, "fuck")); 62 | swearbots[1] 63 | .setCurrentNeuralNetwork(new SwearBot(true, "shit")); 64 | swearbots[2] 65 | .setCurrentNeuralNetwork(new SwearBot(true, "bitch")); 66 | swearbots[3] 67 | .setCurrentNeuralNetwork(new SwearBot(true, "cunt")); 68 | swearbots[4].setCurrentNeuralNetwork(new SwearBot(true, "fag")); 69 | 70 | swearbots[0].startLearningAsynchronously(); 71 | training=true; 72 | for (int i = 1; i < swearbots.length; i++) { 73 | final int k = i; 74 | new BukkitRunnable() { 75 | 76 | @Override 77 | public void run() { 78 | Bukkit.broadcastMessage("Finished training \""+((SwearBot)swearbots[k-1].getCurrentNeuralNetwork()).filterType.substring(0,2)+"\" NN " 79 | + (k) + "/" + swearbots.length+" Accuracy:"+swearbots[k-1].getCurrentNeuralNetwork().getAccuracy().getAccuracyAsInt()); 80 | swearbots[k - 1].stopLearning(); 81 | swearbots[k].startLearningAsynchronously(); 82 | } 83 | }.runTaskLater(Main.getMainClass(), 20 * 15 * k); 84 | // Train for 15 seconds 85 | } 86 | new BukkitRunnable() { 87 | 88 | @Override 89 | public void run() { 90 | swearbots[4].stopLearning(); 91 | Bukkit.broadcastMessage("Finished training \""+((SwearBot)swearbots[4].getCurrentNeuralNetwork()).filterType.substring(0,2)+"\" NN " 92 | + (5) + "/" + swearbots.length+" Accuracy:"+swearbots[4].getCurrentNeuralNetwork().getAccuracy().getAccuracyAsInt()); 93 | Bukkit.broadcastMessage(ChatColor.GOLD + "Done!"); 94 | training=false; 95 | } 96 | }.runTaskLater(Main.getMainClass(), 97 | 20 * 15 * (swearbots.length)); 98 | this.cancel(); 99 | } 100 | }.runTaskTimer(Main.getMainClass(), 20 * 4, 20); 101 | } 102 | 103 | @EventHandler(priority = EventPriority.LOWEST) 104 | public void onChat(AsyncPlayerChatEvent e) { 105 | if (currentNN != null) 106 | if (!(currentNN.getCurrentNeuralNetwork() instanceof SwearBot)) 107 | return; 108 | if(training) 109 | return; 110 | 111 | //If it is not training, and if the demo is set to swearbot, then do the following: 112 | 113 | StringBuilder chat = new StringBuilder(); 114 | chat.append(" "); 115 | for (char c : e.getMessage().toUpperCase().toCharArray()) { 116 | if (c != ' ' && c != '?' && c != '.' && c != ',' && c != '!') 117 | chat.append(c); 118 | } 119 | //Add two spaces before the chat message, remove all spaces and punctuation marks so 's?h.i t' is treated as 'shit' 120 | 121 | for (int i = 0; i < chat.toString().length(); i++) { 122 | String testingString = chat.toString().substring(i); 123 | //We are using a scanner approach. This will offset the string by 1 char until it is at the last letter. 124 | for (NeuralNetwork k : swearbots) { 125 | ((SwearBot) k.getCurrentNeuralNetwork()).word 126 | .changeWord(testingString); 127 | //Loop through all the swear types. Testt it for each NN. 128 | 129 | boolean detectsSwearWord = ((SwearBot) k 130 | .getCurrentNeuralNetwork()).tickAndThink()[0]; 131 | if (detectsSwearWord) { 132 | // The bot detects a similarity to a swear word. May be a swear. 133 | e.setCancelled(true); 134 | e.getPlayer() 135 | .sendMessage( 136 | "[SwearBot] Do not swear. Found similarities of \"" 137 | + ((SwearBot) k 138 | .getCurrentNeuralNetwork()).filterType 139 | + "\" in \"" + testingString + "\""); 140 | return; 141 | } 142 | } 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/example/swearfilter/SwearBot.java: -------------------------------------------------------------------------------- 1 | package example.swearfilter; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.*; 21 | import java.util.concurrent.ThreadLocalRandom; 22 | 23 | import org.bukkit.ChatColor; 24 | import org.bukkit.command.CommandSender; 25 | 26 | import me.zombie_striker.neuralnetwork.*; 27 | import me.zombie_striker.neuralnetwork.neurons.*; 28 | import me.zombie_striker.neuralnetwork.neurons.input.InputLetterNeuron; 29 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Letters; 30 | import me.zombie_striker.neuralnetwork.util.DeepReinforcementUtil; 31 | 32 | public class SwearBot extends NNBaseEntity implements Controler { 33 | 34 | public static char[] letters = InputLetterNeuron.letters; 35 | //Returns capital letters A-Z and 0-9 36 | 37 | public Sensory2D_Letters word = new Sensory2D_Letters("none"); 38 | public boolean wasCorrect = true; 39 | 40 | public List cleanWords = new ArrayList(); 41 | public List swearWords = new ArrayList(); 42 | 43 | public String filterType = "null"; 44 | //Makes it easier to print out what each NN is testing for. 45 | 46 | public SwearBot(boolean createAI) { 47 | // Only used for my Demo system. You do not actually need this constructor for your NNs. 48 | } 49 | 50 | public SwearBot(boolean createAI, String sweartype) { 51 | super(false, 2000); 52 | /** 53 | * The second value for the super is how many points are stored for 54 | * accuracy. This means that the accuracy printed 55 | */ 56 | // initValidNames(); 57 | 58 | if (createAI) { 59 | // Generates an ai with ONE output, which is equal to whether it is 60 | // a player 61 | this.ai = NNAI.generateAI(this, 1, 4, "Is a swear word"); 62 | 63 | for (int index = 0; index < 16; index++) { 64 | for (int character = 0; character < letters.length; character++) { 65 | // 1st one is what index, the next is the actual character 66 | InputLetterNeuron.generateNeuronStatically(ai, index, 67 | character, this.word); 68 | } 69 | } 70 | /** 71 | * Two layers are used for this one because there are a lot of 72 | * nuances in language. Adding more hidden layers will increase the 73 | * amount of variance and specificity that it will look for. 74 | */ 75 | // Creates the neurons for layer 1. 76 | for (int neurons = 0; neurons < 50; neurons++) 77 | Neuron.generateNeuronStatically(ai, 1); 78 | // Creates the neurons for layer 2 79 | for (int neurons = 0; neurons < 15; neurons++) 80 | Neuron.generateNeuronStatically(ai, 2); 81 | 82 | BiasNeuron.generateNeuronStatically(ai, 0); 83 | BiasNeuron.generateNeuronStatically(ai, 1); 84 | 85 | connectNeurons(); 86 | } 87 | this.controler = this; 88 | 89 | this.setNeuronsPerRow(0, letters.length); 90 | 91 | /** 92 | * Since there is no universal quality in the arrangement of all 5 swear words, each NN has to be trained for each specific swear word. 93 | */ 94 | filterType = sweartype; 95 | if (sweartype.equals("fuck")) { 96 | initValidNames(0); 97 | } else if (sweartype.equals("shit")) { 98 | initValidNames(1); 99 | } else if (sweartype.equals("bitch")) { 100 | initValidNames(2); 101 | } else if (sweartype.equals("cunt")) { 102 | initValidNames(3); 103 | } else if (sweartype.equals("fag")) { 104 | initValidNames(4); 105 | } else { 106 | initValidNames(0); 107 | } 108 | } 109 | 110 | public String learn() { 111 | 112 | boolean useSwear = ThreadLocalRandom.current().nextBoolean() 113 | && ThreadLocalRandom.current().nextBoolean(); 114 | //The booleans are doubled to make sure swear words happen 1/4 the time, as it is more important to make sure clean words are not flagged than to go over swear words. 115 | if (useSwear) { 116 | word.changeWord((String) swearWords.toArray()[(int) ((swearWords 117 | .size() - 1) * Math.random())]); 118 | } else { 119 | word.changeWord((String) cleanWords.toArray()[(int) ((cleanWords 120 | .size() - 1) * Math.random())]); 121 | } 122 | boolean result = tickAndThink()[0]; 123 | 124 | boolean isswear = swearWords.contains(word.getWord()); 125 | wasCorrect = result == isswear; 126 | //Returns if it was a swear word; 127 | 128 | this.getAccuracy().addEntry(wasCorrect); 129 | float accuracy = (float) this.getAccuracy().getAccuracy(); 130 | 131 | // IMPROVE IT 132 | Neuron[] array = new Neuron[1]; 133 | if (isswear) 134 | array[0] = ai.getNeuronFromId(0); 135 | //Instead of hashmaps, since there is only 1 output neuron, is is easier to do this instead of defining the suggested value. 136 | //Adding it to the array means the suggested value is +1. Not having it means it is -1. 137 | 138 | //only learn when it was not correct. 139 | if (!wasCorrect) { 140 | DeepReinforcementUtil.instantaneousReinforce(this, array, 1); 141 | } 142 | return ((wasCorrect ? ChatColor.GREEN : ChatColor.RED) + "acc " 143 | + ((int) (100 * accuracy)) + "|=" + word.getWord() + "| " 144 | + result + "." + isswear + "|Swear-Score " + ((int) (100 * (ai 145 | .getNeuronFromId(0).getTriggeredStength())))); 146 | } 147 | 148 | @Override 149 | public String update() { 150 | boolean result = tickAndThink()[0]; 151 | return "" + result; 152 | 153 | } 154 | 155 | @Override 156 | public void setInputs(CommandSender initiator, String[] args) { 157 | if (this.shouldLearn) { 158 | initiator 159 | .sendMessage("Stop the learning before testing. use /nn stoplearning"); 160 | return; 161 | } 162 | if (args.length > 1) { 163 | String username = " " + args[1].toUpperCase(); 164 | this.word.changeWord(username); 165 | return; 166 | } else { 167 | initiator.sendMessage("Provide an id"); 168 | } 169 | } 170 | 171 | private void initValidNames(int i) { 172 | 173 | // swears 174 | /** 175 | * Because there is not some universal element that exists for all swear 176 | * words in existance, you have to narrow the search to just one swear 177 | * word and its varients. For each swear word you want to filter out, 178 | * you need to create and train a new NN 179 | */ 180 | if (i == 0) 181 | a(true, " fuck", " fuk", " fuc", " fck", " phuc", " phuk", 182 | " fuck", " fucccckkking", " fuuuuck", " fookkkkk", 183 | " fuuuk", " fuka", " fuck", " fuck", " fook", 184 | " foock", " fooooking", " fuukin", " fuc", " fuuukk", 185 | " ffuuuuck"); 186 | if (i == 1) 187 | a(true, " shit", " ssshhit", " shhhiiiite", " shite", 188 | " shiiit", " shhhhhhhiiiiiiit", " shitty", " shat", 189 | " shaaaat", " shart", " shaaaaart", " shitt", 190 | " shiiit"); 191 | if (i == 2) 192 | a(true, " bitch", " bich", " bitch", " btch", " biiiitch", 193 | " biiiiich", " biatch", " biiiaaatch", " biiiatch", 194 | " bitttttttttch", " biiiiiiich", " bicccch", " bitch"); 195 | if (i == 3) 196 | a(true, " cunt", " cuuuuuunt", " kunt", " cuuuuuuuunnnt", 197 | " cuuunt", " kuuuunntttt", " kunnnnt"); 198 | if (i == 4) 199 | a(true, " fag", " faggot", " fagget", " feggit", " figgit", 200 | " faaaaag", " phagot", " phaggot", " phag", 201 | " phaaaaag", " phaaaget", " faaaaagggot", " phegot", 202 | " pheggot"); 203 | 204 | // Leave two spaces for beginnings of sentences. Two spaces are done so things like "Mass" does not get flagged as "Ass" simply because it does not see the letter before. 205 | 206 | // clean 207 | a(false, " mass", "mass", " mass", "the", "world", "some", "so", 208 | "such", "mynameisjeff", "woah", "text", "it", "does", "not", 209 | "very", " very", "clean", " clean", "come", " come", 210 | "carrot", " klingon", " captain", " kirk", " discord", 211 | "funky", " funky", "matter", "what", "i", "type", " hello", 212 | " world", " some", " example", " test", " messages", 213 | " of", "of", "normal", "sneak", " sneak", "shifting", 214 | " shifting", " are", " you", " is", "jerky", "snowglobe", 215 | "canoue", " vote", " meat", " meet", " idk", " taxi", 216 | " booya", " bomb", "dictionairy", "coolio", " normal", 217 | "continue", "shihtzu", "zen", "zone", " shihtzu", "zoo", 218 | "zoom", "picklerick", " words", " it", " can", " be", 219 | "anything", "greatgamegg", "anything", " anything", 220 | " aything", " that", " the", " reader", " would", " read", 221 | " cool", " heywantto", "coming", "following", "climbing", 222 | "flagging", "masking", "creating", "flinging", "shining", 223 | " shining", "gliding", "swimming", "swarming", "shunning", 224 | "grappling", "sappling", "tradeforsome", "diamonds", "gold", 225 | "emerald", "do", " do", " do", " iron", " mass", "mass", 226 | " mass", " geoff", "somerandom", "lengthofstring", 227 | "forsomething", "op", "opis", "anythingelseyou", "wouldliketo", 228 | "add", "subtract", "wordassociation", "mispelword", "kik", 229 | "kek", "lol", " lol", " lol", "goodjob", "Accordingtoall", 230 | "knownlawsofaviation", "thereisnowayabee", "shouldbeable", 231 | "toflyits", "wingsaretoo", "smalltogetits", "fatlittlebodyoff", 232 | "thegroundThe", "beeofcourse", "fliesanyway", 233 | "becausebeesdont", "can", " can", " who", " bythepower", 234 | " ofgrayskull", " zombie", " mummy", " mommy", " daddy", 235 | " kiddo", " kid", "thatsright", "atright", "hatsright", 236 | "right", "sright", "meetatspawn", "somebody", "oncetoldme", 237 | "theworldis", "bacon", " bacon", "biscut", " biscut", 238 | " biscut", "totalbiscut", "abiscut", "country", "county", 239 | "community", "poppop", "nevergonna", "giveyouup", "nevergonna", 240 | "letyoudown", "nevergonnarunaround", "anddesertyou", 241 | "takeabow", "carewhathumansthink", "isimpossibleYellow", 242 | "blackYellowblack", "YellowblackYellow", "blackOoh", 243 | "blackandyellow", "letsshakeitupalittle", "ifweeverwanted", 244 | "toachieveinterestaller", "travelsomething", 245 | "somethingorother", "justsomeothertext", "moretextandstuff", 246 | "duck", "ducking", "fudge", "fudging", " ducking", " ducking", 247 | " shipping", "shipping", " shipping", " sharp", "cup", 248 | " cup", "chip", " chip", "caesar", "thangs", 249 | "maybetheNNisoff", "weneedmoretesting", "morestuff", "zebealo", 250 | "weeboasf", "forefsase", "dsfawdsddg", "dsafGASGDSAG", 251 | "stuifas", "testxrtwats", "period", " wirds", "wereecsf", 252 | "zzzzdgfwasf", "mooooos", "thecowgoesmpoo", "dogswoof", 253 | "catsmoew", "cwomoo", "moretext", "swearsstuff", "hullo", 254 | "halo", "wynncraft", "mineplex", "spigot", "bukkit", 255 | "theshotbownetwork", "network", "hivemc", 256 | "thisisanexampletext", "sampletext", "gateeem", "lolwat", 257 | "cooliokid", "Zombie_Striker", "Zombie", "Skeleton", "creeper", 258 | "cow", "chicken", "pig", "squid", "quack", "parrot", 259 | "silverfish", "fish", "redfish", "bluefish", "onefishtwofish", 260 | "enderman", "enderdragon", "dragon", "moretextthatisnotbad", 261 | "goodtext", "mrwsomethingcool", "happens", "fallout", 262 | "callofduty", "blackops", "liamneelson", "mattdamon", 263 | "hisnameisrobert", "paulson", "hisnameis", "robertpaulson", 264 | "fightclub", "incaseyouwerewondering", "plastic", "aluminium", 265 | "iron", "rock", "granite", "andersite", "obsidian", "queue", 266 | "joke", "batman", "superman", "aquaman", "wonderwoman", 267 | "spiderman", "ironman", "hulk", "ironfist", "lukecage", "thor", 268 | "hhhhhug", "firstlook", "quick", "quit", " quick", 269 | "thisisallgoodtext", "somethingthatwouldbe", 270 | "seenoneveryserver", "EVERYSERVER", "nonofitis", "justrabling", 271 | "ofadeveloper", "losingsleep", "becauseastupid", 272 | "neuralnetworkiis", "refusingtowork", "withasmallsamplesize", 273 | "WHYWONTYOU", "FILTEROUTSWEARWORDS", "thereisnotasingle", 274 | "swearwordinthisblock", "oftext", "noneofthese", "sometimes", 275 | "sometimesyou", " youjusthave", " sometimes", "letters", 276 | "tters", "ttters", "certainwords", "whycanyou", 277 | "canyoujustnot", " justnot", "whyareyoudoing", " thistome", 278 | " whyareyoudoingthis", "flipping", " flipping", " flunky", 279 | "flunky", " flunky", " flying", "flying", " flyying", 280 | "false", " false", " full", " filling", " flame", " fling", 281 | " flung", " flop", "flop", " flop", "little", "lame", 282 | " lame", "assassin", " assassin", " assassin", 283 | " assasinscreed", "anassassin", "gas", " gas", "deka", 284 | " daca", " waterboard", "lava", " lava", " villager", 285 | "witch", "potions", " potions", "keepthisinmind", 286 | "learnfromthis", "justdoit", " justdoit", "makeyourdeams", 287 | " makeyourdreams", "cometrue", " cometrue", "true", " true", 288 | "helpme", " help", "howtoraisemaxhealth", "maxhealth", 289 | "thechancesaresmall", "butIhaveagood", "feelingthaththis", 290 | "isenough", "paulwalker"); 291 | 292 | a(false, "abcdefghijklmnopqrstuvwxyz".split("")); 293 | a(false, 294 | " a. b. c. d. e. f. g. h. i. j. k. l. m. n. o. p. q. r. s. t. u. v. w. v. x. y. z" 295 | .split(".")); 296 | a(false, "1234567890".split("")); 297 | 298 | } 299 | 300 | @Override 301 | public NNBaseEntity clone() { 302 | SwearBot thi = new SwearBot(false, filterType); 303 | thi.ai = this.ai; 304 | return thi; 305 | } 306 | 307 | public void setBase(NNBaseEntity t) { 308 | // this.base = (SwearBot) t; 309 | } 310 | 311 | public SwearBot(Map map) { 312 | super(map); 313 | } 314 | 315 | /** 316 | * Adds string B to the hashmap with value true 317 | * 318 | * @param b 319 | */ 320 | public void a(boolean d, String... b) { 321 | if (d) { 322 | for (String c : b) 323 | swearWords.add(c.toUpperCase()); 324 | } else { 325 | for (String c : b) 326 | cleanWords.add(c.toUpperCase()); 327 | // isSwearWord.put(c.toUpperCase(), d); 328 | } 329 | } 330 | 331 | public void a(boolean d, String full) { 332 | full = full.toUpperCase().replaceAll(" ", "").replaceAll("!", "") 333 | .replaceAll("?", "").replaceAll(".", "").replaceAll(",", "") 334 | .replaceAll("'", "").replaceAll("\"", "").replaceAll("-", ""); 335 | int skip = 0; 336 | for (; skip > full.length();) { 337 | int size = (int) ((Math.random() * 13) + 2); 338 | String c = full.substring(skip, size); 339 | skip += size; 340 | if (d) { 341 | swearWords.add(c); 342 | } else { 343 | cleanWords.add(c); 344 | } 345 | // isSwearWord.put(c, d); 346 | } 347 | } 348 | } 349 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/Controler.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import org.bukkit.command.CommandSender; 21 | import org.bukkit.configuration.serialization.ConfigurationSerializable; 22 | 23 | public interface Controler extends ConfigurationSerializable { 24 | /** 25 | * This is what will cause the AI to think. The return is a message that will be 26 | * printed to console. 27 | * 28 | * @return 29 | */ 30 | public String update(); 31 | 32 | public void setBase(NNBaseEntity base); 33 | 34 | public void setInputs(CommandSender initiator, String[] args); 35 | 36 | /** 37 | * This is a method designed for learning. Instead of relying on the update 38 | * method to learn, this will help separate code designed for testing and for 39 | * learning 40 | * 41 | * The learn method will not be called in this update. However, in future 42 | * updates, this is the method that will be called when learning. 43 | */ 44 | public String learn(); 45 | } 46 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/Layer.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.ArrayList; 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | 24 | import org.bukkit.configuration.serialization.ConfigurationSerializable; 25 | 26 | import me.zombie_striker.neuralnetwork.neurons.Neuron; 27 | 28 | public class Layer implements ConfigurationSerializable { 29 | public ArrayList neuronsInLayer = new ArrayList<>(); 30 | private int i; 31 | 32 | private int neuronsperrow = -1; 33 | 34 | public Layer(int layer) { 35 | i = layer; 36 | } 37 | 38 | public int getLayer() { 39 | return i; 40 | } 41 | 42 | public int getNeuronsPerRow() { 43 | return neuronsperrow; 44 | } 45 | 46 | public void setNeuronsPerRow(int i) { 47 | neuronsperrow = i; 48 | } 49 | 50 | @SuppressWarnings("unchecked") 51 | public Layer(Map map) { 52 | this.neuronsInLayer = (ArrayList) map.get("n"); 53 | this.i = (int) map.get("l"); 54 | this.neuronsperrow = (int) map.get("npr"); 55 | } 56 | 57 | @Override 58 | public Map serialize() { 59 | Map m = new HashMap(); 60 | m.put("n", this.neuronsInLayer); 61 | m.put("l", this.i); 62 | m.put("npr", neuronsperrow); 63 | return m; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/NNAI.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.*; 21 | 22 | import org.bukkit.configuration.serialization.ConfigurationSerializable; 23 | 24 | import me.zombie_striker.neuralnetwork.neurons.*; 25 | import me.zombie_striker.neuralnetwork.util.LossHolder; 26 | 27 | public class NNAI implements ConfigurationSerializable { 28 | 29 | public static int idTotal = 0; 30 | private int id = 0; 31 | 32 | public NNBaseEntity entity; 33 | /* 34 | private LossHolder lossHolder = new LossHolder(500); 35 | /** 36 | * Returns the lossHolder, which is usefull for determining how well the network is training 37 | * @return 38 | * 39 | public LossHolder getLossHolder() { 40 | return lossHolder; 41 | }*/ 42 | 43 | 44 | private HashMap allNeurons = new HashMap<>(); 45 | private List layers = new ArrayList(); 46 | 47 | private int currentNeuronId = 0; 48 | private int currentTick = -1; 49 | public int maxlayers = -1; 50 | 51 | public NNAI(NNBaseEntity nnEntityBase) { 52 | this(nnEntityBase, 3); 53 | } 54 | 55 | public NNAI(NNBaseEntity nnEntityBase, int layers_amount) { 56 | id = idTotal; 57 | idTotal++; 58 | entity = nnEntityBase; 59 | nnEntityBase.ai = this; 60 | 61 | this.maxlayers = layers_amount; 62 | 63 | for (int i = 0; i < maxlayers; i++) { 64 | layers.add(new Layer(i)); 65 | } 66 | } 67 | 68 | public NNAI(NNBaseEntity e, int id, boolean addToTotal) { 69 | this(e, id, addToTotal, 3); 70 | } 71 | 72 | public NNAI(NNBaseEntity e, int id, boolean addToTotal, int layers_amount) { 73 | this.id = id; 74 | if (addToTotal) 75 | idTotal++; 76 | entity = e; 77 | e.ai = this; 78 | 79 | this.maxlayers = layers_amount; 80 | 81 | for (int i = 0; i < maxlayers; i++) { 82 | layers.add(new Layer(i)); 83 | } 84 | } 85 | public void setNeuronsPerRow(int row, int amount) { 86 | this.getLayer(row).setNeuronsPerRow(amount); 87 | } 88 | 89 | public int getNeuronsPerRow(int row) { 90 | return this.getLayer(row).getNeuronsPerRow(); 91 | } 92 | 93 | public Neuron getNeuronFromId(Integer n) { 94 | return allNeurons.get(n); 95 | } 96 | /** 97 | * Dropping-out is a method used to cause the NN to generalize. Dropped-out 98 | * neurons will not be activate, and because of that, will not contribute to the 99 | * output value, causing other neurons when training to contribute more. 100 | * 101 | * This should be called before training, and stopDropout() should be called once training is done. 102 | * 103 | * @param chanceForDropout 104 | */ 105 | public void dropOutHiddenLayerNeuronsForTraining(double chanceForDropout) { 106 | for(int i = 1; i < maxlayers-1; i++) { 107 | for(Neuron n : getNeuronsInLayer(i)) { 108 | if(Math.random() getNeuronsFromId(Collection set) { 135 | Set neurons = new HashSet(); 136 | for (Integer n : set) { 137 | neurons.add(allNeurons.get(n)); 138 | } 139 | return neurons; 140 | } 141 | 142 | public static NNAI generateAI(NNBaseEntity nnEntityBase, int numberOfMotorNeurons, String... names) { 143 | NNAI ai = new NNAI(nnEntityBase); 144 | for (int i = 0; i < numberOfMotorNeurons; i++) { 145 | OutputNeuron omn = new OutputNeuron(ai, i); 146 | if (i < names.length) 147 | omn.setName(names[i]); 148 | } 149 | return ai; 150 | } 151 | 152 | public static NNAI generateAI(NNBaseEntity nnEntityBase, int numberOfMotorNeurons, int layers, String... names) { 153 | NNAI ai = new NNAI(nnEntityBase, layers); 154 | for (int i = 0; i < numberOfMotorNeurons; i++) { 155 | OutputNeuron omn = new OutputNeuron(ai, i); 156 | if (i < names.length) 157 | omn.setName(names[i]); 158 | } 159 | return ai; 160 | } 161 | 162 | public boolean[] think() { 163 | this.tick(); 164 | for (int i = 0; i < layers.size(); i++) { 165 | for (Neuron n : getNeuronsInLayer(i)) { 166 | n.forceTriggerStengthUpdate(); 167 | } 168 | } 169 | boolean[] points = new boolean[getOutputNeurons().size()]; 170 | for (Neuron n : getOutputNeurons()) { 171 | if (n.isTriggered()) { 172 | if (n instanceof OutputNeuron) 173 | points[((OutputNeuron) n).responceid] = true; 174 | } 175 | } 176 | return points; 177 | } 178 | 179 | public NNAI clone(NNBaseEntity base) { 180 | NNAI ai = new NNAI(base, maxlayers); 181 | for (int i = 0; i < allNeurons.size(); i++) { 182 | allNeurons.get(i).generateNeuron(ai); 183 | } 184 | return ai; 185 | } 186 | 187 | public void tick() { 188 | currentTick++; 189 | } 190 | 191 | public List getLayers() { 192 | return layers; 193 | } 194 | 195 | public Layer getLayer(int layer) { 196 | return layers.get(layer); 197 | } 198 | 199 | public List getInputNeurons() { 200 | return layers.get(0).neuronsInLayer; 201 | } 202 | 203 | public List getAllNeurons() { 204 | return new ArrayList(allNeurons.values()); 205 | } 206 | 207 | public void addNeuron(Neuron n) { 208 | this.allNeurons.put(n.getID(), n); 209 | } 210 | 211 | public int getCurrentTick() { 212 | return currentTick; 213 | } 214 | 215 | public void setCurrentTick(int i) { 216 | currentTick = i; 217 | } 218 | 219 | public int generateNeuronId() { 220 | return currentNeuronId++; 221 | } 222 | 223 | public int getNewestId() { 224 | return currentNeuronId; 225 | } 226 | 227 | public ArrayList getNeuronsInLayer(int layer) { 228 | return layers.get(layer).neuronsInLayer; 229 | } 230 | 231 | public ArrayList getOutputNeurons() { 232 | return getNeuronsInLayer(layers.size() - 1); 233 | } 234 | 235 | @SuppressWarnings("unchecked") 236 | public NNAI(Map map) { 237 | this.layers = (List) map.get("l"); 238 | for (Layer l : layers) { 239 | for (Neuron n : l.neuronsInLayer) { 240 | if (n != null) { 241 | n.setAI(this); 242 | addNeuron(n); 243 | // getNeuronsInLayer(n.layer).add(n); 244 | } 245 | } 246 | } 247 | this.maxlayers = (int) map.get("ml"); 248 | this.id = (int) map.get("id"); 249 | } 250 | 251 | @Override 252 | public Map serialize() { 253 | Map m = new HashMap(); 254 | m.put("l", this.layers); 255 | m.put("ml", this.maxlayers); 256 | m.put("id", this.id); 257 | return m; 258 | } 259 | 260 | } 261 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/NNBaseEntity.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.Random; 23 | 24 | import org.bukkit.configuration.serialization.ConfigurationSerializable; 25 | 26 | import me.zombie_striker.neuralnetwork.neurons.*; 27 | import me.zombie_striker.neuralnetwork.util.Accuracy; 28 | 29 | public class NNBaseEntity implements ConfigurationSerializable { 30 | 31 | public NNAI ai; 32 | 33 | public Controler controler; 34 | public boolean shouldLearn = false; 35 | 36 | // TODO: Default accuracy is 500. This makes sure slight changes to the 37 | // amount of correct answers should not affect the total accuracy that much 38 | Accuracy accuracy = new Accuracy(500); 39 | 40 | public Accuracy getAccuracy() { 41 | return accuracy; 42 | } 43 | 44 | public NNBaseEntity() { 45 | } 46 | 47 | public NNBaseEntity(boolean createAI) { 48 | if (createAI) 49 | ai = new NNAI(this); 50 | accuracy = new Accuracy(500); 51 | } 52 | 53 | public NNBaseEntity(boolean createAI, int accuracyCheck) { 54 | if (createAI) 55 | ai = new NNAI(this); 56 | accuracy = new Accuracy(accuracyCheck); 57 | } 58 | 59 | public void connectNeurons() { 60 | for (Neuron n : ai.getAllNeurons()) { 61 | connectNeuron(n); 62 | } 63 | } 64 | 65 | public void connectNeuron(Neuron n) { 66 | if (ai.maxlayers > n.layer + 1) { 67 | // n.setWeight((Math.random() * 2) - 1); 68 | // n.setWeight(0.1); 69 | for (Neuron output : ai.getNeuronsInLayer(n.layer + 1)) { 70 | if (output instanceof BiasNeuron) 71 | continue; 72 | // n.getOutputs().add(output.getID()); 73 | // output.getInputs().add(n.getID()); 74 | // n.setStrengthForNeuron(output, (Math.random() * 2) - 1); 75 | n.setStrengthForNeuron(output, 0); 76 | } 77 | } 78 | } 79 | 80 | /** 81 | * In case the neuron needs more neurons after it has already been trained, this 82 | * will add the connection from previous layers. 83 | * 84 | * @param newNeuron 85 | * - the new neuron that was added. 86 | */ 87 | public void backPropNeuronConnections(Neuron newNeuron, boolean randomize) { 88 | if (newNeuron.getLayer() > 0) { 89 | for (Neuron n : getAI().getNeuronsInLayer(newNeuron.getLayer() - 1)) { 90 | if (n.allowNegativeValues()) 91 | n.setStrengthForNeuron(newNeuron, randomize ? (Math.random() * 2) - 1 : 0.1); 92 | else 93 | n.setStrengthForNeuron(newNeuron, randomize ? Math.random() : 0.1); 94 | } 95 | } 96 | } 97 | 98 | public void randomizeNeurons() { 99 | for (Neuron n : ai.getAllNeurons()) { 100 | randomizeNeuron(n); 101 | } 102 | } 103 | 104 | public void randomizeNeuron(Neuron n) { 105 | if (ai.maxlayers > n.layer + 1) { 106 | if (n.allowNegativeValues()) { 107 | n.setWeight((Math.random() * 2) - 1); 108 | n.setThreshold((Math.random() * 2) - 1); 109 | } else { 110 | n.setWeight((Math.random())); 111 | n.setThreshold((Math.random())); 112 | } 113 | for (Neuron output : ai.getNeuronsInLayer(n.layer + 1)) { 114 | if (n.allowNegativeValues()) 115 | n.setStrengthForNeuron(output, (Math.random() * 2) - 1); 116 | else 117 | n.setStrengthForNeuron(output, (Math.random())); 118 | } 119 | } 120 | } 121 | 122 | public boolean[] tickAndThink() { 123 | return ai.think(); 124 | } 125 | 126 | public NNBaseEntity clone() { 127 | return null; 128 | } 129 | 130 | public Controler getControler() { 131 | return controler; 132 | } 133 | 134 | public boolean shouldLearn() { 135 | return shouldLearn; 136 | } 137 | 138 | public void setShouldLearn(boolean b) { 139 | shouldLearn = b; 140 | } 141 | 142 | public void setNeuronsPerRow(int row, int amount) { 143 | getAI().setNeuronsPerRow(row, amount); 144 | } 145 | 146 | public int getNeuronsPerRow(int row) { 147 | return getAI().getNeuronsPerRow(row); 148 | } 149 | 150 | public NNAI getAI() { 151 | return ai; 152 | } 153 | 154 | public NNBaseEntity(Map map) { 155 | this.ai = (NNAI) map.get("ai"); 156 | this.ai.entity = this; 157 | if (map.containsKey("c")) { 158 | this.controler = (Controler) map.get("c"); 159 | } else if (this instanceof Controler) { 160 | this.controler = (Controler) this; 161 | } 162 | } 163 | 164 | @Override 165 | public Map serialize() { 166 | Map m = new HashMap(); 167 | if (this.controler != this) 168 | m.put("c", controler); 169 | m.put("ai", ai); 170 | return m; 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/NeuralNetwork.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | 23 | import me.zombie_striker.neuralnetwork.grapher.Grapher; 24 | 25 | import org.bukkit.Bukkit; 26 | import org.bukkit.plugin.Plugin; 27 | import org.bukkit.scheduler.BukkitRunnable; 28 | import org.bukkit.scheduler.BukkitTask; 29 | 30 | public class NeuralNetwork { 31 | 32 | private Grapher grapher; 33 | private NNBaseEntity base; 34 | private BukkitTask runnable; 35 | private Plugin mainClass; 36 | 37 | private List messages = new ArrayList<>(); 38 | 39 | private boolean Asyncrunning = false; 40 | 41 | private boolean broadcastMessage = true; 42 | 43 | public NeuralNetwork(final Plugin mainClass) { 44 | this.mainClass = mainClass; 45 | new BukkitRunnable() { 46 | public void run() { 47 | if (broadcastMessage) { 48 | if (messages.size() > 0) { 49 | List s = new ArrayList<>(messages); 50 | messages.clear(); 51 | if (s.size() > 5) { 52 | Bukkit.getConsoleSender().sendMessage(s.get(0)); 53 | Bukkit.getConsoleSender().sendMessage(s.get(1)); 54 | Bukkit.getConsoleSender().sendMessage(s.get(2)); 55 | Bukkit.getConsoleSender().sendMessage(s.size() + " more..."); 56 | } else { 57 | for (String ss : s) { 58 | if (ss != null) 59 | Bukkit.getConsoleSender().sendMessage(ss); 60 | } 61 | } 62 | } 63 | } else { 64 | messages.clear(); 65 | } 66 | } 67 | }.runTaskTimer(mainClass, 1, 20); 68 | } 69 | 70 | /** 71 | * Returns the current NeurnalNetwork entity 72 | * 73 | * @param base 74 | */ 75 | public void setCurrentNeuralNetwork(NNBaseEntity base) { 76 | this.base = base; 77 | } 78 | 79 | /** 80 | * Returns the current Neural network entity. 81 | */ 82 | public NNBaseEntity getCurrentNeuralNetwork() { 83 | return base; 84 | } 85 | 86 | /** 87 | * Triggered controler#update once. 88 | */ 89 | public String triggerOnce() { 90 | String a = base.controler.update(); 91 | messages.add(a); 92 | return a; 93 | } 94 | 95 | /** 96 | * Triggered controler#update once. 97 | */ 98 | public String learn() { 99 | String a = base.controler.learn(); 100 | messages.add(a); 101 | return a; 102 | } 103 | 104 | /** 105 | * Starts a BukkitRunnable that will update the control every tick. Should be 106 | * used if the NN requires data from bukkit 107 | */ 108 | public void start() { 109 | if (this.runnable != null) { 110 | this.runnable.cancel(); 111 | this.runnable = null; 112 | } 113 | this.runnable = new BukkitRunnable() { 114 | @Override 115 | public void run() { 116 | triggerOnce(); 117 | } 118 | }.runTaskTimer(this.mainClass, 0, 1); 119 | } 120 | 121 | /** 122 | * Starts training the neural network. Note that this NN should not make any 123 | * calls to Bukkit while training. 124 | */ 125 | public void startLearningAsynchronously() { 126 | getCurrentNeuralNetwork().setShouldLearn(true); 127 | if (this.runnable != null) { 128 | this.runnable.cancel(); 129 | this.runnable = null; 130 | } 131 | Asyncrunning = true; 132 | this.runnable = new BukkitRunnable() { 133 | @Override 134 | public void run() { 135 | while (getCurrentNeuralNetwork().shouldLearn()) { 136 | learn(); 137 | System.out.println("Running again"); 138 | } 139 | } 140 | }.runTaskAsynchronously(this.mainClass); 141 | } 142 | 143 | /** 144 | * Starts training the neural network. Note that this NN should not make any 145 | * calls to Bukkit while training. 146 | */ 147 | public void startLearningAsynchronouslyONCE() { 148 | getCurrentNeuralNetwork().setShouldLearn(true); 149 | if (this.runnable != null) { 150 | this.runnable.cancel(); 151 | this.runnable = null; 152 | } 153 | Asyncrunning = true; 154 | this.runnable = new BukkitRunnable() { 155 | @Override 156 | public void run() { 157 | learn(); 158 | stopLearning(); 159 | this.cancel(); 160 | } 161 | }.runTaskAsynchronously(this.mainClass); 162 | } 163 | 164 | /** 165 | * Starts training the neural network. Note that this this is slower than Async 166 | * learning and may cause some lag on the server. 167 | */ 168 | public void startLearningSynchronously() { 169 | getCurrentNeuralNetwork().setShouldLearn(true); 170 | if (this.runnable != null) { 171 | this.runnable.cancel(); 172 | this.runnable = null; 173 | } 174 | this.runnable = new BukkitRunnable() { 175 | @Override 176 | public void run() { 177 | learn(); 178 | } 179 | }.runTaskTimer(this.mainClass, 0, 1); 180 | } 181 | 182 | /** 183 | * Starts training the neural network. Note that this this is slower than Async 184 | * learning and may cause some lag on the server. 185 | */ 186 | public void startLearningSynchronouslyONCE() { 187 | getCurrentNeuralNetwork().setShouldLearn(true); 188 | if (this.runnable != null) { 189 | this.runnable.cancel(); 190 | this.runnable = null; 191 | } 192 | this.runnable = new BukkitRunnable() { 193 | @Override 194 | public void run() { 195 | learn(); 196 | } 197 | }.runTask(this.mainClass); 198 | } 199 | 200 | /** 201 | * Starts training the neural network. Note that this NN should not make any 202 | * calls to Bukkit while training. 203 | */ 204 | public void stopLearning() { 205 | stop(); 206 | getCurrentNeuralNetwork().setShouldLearn(false); 207 | } 208 | 209 | /** 210 | * Starts an *Asynchronously* BukkitRunnable that will update the control every 211 | * tick. Should be used for training the NN with data not a part of bukkit. 212 | */ 213 | public void startAsynchronously() { 214 | if (this.runnable != null) { 215 | this.runnable.cancel(); 216 | this.runnable = null; 217 | } 218 | Asyncrunning = true; 219 | this.runnable = new BukkitRunnable() { 220 | @Override 221 | public void run() { 222 | while (Asyncrunning) { 223 | triggerOnce(); 224 | } 225 | } 226 | }.runTaskLaterAsynchronously(this.mainClass, 1); 227 | } 228 | 229 | /** 230 | * Stops the BukkitRunnable. 231 | */ 232 | public void stop() { 233 | Asyncrunning = false; 234 | if (runnable != null) { 235 | this.runnable.cancel(); 236 | this.runnable = null; 237 | } 238 | } 239 | 240 | /** 241 | * Opens the NeuralGrapher. Use this to visualize all the neurons. 242 | */ 243 | public void openGrapher() { 244 | if (grapher == null) { 245 | grapher = Grapher.initGrapher(); 246 | } else { 247 | grapher.reOpenGUI(); 248 | } 249 | grapher.setNN(this); 250 | } 251 | 252 | /** 253 | * Closes the NeuralGrapher window. 254 | */ 255 | public void closeGrapher() { 256 | if (grapher != null) 257 | grapher.stopIt(); 258 | // this.grapher = null; 259 | } 260 | 261 | public Grapher getGrapher() { 262 | return grapher; 263 | } 264 | 265 | public boolean isBeingBroadcasted() { 266 | return broadcastMessage; 267 | } 268 | 269 | public void setBroadcasting(boolean b) { 270 | broadcastMessage = b; 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/SIOMemoryHolder.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork; 2 | 3 | import java.util.HashMap; 4 | 5 | public class SIOMemoryHolder { 6 | 7 | public HashMap inputValues; 8 | public HashMap previousOutputValues; 9 | public HashMap suggestOutputValues; 10 | 11 | private boolean requireAllNeuronsTrainWithThis = false; 12 | 13 | public SIOMemoryHolder(HashMap in, HashMap out, 14 | HashMap suggested) { 15 | this.inputValues = in; 16 | this.previousOutputValues = out; 17 | this.suggestOutputValues = suggested; 18 | } 19 | 20 | public SIOMemoryHolder(HashMap in, HashMap suggested) { 21 | this.inputValues = in; 22 | this.suggestOutputValues = suggested; 23 | } 24 | 25 | public void updatePreviousOutputs(HashMap newOutput) { 26 | this.previousOutputValues = newOutput; 27 | } 28 | public boolean needsToUse(){ 29 | return requireAllNeuronsTrainWithThis; 30 | } 31 | public void setNeedToUse(boolean b) { 32 | this.requireAllNeuronsTrainWithThis = b; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/grapher/Grapher.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.grapher; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.awt.*; 21 | import java.awt.image.BufferedImage; 22 | import java.util.Collection; 23 | 24 | import javax.swing.JFrame; 25 | import javax.swing.JPanel; 26 | 27 | import me.zombie_striker.neuralnetwork.*; 28 | import me.zombie_striker.neuralnetwork.neurons.Neuron; 29 | import me.zombie_striker.neuralnetwork.neurons.OutputNeuron; 30 | 31 | public class Grapher extends JPanel implements Runnable { 32 | 33 | /** 34 | * 35 | */ 36 | private static final long serialVersionUID = 2519755633786585583L; 37 | 38 | JFrame frame; 39 | Thread thread; 40 | 41 | public Collection allNeurons; 42 | 43 | NeuralNetwork nn; 44 | 45 | final static int WIDTH = 1000; 46 | final static int HEIGHT = 1000; 47 | 48 | int vsHeight = 50; 49 | int vsWidth = 10; 50 | int tileSize = 25; 51 | 52 | int onHeight = 50; 53 | int onWidth = 450; 54 | 55 | final int spacing = 20; 56 | final int height_spacing = 10; 57 | 58 | final int init_gray = 100; 59 | 60 | public boolean running = true; 61 | 62 | public void setNN(NeuralNetwork n) { 63 | this.nn = n; 64 | } 65 | 66 | public static Grapher initGrapher() { 67 | final Grapher grapher = new Grapher(); 68 | grapher.initvars(); 69 | return grapher; 70 | } 71 | 72 | public void reOpenGUI() { 73 | running = true; 74 | initvars(); 75 | } 76 | 77 | private void initvars() { 78 | this.thread = new Thread(this); 79 | this.frame = new JFrame("Neuron Grapher v0.4"); 80 | // grapher.frame.add(grapher); 81 | this.thread.start(); 82 | this.setSize(new Dimension(WIDTH, HEIGHT)); 83 | this.frame.setSize(new Dimension(WIDTH, HEIGHT)); 84 | this.frame.setPreferredSize(new Dimension(WIDTH, HEIGHT)); 85 | 86 | this.frame.setContentPane(this); 87 | this.frame.setVisible(true); 88 | // grapher.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 89 | this.frame.setResizable(true); 90 | this.frame.pack(); 91 | } 92 | 93 | public void stopIt() { 94 | running = false; 95 | } 96 | 97 | @SuppressWarnings({ "static-access", "deprecation" }) 98 | @Override 99 | public void run() { 100 | running = true; 101 | while (running) { 102 | try { 103 | BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); 104 | Graphics2D graphics = (Graphics2D) bi.getGraphics(); 105 | graphics.fillRect(0, 0, bi.getWidth(), bi.getHeight()); 106 | 107 | int space_layer = 20; 108 | int space_neuron = 10; 109 | if (this.nn == null || this.nn.getCurrentNeuralNetwork() == null) { 110 | // If there is no neural network, stop trying to find it. 111 | // One second delays should be fine for performance 112 | try { 113 | Graphics2D thisGraph = (Graphics2D) getGraphics(); 114 | if (thisGraph != null) 115 | thisGraph.drawImage(bi, 0, 0, frame.getWidth(), frame.getHeight(), null); 116 | thread.sleep(1000L); 117 | } catch (InterruptedException e) { 118 | e.printStackTrace(); 119 | } 120 | continue; 121 | } 122 | 123 | int offset = 0; 124 | boolean firstRow = true; 125 | int colorOffset = 1; 126 | for (int layerId = 0; layerId < this.nn.getCurrentNeuralNetwork().getAI().maxlayers; layerId++) { 127 | int cc = init_gray + (8 * colorOffset); 128 | Layer layer = this.nn.getCurrentNeuralNetwork().getAI().getLayer(layerId); 129 | if (layer.getNeuronsPerRow() > 0) { 130 | graphics.setColor(new Color(cc, cc, cc)); 131 | int expectedOffset = (int) (space_layer 132 | * (((double) this.nn.getCurrentNeuralNetwork().getAI().getNeuronsInLayer(layerId).size() 133 | / layer.getNeuronsPerRow()) + 2)); 134 | graphics.fillRect(firstRow ? 0 : offset, 0, expectedOffset, 1000); 135 | firstRow = false; 136 | offset += expectedOffset; 137 | } else { 138 | graphics.setColor(new Color(cc, cc, cc)); 139 | graphics.fillRect(firstRow ? 0 : offset, 0, (space_layer * 2), 1000); 140 | firstRow = false; 141 | offset += space_layer * 2; 142 | } 143 | colorOffset++; 144 | } 145 | // TODO:Tempfix 146 | int cc = init_gray + (8 * (colorOffset + 2)); 147 | graphics.setColor(new Color(cc, cc, cc)); 148 | graphics.fillRect(offset, 0, 1920 - offset, 1000); 149 | 150 | int layeroffset = 0; 151 | 152 | for (Layer layer : this.nn.getCurrentNeuralNetwork().getAI().getLayers()) { 153 | for (int i = 0; i < layer.neuronsInLayer.size(); i++) { 154 | Neuron n = layer.neuronsInLayer.get(i); 155 | // TODO: Make it not rely on bot guesser 156 | if (layer.getNeuronsPerRow() > 0 && i % (layer.getNeuronsPerRow()) == 0) 157 | layeroffset++; 158 | int cs = 0; 159 | int cw = (int) (((n.getWeight()) * 255 / 2) + 255 / 2); 160 | if (cw < 0) 161 | cw = 0; 162 | if (cw > 255) 163 | cw = 255; 164 | 165 | if (n.isTraining()) { 166 | graphics.setColor(new Color(100, 255, 255)); 167 | graphics.fillRect((space_layer * (layer.getLayer() + layeroffset) + 3) - 3, 168 | (space_neuron 169 | * (layer.getNeuronsPerRow() > 0 ? (i % layer.getNeuronsPerRow()) : i % 100) 170 | + height_spacing) - 3, 171 | (6 / 2) + (6), 6 + (6)); 172 | } 173 | 174 | graphics.setColor(new Color(255 - cw, cw, 0)); 175 | graphics.fillRect(space_layer * (layer.getLayer() + layeroffset) + 3, 176 | space_neuron * (layer.getNeuronsPerRow() > 0 ? (i % layer.getNeuronsPerRow()) : i % 100) 177 | + height_spacing, 178 | 6 / 2, 6); 179 | if (n.isTriggered()) { 180 | if (n.getTriggeredStength() == 0) { 181 | graphics.setColor(new Color(80, 45, 80)); 182 | } else { 183 | cs = (int) (((n.getTriggeredStength()) * 255 / 2) + 255 / 2); 184 | if (cs < 0) 185 | cs = 0; 186 | if (cs > 255) 187 | cs = 255; 188 | graphics.setColor(new Color(255 - cs, cs, 0)); 189 | } 190 | } else { 191 | graphics.setColor(new Color(0, 10, 0)); 192 | } 193 | graphics.fillRect(space_layer * (layer.getLayer() + layeroffset), 194 | space_neuron * (layer.getNeuronsPerRow() > 0 ? (i % layer.getNeuronsPerRow()) : i % 100) 195 | + height_spacing, 196 | 6 / 2, 6); 197 | 198 | if (layer.getLayer() == nn.getCurrentNeuralNetwork().getAI().maxlayers - 1) { 199 | // If they are output neurons: 200 | if (n instanceof OutputNeuron) { 201 | OutputNeuron on = (OutputNeuron) n; 202 | if (on.hasName()) { 203 | if (on.isTriggered()) { 204 | cs = (int) (((n.getTriggeredStength()) * 255 / 2) + 255 / 2); 205 | if (cs < 0) 206 | cs= 0; 207 | if (cs > 255) 208 | cs = 255; 209 | graphics.setColor(new Color(255 - cs, cs, 0)); 210 | } else { 211 | graphics.setColor(new Color(230, 230, 230)); 212 | } 213 | graphics.drawString(on.getName() + " - " + on.getTriggeredStength(), 214 | space_layer * (layer.getLayer() + layeroffset + 1) + 3, 215 | space_neuron 216 | * (layer.getNeuronsPerRow() > 0 ? (i % layer.getNeuronsPerRow()) 217 | : i % 100) 218 | + height_spacing + 6); 219 | } 220 | } 221 | } 222 | } 223 | layeroffset++; 224 | } 225 | 226 | // int finalLossGraphXOffset = space_layer * 227 | // (this.nn.getCurrentNeuralNetwork().getAI().maxlayers+ layeroffset+1)+3 + 200; 228 | 229 | // graphics.setColor(new Color(230,230,230)); 230 | 231 | Graphics2D thisGraph = (Graphics2D) getGraphics(); 232 | if (thisGraph != null) 233 | thisGraph.drawImage(bi, 0, 0, WIDTH, HEIGHT, null); 234 | 235 | try { 236 | thread.sleep(33L); 237 | } catch (InterruptedException e) { 238 | e.printStackTrace(); 239 | } 240 | 241 | } catch (Exception e) { 242 | e.printStackTrace(); 243 | } 244 | } 245 | frame.setVisible(false); 246 | frame.dispose(); 247 | thread.stop(); 248 | } 249 | 250 | /* 251 | * @Override public void run() { running=true; while (running) { try { 252 | * BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, 253 | * BufferedImage.TYPE_INT_RGB); Graphics2D graphics = (Graphics2D) 254 | * bi.getGraphics(); graphics.fillRect(0, 0, bi.getWidth(), bi.getHeight()); if 255 | * (view != null) { int tiles = ((view.viewdistance * 2) + 1); int[][] 256 | * tileScanTypes = new int[tiles][tiles]; int outputNeurons = 0; 257 | * 258 | * if (allNeurons != null) { for (Neuron n : allNeurons) { if (n instanceof 259 | * OutputMotorNeuron) { graphics.setColor(new Color(0, 0, 0)); 260 | * graphics.fillRect(onWidth - 1, onHeight - 1+ (((OutputMotorNeuron) 261 | * n).responceid * (tileSize + spacing)), tileSize + 2, tileSize + 2); 262 | * if(n.input.size()==0){ graphics.setColor(new Color(110, 110, 110)); }else if 263 | * (n.isTriggered()) { graphics.setColor(new Color(240, 240, 240)); } else { 264 | * graphics.setColor(new Color(160 , 160, 160)); } graphics.fillRect( onWidth, 265 | * onHeight 266 | * 267 | * + (((OutputMotorNeuron) n).responceid * (tileSize + spacing)), tileSize , 268 | * tileSize); } else if (n instanceof InputNeuron) { if (n instanceof 269 | * InputMobNeuron) { tileScanTypes[((InputNeuron) n).xlink][((InputNeuron) 270 | * n).ylink] = 1; } else if (n instanceof InputBlockNeuron) { 271 | * tileScanTypes[((InputNeuron) n).xlink][((InputNeuron) n).ylink] = 2; } } } } 272 | * for (int w = 0; w < view.universe.length; w++) { for (int h = 0; h < 273 | * view.universe[w].length; h++) { if (view.universe[w][h] != null) { int r = 0; 274 | * int g = 0; int b = 0; if (view.universe[w][h] instanceof Block) g = 160; if 275 | * (view.universe[w][h] instanceof Entity) r = 160; if (tileScanTypes[w][h] == 276 | * 1) r += 80; if (tileScanTypes[w][h] == 2) g += 80; 277 | * 278 | * graphics.setColor(new Color(r, g, b)); graphics.fillRect(vsWidth + (w * 279 | * tileSize), vsHeight + (h * tileSize), tileSize, tileSize); } } } 280 | * graphics.setColor(new Color(0, 0, 0)); for (int Lines = 0; Lines < tiles + 1; 281 | * Lines++) { graphics.drawLine(vsWidth + (tileSize * Lines), vsHeight, vsWidth 282 | * + (tileSize * Lines), vsHeight + (tileSize * tiles)); 283 | * graphics.drawLine(vsWidth, vsHeight + (tileSize * Lines), vsWidth + (tileSize 284 | * * tiles), vsHeight + (tileSize * Lines)); } graphics.drawString( 285 | * "Generation ="+Test.test.generation+" || Active Geneome =" 286 | * +Test.test.activePop 287 | * +" || Current score ="+(Test.test.current!=null?Test.test 288 | * .current.ai.score:-1),30, 10); } 289 | * 290 | * if (allNeurons != null) { for (Neuron n : allNeurons) { if (n instanceof 291 | * OutputMotorNeuron) { for (Neuron inputs : n.ai.getNeuronsFromId(n.input)) { 292 | * int r = 0; int g = 0; int b = 0; // Make the colors darker for lines if 293 | * (inputs instanceof InputBlockNeuron) g = 160 + (inputs.isTriggered() ? 80 : 294 | * 0) - 30; if (inputs instanceof InputMobNeuron) r = 160 + 295 | * (inputs.isTriggered() ? 80 : 0) - 30; if (inputs instanceof 296 | * OutputMotorNeuron) b = 160 + (inputs.isTriggered() ? 80 : 0) - 30; 297 | * 298 | * graphics.setColor(new Color(r, g, b)); if (inputs instanceof InputNeuron) { 299 | * graphics.drawLine( vsWidth + (tileSize / 2) + (((InputNeuron) inputs).xlink * 300 | * tileSize), vsHeight + (tileSize / 2) + (((InputNeuron) inputs).ylink * 301 | * tileSize), onWidth + (tileSize / 2), onHeight + (tileSize / 2) + 302 | * (((OutputMotorNeuron) n).responceid * (tileSize + spacing))); }else if 303 | * (inputs instanceof OutputMotorNeuron){ int direction = (((OutputMotorNeuron) 304 | * inputs).responceid-((OutputMotorNeuron) n).responceid); int 305 | * directionNormalized = (direction)/(direction<0?-direction:direction); 306 | * graphics.drawLine(onWidth + (tileSize / 2), onHeight + (tileSize / 2) + 307 | * (((OutputMotorNeuron) inputs).responceid * (tileSize + spacing)), onWidth + 308 | * (tileSize / 2) +(direction*(spacing)+(directionNormalized*tileSize)), 309 | * onHeight + (tileSize / 2) + (((OutputMotorNeuron) inputs).responceid * 310 | * (tileSize + spacing))); graphics.drawLine(onWidth + (tileSize / 2), onHeight 311 | * + (tileSize / 2) + (((OutputMotorNeuron) n).responceid * (tileSize + 312 | * spacing)), onWidth + (tileSize / 2) 313 | * +((direction*(spacing)+(directionNormalized*tileSize))), onHeight + (tileSize 314 | * / 2) + (((OutputMotorNeuron) n).responceid * (tileSize + spacing))); 315 | * 316 | * graphics.drawLine(onWidth + (tileSize / 2) 317 | * +(direction*(spacing)+(directionNormalized*tileSize)), onHeight + (tileSize / 318 | * 2) + (((OutputMotorNeuron) inputs).responceid * (tileSize + spacing)), 319 | * onWidth + (tileSize / 2) 320 | * +(direction*(spacing)+(directionNormalized*tileSize)), onHeight + (tileSize / 321 | * 2) + (((OutputMotorNeuron) n).responceid * (tileSize + spacing))); } } } } } 322 | * Graphics2D thisGraph = (Graphics2D) getGraphics(); if (thisGraph != null) 323 | * thisGraph.drawImage(bi, 0, 0, 1600, 800, null); 324 | * 325 | * try { thread.sleep(100L); } catch (InterruptedException e) { 326 | * e.printStackTrace(); } 327 | * 328 | * } catch (Exception e) { e.printStackTrace(); } } frame.setVisible(false); 329 | * frame.dispose(); thread.stop(); } 330 | */ 331 | public void addNotify() { 332 | super.addNotify(); 333 | if (thread == null) { 334 | thread = new Thread(this); 335 | thread.start(); 336 | } 337 | } 338 | 339 | } 340 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/neurons/BiasNeuron.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.neurons; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.Map; 21 | 22 | import me.zombie_striker.neuralnetwork.NNAI; 23 | 24 | public class BiasNeuron extends Neuron{ 25 | 26 | public BiasNeuron(NNAI ai, int layer) { 27 | super(ai, layer); 28 | } 29 | @Override 30 | public double getTriggeredStength() { 31 | if(droppedOut()) 32 | return 0; 33 | return 1; 34 | } 35 | @Override 36 | public boolean isTriggered() { 37 | if(droppedOut()) 38 | return false; 39 | if(!useThreshold()) 40 | return true; 41 | return getThreshold() < 0.5; 42 | } 43 | public Neuron generateNeuron(NNAI ai) { 44 | return BiasNeuron.generateNeuronStatically(ai, this.layer); 45 | } 46 | 47 | public static BiasNeuron generateNeuronStatically(NNAI ai, int layer) { 48 | return new BiasNeuron(ai, layer); 49 | } 50 | @Override 51 | public double forceTriggerStengthUpdate() { 52 | this.tickUpdated = getAI().getCurrentTick(); 53 | return lastResult = 1; 54 | } 55 | public BiasNeuron(Map map) { 56 | super(map); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/neurons/OutputNeuron.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.neurons; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.Map; 21 | 22 | import me.zombie_striker.neuralnetwork.NNAI; 23 | 24 | public class OutputNeuron extends Neuron { 25 | 26 | public int responceid; 27 | private String name; 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String n) { 34 | name = n; 35 | } 36 | 37 | public boolean hasName() { 38 | return name != null; 39 | } 40 | 41 | public OutputNeuron(NNAI ai, int responceid) { 42 | super(ai, ai.maxlayers - 1); 43 | this.responceid = responceid; 44 | } 45 | 46 | public OutputNeuron(NNAI ai, int responceid, int layer) { 47 | super(ai, layer); 48 | this.responceid = responceid; 49 | } 50 | 51 | @Override 52 | public Neuron generateNeuron(NNAI ai) { 53 | OutputNeuron n = new OutputNeuron(ai, responceid); 54 | return n; 55 | } 56 | 57 | @Override 58 | public Neuron clone(NNAI ai) { 59 | OutputNeuron clone = (OutputNeuron) generateNeuron(ai); 60 | clone.responceid = responceid; 61 | return clone; 62 | } 63 | 64 | @Override 65 | public boolean isTriggered() { 66 | if (allowNegativeValues()) 67 | return getTriggeredStength() > 0.0; 68 | else 69 | return getTriggeredStength() > 0.5; 70 | } 71 | 72 | public OutputNeuron(Map map) { 73 | super(map); 74 | this.name = (String) map.get("n"); 75 | this.responceid = (int) map.get("rid"); 76 | } 77 | 78 | @Override 79 | public Map serialize() { 80 | Map m = super.serialize();// new HashMap(); 81 | m.put("n", this.name); 82 | m.put("rid", this.responceid); 83 | return m; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/neurons/input/InputBlockNeuron.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.neurons.input; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import me.zombie_striker.neuralnetwork.NNAI; 21 | import me.zombie_striker.neuralnetwork.senses.Senses2D; 22 | import me.zombie_striker.neuralnetwork.senses.Sensory2D_Numbers; 23 | 24 | /** 25 | * DO NOT USE. Still updating! 26 | * 27 | * @author ZombieStriker 28 | * 29 | */ 30 | 31 | public class InputBlockNeuron extends InputNeuron { 32 | 33 | public InputBlockNeuron(NNAI ai, int xlink, int ylink, Sensory2D_Numbers sn) { 34 | this(ai, xlink, ylink, -1, sn); 35 | } 36 | 37 | public InputBlockNeuron(NNAI ai, int xlink, int ylink, int blockID, 38 | Sensory2D_Numbers sn) { 39 | super(ai, xlink, ylink,blockID, sn); 40 | } 41 | 42 | public InputBlockNeuron(NNAI ai, Sensory2D_Numbers sn) { 43 | super(ai); 44 | this.s = sn; 45 | } 46 | 47 | @Override 48 | public InputNeuron generateNeuron(NNAI ai, Senses2D n) { 49 | return InputBlockNeuron.generateNeuronStatically(ai, 0, 0, 50 | (Sensory2D_Numbers) n); 51 | } 52 | 53 | public static InputNeuron generateNeuronStatically(NNAI ai, int x, int y, 54 | Sensory2D_Numbers sn) { 55 | InputNeuron link = new InputBlockNeuron(ai, x, y, sn); 56 | return link; 57 | } 58 | 59 | @Override 60 | public boolean isTriggered() { 61 | if (tickUpdated == this.getAI().getCurrentTick()) 62 | return lastResult == 1; 63 | tickUpdated = this.getAI().getCurrentTick(); 64 | if ((zlink == -1 && ((Sensory2D_Numbers) s).getNumberAt(xlink, ylink) != 0) 65 | || ((Sensory2D_Numbers) s).getNumberAt(xlink, ylink) == zlink) { 66 | lastResult = 1; 67 | return true; 68 | } 69 | lastResult = 0; 70 | return false; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/neurons/input/InputBooleanNeuron.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.neurons.input; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.Map; 21 | 22 | import me.zombie_striker.neuralnetwork.NNAI; 23 | import me.zombie_striker.neuralnetwork.senses.*; 24 | 25 | public class InputBooleanNeuron extends InputNeuron { 26 | 27 | public InputBooleanNeuron(NNAI ai, Sensory2D_Booleans sl) { 28 | super(ai); 29 | this.s = sl; 30 | } 31 | 32 | public InputBooleanNeuron(NNAI ai, int row, int col, 33 | Sensory2D_Booleans sl) { 34 | super(ai, row, col,sl); 35 | this.s = sl; 36 | } 37 | 38 | @Override 39 | public InputNeuron generateNeuron(NNAI ai, Senses2D word) { 40 | return InputBooleanNeuron.generateNeuronStatically(ai, 0, ' ', 41 | (Sensory2D_Booleans) word); 42 | } 43 | 44 | public static InputNeuron generateNeuronStatically(NNAI ai, int row, 45 | int col, Sensory2D_Booleans sl) { 46 | InputNeuron link = new InputBooleanNeuron(ai, row, col, (Sensory2D_Booleans) sl); 47 | return link; 48 | } 49 | public InputBooleanNeuron(Map map) { 50 | super(map); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/neurons/input/InputLetterNeuron.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.neurons.input; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.Map; 21 | 22 | import me.zombie_striker.neuralnetwork.NNAI; 23 | import me.zombie_striker.neuralnetwork.senses.*; 24 | 25 | public class InputLetterNeuron extends InputNeuron { 26 | 27 | public static char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 28 | 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 29 | 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', 30 | '8', '9', '_' }; 31 | 32 | public char letter; 33 | 34 | public InputLetterNeuron(NNAI ai, Sensory2D_Letters sl) { 35 | super(ai); 36 | this.s = sl; 37 | } 38 | 39 | public InputLetterNeuron(NNAI ai, int index, int charr, 40 | Sensory2D_Letters sl) { 41 | super(ai, index, charr, sl); 42 | this.letter = letters[charr]; 43 | this.s = sl; 44 | } 45 | 46 | @Override 47 | public InputNeuron generateNeuron(NNAI ai, Senses2D word) { 48 | return InputLetterNeuron.generateNeuronStatically(ai, 0, ' ', 49 | (Sensory2D_Letters) word); 50 | } 51 | 52 | public static InputNeuron generateNeuronStatically(NNAI ai, int index, 53 | char letter, Sensory2D_Letters sl) { 54 | int index2 = 0; 55 | for(;index2 map) { 77 | super(map); 78 | this.letter= (map.get("char")+"").toCharArray()[0]; 79 | } 80 | @Override 81 | public Map serialize() { 82 | Map map = super.serialize(); 83 | map.put("char", letter); 84 | return map; 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/neurons/input/InputMobNeuron.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.neurons.input; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import me.zombie_striker.neuralnetwork.NNAI; 21 | import me.zombie_striker.neuralnetwork.senses.*; 22 | 23 | /** 24 | * DO NOT USE. Still updating! 25 | * @author ZombieStriker 26 | * 27 | */ 28 | public class InputMobNeuron extends InputNeuron { 29 | 30 | public InputMobNeuron(NNAI ai,Sensory2D_Numbers sn) { 31 | super(ai); 32 | this.s = sn; 33 | } 34 | 35 | public InputMobNeuron(NNAI ai, int xlink, int ylink, Sensory2D_Numbers sn) { 36 | super(ai,xlink,ylink,sn); 37 | this.s = sn; 38 | } 39 | 40 | @Override 41 | public InputNeuron generateNeuron(NNAI ai,Senses2D sn) { 42 | return InputMobNeuron.generateNeuronStatically(ai, (Sensory2D_Numbers) sn); 43 | } 44 | 45 | public static InputNeuron generateNeuronStatically(NNAI ai,Sensory2D_Numbers sn) { 46 | InputNeuron link = new InputMobNeuron(ai,sn); 47 | return link; 48 | } 49 | 50 | 51 | @Override 52 | public boolean isTriggered() { 53 | if(tickUpdated==this.getAI().getCurrentTick()){ 54 | return lastResult==1; 55 | } 56 | tickUpdated = this.getAI().getCurrentTick(); 57 | if (((Sensory2D_Numbers) s).getNumberAt(xlink,ylink) !=0) { 58 | lastResult=1; 59 | return true; 60 | } 61 | lastResult=0; 62 | return false; 63 | } 64 | 65 | 66 | } -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/neurons/input/InputNeuron.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.neurons.input; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.Map; 21 | 22 | import me.zombie_striker.neuralnetwork.NNAI; 23 | import me.zombie_striker.neuralnetwork.neurons.Neuron; 24 | import me.zombie_striker.neuralnetwork.senses.*; 25 | 26 | public class InputNeuron extends Neuron { 27 | 28 | public int xlink; 29 | public int ylink; 30 | public int zlink; 31 | 32 | public Senses s; 33 | 34 | public boolean isTriggeredLast = false; 35 | 36 | /// public Sensory_Vision entitiesVision; 37 | 38 | public InputNeuron(NNAI ai, int xlink, int ylink, int zlink, Senses s) { 39 | super(ai, 0); 40 | init(ai, xlink, ylink, zlink, s); 41 | } 42 | 43 | public InputNeuron(NNAI ai, int xlink, int ylink, Senses s) { 44 | super(ai, 0); 45 | init(ai, xlink, ylink, 0, s); 46 | } 47 | 48 | public InputNeuron(NNAI ai) { 49 | super(ai, 0); 50 | } 51 | 52 | private void init(NNAI ai, int xlink, int ylink, int zlink, Senses s) { 53 | this.xlink = xlink; 54 | this.ylink = ylink; 55 | this.zlink = zlink; 56 | this.s = s; 57 | } 58 | 59 | public void setIsTriggeredLast(boolean b) { 60 | this.isTriggeredLast = b; 61 | } 62 | 63 | public boolean getIsTriggeredLast() { 64 | return this.isTriggeredLast; 65 | } 66 | 67 | @Override 68 | public Neuron clone(NNAI ai) { 69 | InputNeuron n = (InputNeuron) super.clone(ai); 70 | n.xlink = xlink; 71 | n.ylink = ylink; 72 | return null; 73 | } 74 | 75 | public InputNeuron generateNeuron(NNAI ai, Senses2D sensory) { 76 | return null; 77 | } 78 | 79 | @Override 80 | public double forceTriggerStengthUpdate() { 81 | this.tickUpdated = getAI().getCurrentTick(); 82 | 83 | double i = 0; 84 | 85 | if (s instanceof Senses2D) 86 | i= lastResult = ((Senses2D) s).getPowerFor(xlink, ylink); 87 | if (s instanceof Senses3D) 88 | i= lastResult = ((Senses3D) s).getPowerFor(xlink, ylink, zlink); 89 | isTriggeredLast = i > 0; 90 | return i; 91 | } 92 | 93 | @Override 94 | public double getTriggeredStength() { 95 | if (this.tickUpdated == this.getAI().getCurrentTick()) 96 | return lastResult; 97 | if (s instanceof Senses2D) 98 | return lastResult = ((Senses2D) s).getPowerFor(xlink, ylink); 99 | if (s instanceof Senses3D) 100 | return lastResult = ((Senses3D) s).getPowerFor(xlink, ylink, zlink); 101 | return 0; 102 | } 103 | 104 | public Senses getSenses() { 105 | return s; 106 | } 107 | 108 | public void stSenses(Senses s) { 109 | this.s = s; 110 | } 111 | 112 | public InputNeuron(Map map) { 113 | super(map); 114 | this.xlink = map.containsKey("xl") ? (int) map.get("xl") : 0; 115 | this.ylink = map.containsKey("yl") ? (int) map.get("yl") : 0; 116 | this.zlink = map.containsKey("zl") ? (int) map.get("zl") : 0; 117 | this.s = (Senses) map.get("s"); 118 | } 119 | 120 | @Override 121 | public Map serialize() { 122 | Map m = super.serialize();// new HashMap(); 123 | if (this.xlink != 0) 124 | m.put("xl", this.xlink); 125 | if (this.ylink != 0) 126 | m.put("yl", this.ylink); 127 | if (this.zlink != 0) 128 | m.put("zl", this.zlink); 129 | m.put("s", this.s); 130 | return m; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/neurons/input/InputNumberNeuron.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.neurons.input; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.Map; 21 | 22 | import me.zombie_striker.neuralnetwork.NNAI; 23 | import me.zombie_striker.neuralnetwork.senses.*; 24 | 25 | public class InputNumberNeuron extends InputNeuron { 26 | 27 | public InputNumberNeuron(NNAI ai, Sensory2D_Numbers sl) { 28 | super(ai); 29 | this.s = sl; 30 | } 31 | 32 | public InputNumberNeuron(Map map) { 33 | super(map); 34 | } 35 | 36 | public InputNumberNeuron(NNAI ai, int row, int col, 37 | Sensory2D_Numbers sl) { 38 | super(ai, row, col,sl); 39 | this.s = sl; 40 | } 41 | 42 | @Override 43 | public InputNeuron generateNeuron(NNAI ai, Senses2D word) { 44 | return InputNumberNeuron.generateNeuronStatically(ai, 0, ' ', 45 | (Sensory2D_Numbers) word); 46 | } 47 | 48 | public static InputNeuron generateNeuronStatically(NNAI ai, int row, 49 | int col, Sensory2D_Numbers sl) { 50 | return new InputNumberNeuron(ai, row, col, (Sensory2D_Numbers) sl); 51 | } 52 | 53 | @Override 54 | public boolean isTriggered() { 55 | return getTriggeredStength()!=0; 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/neurons/input/InputTickNeuron.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.neurons.input; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import me.zombie_striker.neuralnetwork.NNAI; 21 | import me.zombie_striker.neuralnetwork.senses.*; 22 | 23 | /** 24 | * DO NOT USE. Still updating! 25 | * @author ZombieStriker 26 | * 27 | */ 28 | public class InputTickNeuron extends InputNeuron { 29 | 30 | int maxTick=0; 31 | 32 | public InputTickNeuron(NNAI ai,int maxtick) { 33 | super(ai); 34 | this.maxTick = maxtick; 35 | } 36 | 37 | public InputTickNeuron(NNAI ai, int row, int col, 38 | Sensory2D_Numbers sl) { 39 | super(ai, row, col,sl); 40 | } 41 | 42 | @Override 43 | public InputNeuron generateNeuron(NNAI ai, Senses2D word) { 44 | return InputTickNeuron.generateNeuronStatically(ai, 0); 45 | } 46 | 47 | public static InputNeuron generateNeuronStatically(NNAI ai, int maxTick) { 48 | InputNeuron link = new InputTickNeuron(ai, maxTick); 49 | return link; 50 | } 51 | 52 | @Override 53 | public double getTriggeredStength() { 54 | return ((/*(double)*/getAI().getCurrentTick()%maxTick)/*/maxTick*/)==0?1:0; 55 | } 56 | 57 | @Override 58 | public boolean isTriggered() { 59 | return getTriggeredStength()==1; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/senses/Senses.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.senses; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import org.bukkit.configuration.serialization.ConfigurationSerializable; 21 | 22 | public interface Senses extends ConfigurationSerializable{ 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/senses/Senses2D.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.senses; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | public interface Senses2D extends Senses{ 21 | public double getPowerFor(int x, int y); 22 | } 23 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/senses/Senses3D.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.senses; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | public interface Senses3D extends Senses{ 21 | public double getPowerFor(int x, int y, int z); 22 | } 23 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/senses/Sensory2D_Booleans.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.senses; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | public class Sensory2D_Booleans implements Senses2D{ 24 | 25 | @Override 26 | public double getPowerFor(int x, int y) { 27 | return values[x][y]?1:0; 28 | } 29 | 30 | private boolean[][] values; 31 | 32 | public Sensory2D_Booleans(int rows, int col) { 33 | this.values = new boolean[rows][col]; 34 | } 35 | 36 | public boolean getBooleanAt(int row, int col) { 37 | return values[row][col]; 38 | } 39 | 40 | public void changeMatrix(boolean[][] newValues) { 41 | this.values = newValues; 42 | } 43 | public boolean[][] getMatrix(){ 44 | return this.values; 45 | } 46 | public void changeValueAt(int x, int y, boolean value){ 47 | this.values[x][y]=value; 48 | } 49 | 50 | public Sensory2D_Booleans(Map map) { 51 | values = new boolean[(int) map.get("x")][(int) map.get("y")]; 52 | } 53 | 54 | @Override 55 | public Map serialize() { 56 | Map v = new HashMap(); 57 | v.put("x", values.length); 58 | v.put("y", values[0].length); 59 | return v; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/senses/Sensory2D_Letters.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.senses; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | import me.zombie_striker.neuralnetwork.neurons.input.InputLetterNeuron; 24 | 25 | public class Sensory2D_Letters implements Senses2D{ 26 | 27 | 28 | private char[] letters= InputLetterNeuron.letters; 29 | private String word="null"; 30 | private String fullWord="null"; 31 | public static final int MAX_LETTERS = 19; 32 | 33 | @Override 34 | public double getPowerFor(int x, int y) { 35 | //if(word.length()>x&&letters.length>y) 36 | return (fullWord.length()>x&&fullWord.charAt(x)==letters[y])?1:0; 37 | //return -1; 38 | } 39 | 40 | 41 | public Sensory2D_Letters(String word) { 42 | this.word = word; 43 | StringBuilder sb = new StringBuilder(); 44 | sb.append(word); 45 | for(int i = word.length(); i < MAX_LETTERS;i++){ 46 | sb.append(" "); 47 | } 48 | this.fullWord = sb.toString(); 49 | } 50 | 51 | public char getCharacterAt(int index) { 52 | if(fullWord==null)return ' '; 53 | try{ 54 | return fullWord.charAt(index); 55 | }catch(Exception e){ 56 | /** 57 | * Seriously, I have tried doing a length check, a null check. Do I seriously need to add a catch statement?> 58 | */ 59 | return ' '; 60 | } 61 | } 62 | public String getWord(){ 63 | return word; 64 | } 65 | public void changeWord(String word) { 66 | this.word = word; 67 | StringBuilder sb = new StringBuilder(); 68 | sb.append(word); 69 | for(int i = word.length(); i < MAX_LETTERS;i++){ 70 | sb.append(" "); 71 | } 72 | fullWord = sb.toString(); 73 | } 74 | public Sensory2D_Letters(Map map) { 75 | } 76 | 77 | @Override 78 | public Map serialize() { 79 | Map v = new HashMap(); 80 | return v; 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/senses/Sensory2D_Numbers.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.senses; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | public class Sensory2D_Numbers implements Senses2D{ 24 | 25 | @Override 26 | public double getPowerFor(int x, int y) { 27 | return values[x][y]; 28 | } 29 | 30 | private double[][] values; 31 | 32 | public Sensory2D_Numbers(int rows, int col) { 33 | this.values = new double[rows][col]; 34 | } 35 | 36 | public double getNumberAt(int row, int col) { 37 | return values[row][col]; 38 | } 39 | 40 | public void changeMatrix(double[][] newValues) { 41 | this.values = newValues; 42 | } 43 | public double[][] getMatrix(){ 44 | return this.values; 45 | } 46 | public void changeNumberAt(int x, int y, double value){ 47 | this.values[x][y]=value; 48 | } 49 | public Sensory2D_Numbers(Map map) { 50 | values = new double[(int) map.get("x")][(int) map.get("y")]; 51 | } 52 | 53 | @Override 54 | public Map serialize() { 55 | Map v = new HashMap(); 56 | v.put("x", values.length); 57 | v.put("y", values[0].length); 58 | return v; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/senses/Sensory3D_Booleans.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.senses; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | public class Sensory3D_Booleans implements Senses3D{ 24 | 25 | private boolean[][][] values; 26 | 27 | @Override 28 | public double getPowerFor(int x, int y,int z) { 29 | return values[x][y][z]?1:0; 30 | } 31 | 32 | public Sensory3D_Booleans(int x,int y,int z) { 33 | this.values = new boolean[x][y][z]; 34 | } 35 | 36 | public boolean getBooleanAt(int x,int y ,int z) { 37 | return values[x][y][z]; 38 | } 39 | 40 | public void changeMatrix(boolean[][][] newValues) { 41 | this.values = newValues; 42 | } 43 | public boolean[][][] getMatrix(){ 44 | return this.values; 45 | } 46 | public void changeValueAt(int x, int y,int z, boolean value){ 47 | this.values[x][y][z]=value; 48 | } 49 | public Sensory3D_Booleans(Map map) { 50 | values = new boolean[(int) map.get("x")][(int) map.get("y")][(int) map.get("z")]; 51 | } 52 | 53 | @Override 54 | public Map serialize() { 55 | Map v = new HashMap(); 56 | v.put("x", values.length); 57 | v.put("y", values[0].length); 58 | v.put("z", values[0][0].length); 59 | return v; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/senses/Sensory3D_Numbers.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.senses; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | public class Sensory3D_Numbers implements Senses3D{ 24 | 25 | private double[][][] values; 26 | 27 | @Override 28 | public double getPowerFor(int x, int y, int z) { 29 | return values[x][y][z]; 30 | } 31 | 32 | public Sensory3D_Numbers(int x, int y, int z) { 33 | this.values = new double[x][y][z]; 34 | } 35 | 36 | public double getNumberAt(int x,int y, int z) { 37 | return values[x][y][z]; 38 | } 39 | 40 | public void changeMatrix(double[][][] newValues) { 41 | this.values = newValues; 42 | } 43 | public double[][][] getMatrix(){ 44 | return this.values; 45 | } 46 | public void changeNumberAt(int x, int y,int z, double value){ 47 | this.values[x][y][z]=value; 48 | } 49 | public Sensory3D_Numbers(Map map) { 50 | values = new double[(int) map.get("x")][(int) map.get("y")][(int) map.get("z")]; 51 | } 52 | 53 | @Override 54 | public Map serialize() { 55 | Map v = new HashMap(); 56 | v.put("x", values.length); 57 | v.put("y", values[0].length); 58 | v.put("z", values[0][0].length); 59 | return v; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/util/Accuracy.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.util; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | public class Accuracy { 21 | 22 | boolean[] accuracy; 23 | int currentIndex = 0; 24 | double currentPrecent = 0; 25 | 26 | public Accuracy(int max_entries) { 27 | accuracy = new boolean[max_entries]; 28 | } 29 | 30 | public double getAccuracy() { 31 | return currentPrecent; 32 | } 33 | public int getAccuracyAsInt() { 34 | return (int)(getAccuracy()*100); 35 | } 36 | public void addEntry(boolean wasAccurate){ 37 | boolean oldone = accuracy[currentIndex]; 38 | accuracy[currentIndex]=wasAccurate; 39 | if(oldone!=wasAccurate){ 40 | currentPrecent+=(wasAccurate?1.0:-1.0)/accuracy.length; 41 | } 42 | currentIndex++; 43 | if(currentIndex==accuracy.length){ 44 | currentIndex=0; 45 | for(boolean b : accuracy){ 46 | if(b) 47 | currentPrecent+=1/accuracy.length; 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/util/LossHolder.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.util; 2 | 3 | public class LossHolder { 4 | 5 | int maxLossStored = 1; 6 | 7 | int lastIndex = -1; 8 | 9 | double[] lossTrack; 10 | 11 | int sizeOfStoredLosses = -1; 12 | 13 | public LossHolder(int entriesStored) { 14 | this.sizeOfStoredLosses = entriesStored; 15 | this.lossTrack = new double[entriesStored]; 16 | } 17 | 18 | public void storeNewLoss(double loss) { 19 | lastIndex=lastIndex++%sizeOfStoredLosses; 20 | lossTrack[lastIndex] = loss; 21 | } 22 | public double getLossAt(int index) { 23 | return this.lossTrack[index]; 24 | } 25 | public int getStartingIndex() { 26 | return (lastIndex+1)%sizeOfStoredLosses; 27 | } 28 | 29 | public void setNewLossHolder(int newSize) { 30 | this.sizeOfStoredLosses = newSize; 31 | this.lossTrack = new double[newSize]; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/util/MutationUtil.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.util; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | 21 | public class MutationUtil { 22 | //TODO: Commenting out, as no one should use it: 23 | 24 | /* 25 | private static final double MUTATION_CHANCE = 0.0; 26 | //TODO: Go back to 0.3. Right now, no mutations 27 | 28 | private static final double NEURON_SUICIDE_CHANCE = 0.25; 29 | private static final double NEURON_CREATION_CHANCE = 0.30; 30 | // Drop them from 0.20 each to .10 so the total for either change is 0.20 31 | private static final double NEURON_CONNECTION_MUTATION_CHANCE = 0.10; 32 | private static final double NEURON_CONNECTION_CREATION_MUTATION_CHANCE = 0.10; 33 | private static final double NEURON_CONNECTION_SUICIDE_MUTATION_CHANCE = 0.10; 34 | private static final double NEURON_LOCATION_X_MUTATION_CHANCE = 0.10; 35 | private static final double NEURON_LOCATION_Y_MUTATION_CHANCE = 0.10; 36 | private static final double NEURON_THRESHOLD_MUTATION_CHANCE = 0.10; 37 | private static final double NEURON_OUTPUT_STRENGTH_MUTATION_CHANCE = 0.10; 38 | private static final double CROSSOVER_DISJOINT_MUTATION_CHANCE = 0.20; 39 | 40 | private static boolean CREATE_INPUT_NEURONS = false; 41 | private static boolean CHANGE_XY_NEURONS = false; 42 | private static boolean CREATE_NEURONS = false; 43 | 44 | // For the roll section 45 | private static final double[] ARRAY_CONNECTION_CHANCE = new double[] { 46 | NEURON_CONNECTION_MUTATION_CHANCE, 47 | NEURON_CONNECTION_CREATION_MUTATION_CHANCE, 48 | NEURON_CONNECTION_SUICIDE_MUTATION_CHANCE }; 49 | 50 | public static boolean rollCrossoverMutation() { 51 | return Math.random() > 1 - CROSSOVER_DISJOINT_MUTATION_CHANCE; 52 | } 53 | 54 | public static void rollSuicide(NNAI ai) { 55 | if (Math.random() > 1 - NEURON_SUICIDE_CHANCE) { 56 | for (int i = 0; i < 10; i++) { 57 | // Ten chances to kill a neuron and see if it 58 | // survives. 59 | int neuron = getObjectByChance((ai.allNeurons.size() - 1)); 60 | if (ai.allNeurons.get(neuron) != null 61 | && !(ai.allNeurons.get(neuron) instanceof OutputNeuron)) { 62 | Bukkit.broadcastMessage("Neuron kill mutation!"); 63 | Neuron toRemove = ai.allNeurons.get(neuron); 64 | for (Neuron input : ai.getNeuronsFromId(toRemove.getInputs())) { 65 | input.getOutputs().remove(toRemove); 66 | } 67 | for (Neuron output : ai.getNeuronsFromId(toRemove.getOutputs())) { 68 | output.getInputs().remove(toRemove); 69 | } 70 | toRemove.getInputs().clear(); 71 | toRemove.getOutputs().clear(); 72 | ai.allNeurons.put(toRemove.getID(), null); 73 | ai.getNeuronsInLayer(toRemove.layer).remove(toRemove); 74 | break; 75 | } 76 | } 77 | } 78 | } 79 | 80 | private static int pickOnOf(int entires) { 81 | return (int) (Math.random() * entires); 82 | } 83 | 84 | public static void rollCreate(NNAI ai) { 85 | if (Math.random() > 1 - NEURON_CREATION_CHANCE && CREATE_NEURONS) { 86 | Neuron n = null; 87 | int pick = pickOnOf(2); 88 | if(!CREATE_INPUT_NEURONS){ 89 | n = Neuron.generateNeuronStatically(ai, 90 | (int) (Math.random() * (ai.MAX_LAYERS - 2)) + 1); 91 | } 92 | 93 | //We should not need to generate input neurons. All input neurons should already be there. 94 | 95 | /*switch (pick) { // 3 = cases 96 | case 0: 97 | n = Neuron.generateNeuronStatically(ai, 98 | (int) (Math.random() * (Layer.MAX_LAYERS - 2)) + 1); 99 | break; 100 | 101 | case 1: 102 | n = InputMobNeuron.generateNeuronStatically(ai); 103 | break; 104 | case 2: 105 | n = InputBlockNeuron.generateNeuronStatically(ai); 106 | break; 107 | }* 108 | if (n != null) { 109 | Bukkit.broadcastMessage("Neuron creation mutation! Type= " 110 | + pick + ". Neuron count=" + ai.allNeurons.size()); 111 | } 112 | } 113 | } 114 | 115 | /** 116 | * Mode 0 = Regular Mutation change 117 | * 118 | * Mode 1 = Add connection 119 | * 120 | * Mode 2 = Remove connection 121 | * 122 | * @param ai 123 | * @param modeToTestFor 124 | * 125 | public static void rollInOutMutationChance(NNAI ai, int modeToTestFor) { 126 | 127 | boolean shouldgo = false; 128 | if (Math.random() > 1 - ARRAY_CONNECTION_CHANCE[modeToTestFor]) 129 | shouldgo = true; 130 | 131 | if (shouldgo) { 132 | Neuron n = null; 133 | for (int tries = 0; tries < 10; tries++) { 134 | n = ai.allNeurons 135 | .get(getObjectByChance((ai.allNeurons.size() - 1))); 136 | if (n != null) 137 | break; 138 | } 139 | Bukkit.broadcastMessage("Neuron connection " 140 | + (modeToTestFor == 1 ? "addtion" 141 | : (modeToTestFor == 2 ? "removal" : "change")) 142 | + " mutation!"); 143 | if (modeToTestFor == 0 || modeToTestFor == 2) { 144 | if (n.getInputs().size() > 0) { 145 | for (int i = 0; i < 5; i++) { 146 | int chance = getObjectByChance((n.getInputs().size() - 1)); 147 | if (n.getInputs().toArray()[chance] != n 148 | && n.getInputs().toArray()[chance] != null) { 149 | n.getInputs().remove((Neuron) ai.allNeurons.get(chance)); 150 | ((Neuron) ai.allNeurons.get(chance)).getOutputs() 151 | .remove(n); 152 | break; 153 | } 154 | } 155 | } 156 | } 157 | if (modeToTestFor == 0 || modeToTestFor == 1) { 158 | // Neuron connection = n;// set to n just for the for loop 159 | // for (int i = 0; connection == n && connection != null 160 | // && i < 100; i++) { 161 | // // connection = (Neuron) ai.allNeurons 162 | // .get(getObjectByChance((ai.allNeurons.size() - 1))); 163 | 164 | // Only add a connection to the layer before, or after. 165 | 166 | boolean addToLastLayer = Math.random() > 0.5; 167 | addConnections(n, addToLastLayer); 168 | 169 | // } 170 | // n.input.add(connection.id); 171 | // connection.output.add(n.id); 172 | } 173 | } 174 | } 175 | 176 | public static void addConnections(Neuron n, boolean addToLastLayer) { 177 | Layer connectionLayer = n.getAI().layers.get(n.layer 178 | + (addToLastLayer ? -1 : +1)); 179 | if(connectionLayer==null)return; 180 | if(connectionLayer.neuronsInLayer.size()==0)return; 181 | Neuron randomNeuron = connectionLayer.neuronsInLayer.get((int) (Math 182 | .random() * connectionLayer.neuronsInLayer.size())); 183 | if (addToLastLayer) { 184 | n.getInputs().add(randomNeuron.getID()); 185 | randomNeuron.getOutputs().add(n.getID()); 186 | } else { 187 | n.getOutputs().add(randomNeuron.getID()); 188 | randomNeuron.getInputs().add(n.getID()); 189 | } 190 | } 191 | 192 | public static void rollXYChange(NNAI ai, boolean isY) { 193 | if(!CHANGE_XY_NEURONS)return; 194 | boolean shouldgo = false; 195 | if (isY) { 196 | if (Math.random() > 1 - NEURON_LOCATION_Y_MUTATION_CHANCE) 197 | shouldgo = true; 198 | } else { 199 | if (Math.random() > 1 - NEURON_LOCATION_X_MUTATION_CHANCE) 200 | shouldgo = true; 201 | } 202 | if (shouldgo) { 203 | // Do not do these mutation just yet. 204 | InputNeuron inputNeuron = null; 205 | int tries = 0; 206 | while (inputNeuron == null && tries < 100) { 207 | tries++; 208 | int neuron = getObjectByChance(ai.allNeurons.size() - 1); 209 | Neuron temp = (Neuron) ai.allNeurons.get(neuron); 210 | if (temp instanceof InputNeuron) { 211 | inputNeuron = (InputNeuron) temp; 212 | } 213 | } 214 | if (inputNeuron != null) { 215 | for (int i = 0; i < 5; i++) { 216 | if (isY) { 217 | //TODO: inputNeuron.ylink = getObjectByChance(((inputNeuron.entitiesVision.viewdistance * 2) + 1)); 218 | // if (inputNeuron.ylink < inputNeuron.entitiesVision.universe.length) 219 | // break; 220 | } else { 221 | // inputNeuron.xlink = getObjectByChance(((inputNeuron.entitiesVision.viewdistance * 2) + 1)); 222 | // if (inputNeuron.xlink < inputNeuron.entitiesVision.universe.length) 223 | // break; 224 | } 225 | } 226 | Bukkit.broadcastMessage("Neuron xlink mutation!"); 227 | } 228 | 229 | } 230 | } 231 | 232 | public static void rollThresholdChange(NNAI ai) { 233 | if (Math.random() > 1 - NEURON_THRESHOLD_MUTATION_CHANCE) { 234 | Neuron neuron = null; 235 | int tries = 0; 236 | while (neuron == null && tries < 100) { 237 | tries++; 238 | int neuroni = getObjectByChance(ai.allNeurons.size() - 1); 239 | neuron = (Neuron) ai.allNeurons.get(neuroni); 240 | } 241 | if (neuron != null) { 242 | //TODO: neuron.threshold = Math.random(); 243 | Bukkit.broadcastMessage("Neuron threshold mutation!"); 244 | } 245 | } 246 | } 247 | 248 | public static void rollOutputSignalChange(NNAI ai) { 249 | if (Math.random() > 1 - NEURON_OUTPUT_STRENGTH_MUTATION_CHANCE) { 250 | Neuron neuron = null; 251 | int tries = 0; 252 | while (neuron == null && tries < 100) { 253 | tries++; 254 | int neuroni = getObjectByChance(ai.allNeurons.size() - 1); 255 | neuron = (Neuron) ai.allNeurons.get(neuroni); 256 | } 257 | if (neuron != null) { 258 | //TODO:neuron.outputStength = (Math.random() * 2) - 1; 259 | Bukkit.broadcastMessage("Neuron signal output mutation!"); 260 | } 261 | } 262 | } 263 | 264 | public static void mutateGene(NNAI ai) { 265 | boolean first = true; 266 | 267 | while (first || Math.random() > 1 - MUTATION_CHANCE) { 268 | first = false; 269 | rollSuicide(ai); 270 | rollCreate(ai); 271 | rollOutputSignalChange(ai); 272 | rollThresholdChange(ai); 273 | for (int i = 0; i < ARRAY_CONNECTION_CHANCE.length; i++) 274 | rollInOutMutationChance(ai, i); 275 | for (int i = 0; i < 2; i++) 276 | rollXYChange(ai, i == 1); 277 | } 278 | } 279 | 280 | public static int getObjectByChance(int range) { 281 | return (int) ((Math.random() * range) + 0.5); 282 | } 283 | */ 284 | } 285 | -------------------------------------------------------------------------------- /src/me/zombie_striker/neuralnetwork/util/SigmoidUtil.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.neuralnetwork.util; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | public class SigmoidUtil { 21 | 22 | public static double sigmoidNumber(double input){ 23 | return 1/(1+Math.pow(Math.E,-input)); 24 | } 25 | public static double sigmoidNumberPosAndNeg(double input){ 26 | return (sigmoidNumber(input)*2)-1; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/me/zombie_striker/nnmain/GithubDependDownloader.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZombieStriker/NeuralNetworkAPI/0afbe586970bf8a3a161eaad917b76a001a53c2d/src/me/zombie_striker/nnmain/GithubDependDownloader.java -------------------------------------------------------------------------------- /src/me/zombie_striker/nnmain/GithubUpdater.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZombieStriker/NeuralNetworkAPI/0afbe586970bf8a3a161eaad917b76a001a53c2d/src/me/zombie_striker/nnmain/GithubUpdater.java -------------------------------------------------------------------------------- /src/me/zombie_striker/nnmain/HelpPages.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.nnmain; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import org.bukkit.ChatColor; 21 | 22 | public enum HelpPages { 23 | one(ChatColor.GOLD+"--==Description: Page 1/3 ==--", 24 | "NeuralNetworkAPI is a plugin aimed on adding NeuralNetworks to minecraft.", 25 | "Pages:", 26 | "-Desctipion (Current)", 27 | "-How to use", 28 | "-Commands" 29 | ), 30 | two(ChatColor.GOLD+"--==How to use: Page 2/3==--", 31 | "To start, select a neural network you wish to use by using \"/nn cnn \". To see all NN-Types, leave empty.", 32 | "Once you have selected a type, you need to train the neural network. Use \"/nn startlearning\" to start training.", 33 | "Once you feel the NN is good enough (you can check the console to see its accuracy), use \"/nn stoplearning\" to stop.", 34 | "To test the NN, use \"/nn test \" to test it." 35 | ), 36 | three(ChatColor.GOLD+"--==Commands: Page 3/3==--", 37 | "/nn help - Displays help pages", 38 | "/nn cnn (or createNewNN) - creates a new NN", 39 | "/nn openGrapher - Opens the neuron grapher gui (only useful for servers running on a person computer)", 40 | "/nn closeGrapher- closes grapher", 41 | "/nn startLearning - Starts training the NN", 42 | "/nn stoplearning - Stops training the nn", 43 | "/nn test - tests the NN givin the input", 44 | "/nn save - Saves the current to the config", 45 | "/nn load - Loads the NN from the config", 46 | "/nn list - Lists all saved NN from the config", 47 | "/nn triggeronce- Triggers the NN once, (does not change inputs)" 48 | ); 49 | 50 | String[] lines; 51 | private HelpPages(String... text) { 52 | this.lines = text; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/me/zombie_striker/nnmain/Main.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.nnmain; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | import java.io.File; 21 | import java.io.IOException; 22 | import java.util.*; 23 | 24 | import me.zombie_striker.neuralnetwork.*; 25 | import me.zombie_striker.neuralnetwork.neurons.*; 26 | import me.zombie_striker.neuralnetwork.neurons.input.*; 27 | import me.zombie_striker.neuralnetwork.senses.*; 28 | 29 | import org.bukkit.*; 30 | import org.bukkit.command.*; 31 | import org.bukkit.configuration.file.*; 32 | import org.bukkit.configuration.serialization.ConfigurationSerialization; 33 | import org.bukkit.event.Listener; 34 | import org.bukkit.plugin.java.JavaPlugin; 35 | 36 | import example.blackjack_helper.BlackJackHelper; 37 | import example.bot_guesser.BotGuesser; 38 | import example.logical.*; 39 | import example.music_bot.MusicBot; 40 | import example.number_adder.NumberAdder; 41 | import example.prime_number_guesser.PrimeNumberBot; 42 | import example.swearfilter.ExampleSwearListener; 43 | import example.swearfilter.SwearBot; 44 | 45 | public class Main extends JavaPlugin implements Listener { 46 | 47 | /** 48 | * This class is used to make a Neural Network figure out whether a username 49 | * is valid 50 | */ 51 | public void onLoad() { 52 | ConfigurationSerialization.registerClass(NNBaseEntity.class); 53 | ConfigurationSerialization.registerClass(NNAI.class); 54 | ConfigurationSerialization.registerClass(Layer.class); 55 | ConfigurationSerialization.registerClass(Senses.class); 56 | ConfigurationSerialization.registerClass(Controler.class); 57 | 58 | ConfigurationSerialization.registerClass(Senses2D.class); 59 | ConfigurationSerialization.registerClass(Senses3D.class); 60 | ConfigurationSerialization.registerClass(Sensory2D_Booleans.class); 61 | ConfigurationSerialization.registerClass(Sensory2D_Letters.class); 62 | ConfigurationSerialization.registerClass(Sensory2D_Numbers.class); 63 | ConfigurationSerialization.registerClass(Sensory3D_Booleans.class); 64 | ConfigurationSerialization.registerClass(Sensory3D_Numbers.class); 65 | 66 | ConfigurationSerialization.registerClass(Neuron.class); 67 | ConfigurationSerialization.registerClass(InputNeuron.class); 68 | ConfigurationSerialization.registerClass(InputBlockNeuron.class); 69 | ConfigurationSerialization.registerClass(InputBooleanNeuron.class); 70 | ConfigurationSerialization.registerClass(InputLetterNeuron.class); 71 | ConfigurationSerialization.registerClass(InputNumberNeuron.class); 72 | ConfigurationSerialization.registerClass(InputTickNeuron.class); 73 | ConfigurationSerialization.registerClass(OutputNeuron.class); 74 | ConfigurationSerialization.registerClass(BiasNeuron.class); 75 | 76 | ConfigurationSerialization.registerClass(LogicalAND.class); 77 | ConfigurationSerialization.registerClass(LogicalOR.class); 78 | ConfigurationSerialization.registerClass(LogicalXOR.class); 79 | ConfigurationSerialization.registerClass(LogicalXNOR.class); 80 | ConfigurationSerialization.registerClass(LogicalNAND.class); 81 | ConfigurationSerialization.registerClass(LogicalInverted.class); 82 | ConfigurationSerialization.registerClass(LogicalNOR.class); 83 | 84 | ConfigurationSerialization.registerClass(BlackJackHelper.class); 85 | ConfigurationSerialization.registerClass(NumberAdder.class); 86 | ConfigurationSerialization.registerClass(BotGuesser.class); 87 | ConfigurationSerialization.registerClass(PrimeNumberBot.class); 88 | ConfigurationSerialization.registerClass(MusicBot.class); 89 | ConfigurationSerialization.registerClass(SwearBot.class); 90 | } 91 | 92 | private FileConfiguration config; 93 | private File f = new File(getDataFolder(), "NNData.yml"); 94 | 95 | /** 96 | * If you are creating your own plugin using the NNAPI, do not use the 97 | * default NN. You should have your own class. 98 | */ 99 | private NeuralNetwork nn; 100 | 101 | protected static Main plugin; 102 | 103 | protected boolean enableMetrics = true; 104 | 105 | @Override 106 | public void onDisable() { 107 | plugin = null; 108 | if (getNn() != null && getNn().getGrapher() != null) 109 | getNn().closeGrapher(); 110 | clearAllRegisteredClasses(); 111 | } 112 | 113 | @Override 114 | public void onEnable() { 115 | // TODO: Remove these values. They were only needed back when the NNs 116 | // did not implement ConfigurationSerializable 117 | registerDemoEntity(BlackJackHelper.class); 118 | registerDemoEntity(PrimeNumberBot.class); 119 | registerDemoEntity(NumberAdder.class); 120 | registerDemoEntity(MusicBot.class); 121 | registerDemoEntity(BotGuesser.class); 122 | registerDemoEntity(SwearBot.class); 123 | registerDemoEntity(LogicalInverted.class); 124 | registerDemoEntity(LogicalOR.class); 125 | registerDemoEntity(LogicalAND.class); 126 | registerDemoEntity(LogicalXOR.class); 127 | registerDemoEntity(LogicalNAND.class); 128 | registerDemoEntity(LogicalNOR.class); 129 | registerDemoEntity(LogicalXNOR.class); 130 | 131 | nn = new NeuralNetwork(this); 132 | plugin = this; 133 | 134 | config = YamlConfiguration.loadConfiguration(f); 135 | Bukkit.getPluginManager().registerEvents( 136 | new ExampleSwearListener(getNn()), this); 137 | 138 | if (!getConfig().contains("enableStats")) { 139 | getConfig().set("enableStats", true); 140 | saveConfig(); 141 | } 142 | enableMetrics = getConfig().getBoolean("enableStats"); 143 | 144 | //new Updater(this, 280241); 145 | GithubUpdater.autoUpdate(this, "ZombieStriker","NeuralNetworkAPI","NeuralNetworkAPI.jar"); 146 | 147 | if (Bukkit.getPluginManager().getPlugin("PluginConstructorAPI") == null) 148 | // new DependencyDownloader(this, 276723); 149 | GithubDependDownloader.autoUpdate(this, 150 | new File(getDataFolder().getParentFile(), "PluginConstructorAPI.jar"), "ZombieStriker", 151 | "PluginConstructorAPI", "PluginConstructorAPI.jar"); 152 | /** 153 | * Everyone should want the most up to date version of the plugin, so 154 | * any improvements made (either with performance or through new 155 | * methods) should be welcome. Since it is rare that I will remove 156 | * anything, and even if I did, I would deprecate the methods for a long 157 | * period of time before I do, nothing should really break. 158 | */ 159 | if (enableMetrics) { 160 | /** 161 | * I use bStats metrics to monitor how many servers are using my 162 | * API. This does not send any personal/private information. This 163 | * only sends: 164 | * 165 | * the server version, Java version, 166 | * the plugin's version, 167 | * system architecture, 168 | * Core count, 169 | * 170 | * You can view the stats being collected at: 171 | * https://bstats.org/plugin/bukkit/NeuralNetworkAPI 172 | */ 173 | Metrics metrics = new Metrics(this); 174 | } 175 | } 176 | 177 | public static Main getMainClass() { 178 | return plugin; 179 | } 180 | 181 | private void b(List list, String input, String check) { 182 | if (check.toLowerCase().startsWith(input.toLowerCase())) 183 | list.add(check); 184 | } 185 | 186 | @Override 187 | public List onTabComplete(CommandSender sender, Command command, 188 | String alias, String[] args) { 189 | List list = new ArrayList<>(); 190 | if (args.length == 1) { 191 | b(list, args[0], "save"); 192 | b(list, args[0], "load"); 193 | b(list, args[0], "list"); 194 | b(list, args[0], "startlearning"); 195 | b(list, args[0], "stoplearning"); 196 | b(list, args[0], "start"); 197 | b(list, args[0], "stop"); 198 | b(list, args[0], "createNewNN"); 199 | b(list, args[0], "help"); 200 | b(list, args[0], "test"); 201 | } 202 | if (args.length == 2) { 203 | if (args[0].equalsIgnoreCase("load")) { 204 | for (String s : getConfig().getConfigurationSection( 205 | "NeuralNetworks").getKeys(false)) 206 | b(list, args[1], s); 207 | } else if (args[0].equalsIgnoreCase("createNewNN")) { 208 | for (Class c : getRegisteredDemoEntityClasses()) { 209 | b(list, args[1], c.getSimpleName()); 210 | } 211 | } 212 | } 213 | return list; 214 | } 215 | 216 | @Override 217 | public boolean onCommand(CommandSender sender, Command command, 218 | String label, String[] args) { 219 | if (args.length == 0 || args[0].equalsIgnoreCase("help")) { 220 | int page = 0; 221 | if (args.length > 1) { 222 | page = Integer.parseInt(args[1]) - 1; 223 | } 224 | String[] pages = HelpPages.values()[page].lines; 225 | for (String p : pages) { 226 | sender.sendMessage(p); 227 | } 228 | return true; 229 | } 230 | 231 | if (!sender.isOp()) { 232 | sender.sendMessage("Sorry, only OP players can access demo commands."); 233 | return true; 234 | } 235 | 236 | if (args[0].equalsIgnoreCase("createNewNN") 237 | || args[0].equalsIgnoreCase("cnn")) { 238 | if (args.length < 2) { 239 | sender.sendMessage("You must specify which NN you want to create. Choose one of the following:"); 240 | for (Class c : getRegisteredDemoEntityClasses()) { 241 | sender.sendMessage("-" + c.getSimpleName()); 242 | } 243 | return true; 244 | } 245 | NNBaseEntity base = null; 246 | for (Class c : getRegisteredDemoEntityClasses()) { 247 | if (args[1].equalsIgnoreCase(c.getSimpleName())) { 248 | try { 249 | try { 250 | base = (NNBaseEntity) c.getDeclaredConstructor( 251 | Boolean.TYPE).newInstance(true); 252 | } catch (Exception e) { 253 | // If it does not have a parameter for boolean 254 | // types, use default, empty constructor. 255 | base = (NNBaseEntity) c.getDeclaredConstructor() 256 | .newInstance(true); 257 | } 258 | } catch (Exception e) { 259 | e.printStackTrace(); 260 | } 261 | } 262 | } 263 | if (base == null) { 264 | sender.sendMessage("You need to provide a valid bot type. Choose one of the following."); 265 | for (Class c : getRegisteredDemoEntityClasses()) { 266 | sender.sendMessage("-" + c.getSimpleName()); 267 | } 268 | return true; 269 | } 270 | sender.sendMessage("Set the NN to " 271 | + base.getClass().getSimpleName()); 272 | this.getNn().setCurrentNeuralNetwork(base); 273 | return true; 274 | } 275 | if (args[0].equalsIgnoreCase("setNeuronsPerRow") 276 | || args[0].equalsIgnoreCase("snpr")) { 277 | try { 278 | this.getNn().getCurrentNeuralNetwork().getAI() 279 | .setNeuronsPerRow(0, Integer.parseInt(args[1])); 280 | } catch (Exception e) { 281 | sender.sendMessage("You must provide how many neurons should be displayed per row"); 282 | } 283 | return true; 284 | } 285 | 286 | if (args[0].equalsIgnoreCase("startlearning")) { 287 | getNn().startLearningAsynchronously(); 288 | sender.sendMessage("Starting learning"); 289 | return true; 290 | } 291 | if (args[0].equalsIgnoreCase("stoplearning")) { 292 | getNn().stopLearning(); 293 | sender.sendMessage("Stoped learning"); 294 | return true; 295 | } 296 | if (args[0].equalsIgnoreCase("stop")) { 297 | getNn().stop(); 298 | sender.sendMessage("Stopping"); 299 | return true; 300 | } 301 | if (args[0].equalsIgnoreCase("start")) { 302 | getNn().start(); 303 | sender.sendMessage("Starting"); 304 | return true; 305 | } 306 | if (args[0].equalsIgnoreCase("triggeronce")) { 307 | sender.sendMessage(getNn().triggerOnce()); 308 | return true; 309 | } 310 | 311 | if (args[0].equalsIgnoreCase("test")) { 312 | getNn().getCurrentNeuralNetwork().getControler() 313 | .setInputs(sender, args); 314 | sender.sendMessage(getNn().triggerOnce()); 315 | return true; 316 | } 317 | if (args[0].equalsIgnoreCase("openGrapher")) { 318 | getNn().openGrapher(); 319 | sender.sendMessage("Opeining Grapher"); 320 | return true; 321 | } 322 | if (args[0].equalsIgnoreCase("closeGrapher")) { 323 | getNn().closeGrapher(); 324 | sender.sendMessage("closing Grapher"); 325 | return true; 326 | } 327 | if (args[0].equalsIgnoreCase("save")) { 328 | if (args.length > 1) { 329 | String id = args[1]; 330 | config.set(id, getNn().getCurrentNeuralNetwork()); 331 | try { 332 | config.save(f); 333 | } catch (IOException e) { 334 | e.printStackTrace(); 335 | } 336 | sender.sendMessage("Saving the NN " + id); 337 | } else { 338 | sender.sendMessage("Provide a path for the NN"); 339 | } 340 | return true; 341 | } 342 | if (args[0].equalsIgnoreCase("load")) { 343 | if (args.length > 1) { 344 | String id = args[1]; 345 | if (!config.contains(id)) { 346 | sender.sendMessage("The path in the config is null."); 347 | return true; 348 | } 349 | NNBaseEntity b = (NNBaseEntity) config.get(id); 350 | if (b == null) { 351 | sender.sendMessage("The NN is null."); 352 | return true; 353 | } 354 | getNn().setCurrentNeuralNetwork(b); 355 | // nn.setCurrentNeuralNetwork(Save_Config.loadnn(this, base, 356 | // id)); 357 | sender.sendMessage("loading the NN " + id); 358 | } else { 359 | sender.sendMessage("Provide an id"); 360 | } 361 | return true; 362 | } 363 | return false; 364 | } 365 | 366 | private NeuralNetwork getNn() { 367 | return nn; 368 | } 369 | 370 | private static List> registeredDemoClasses = new ArrayList<>(); 371 | 372 | /** 373 | * THIS SHOULD ONLY BE USED BY OTHER PLUGINS IF YOU WANT TO TEST IT IN THE 374 | * DEMO MODE 375 | */ 376 | public static void registerDemeEntity(NNBaseEntity base) { 377 | registeredDemoClasses.add(base.getClass()); 378 | } 379 | 380 | /** 381 | * THIS SHOULD ONLY BE USED BY OTHER PLUGINS IF YOU WANT TO TEST IT IN THE 382 | * DEMO MODE 383 | */ 384 | public static void registerDemoEntity(Class base) { 385 | registeredDemoClasses.add(base); 386 | } 387 | 388 | /** 389 | * SHOULD NOT BE USED BY OTHER PLUGINS. 390 | */ 391 | public static List> getRegisteredDemoEntityClasses() { 392 | return new ArrayList<>(registeredDemoClasses); 393 | } 394 | 395 | /** 396 | * SHOULD NOT BE USED BY OTHER PLUGINS. 397 | */ 398 | @Deprecated 399 | public static void clearAllRegisteredClasses() { 400 | registeredDemoClasses.clear(); 401 | registeredDemoClasses = null; 402 | } 403 | 404 | } 405 | -------------------------------------------------------------------------------- /src/me/zombie_striker/nnmain/Save_Config.java: -------------------------------------------------------------------------------- 1 | package me.zombie_striker.nnmain; 2 | 3 | /** 4 | Copyright (C) 2017 Zombie_Striker 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | **/ 19 | 20 | 21 | import java.io.File; 22 | import java.io.IOException; 23 | 24 | import me.zombie_striker.neuralnetwork.*; 25 | import me.zombie_striker.neuralnetwork.neurons.*; 26 | import me.zombie_striker.neuralnetwork.neurons.input.*; 27 | 28 | import org.bukkit.configuration.ConfigurationSection; 29 | import org.bukkit.configuration.file.FileConfiguration; 30 | import org.bukkit.plugin.Plugin; 31 | 32 | @SuppressWarnings("unused") 33 | @Deprecated 34 | public class Save_Config{ 35 | 36 | public static NNBaseEntity loadn312n(Plugin main, NNBaseEntity base, String id) { 37 | ConfigurationSection nids = main.getConfig().getConfigurationSection( 38 | "NeuralNetworks." + id + ".neurons"); 39 | NNBaseEntity ent = base; 40 | 41 | int cId = main.getConfig().getInt("NeuralNetworks." + id + ".id"); 42 | int layers = main.getConfig().getInt("NeuralNetworks." + id + ".layers"); 43 | 44 | String senses = main.getConfig().getString("NeuralNetworks." + id + ".senses"); 45 | int i = 0; 46 | for(String s : senses.split("\\|")){ 47 | if(s.startsWith("vision")){ 48 | // ent.senses.add(new Sensory2D_Numbers(Integer.parseInt(s.split(",")[1]),i)); 49 | i++; 50 | }else if (s.startsWith("letters")){ 51 | // ent.senses.add(new Sensory2D_Letters("config",i)); 52 | i++; 53 | } 54 | } 55 | 56 | 57 | NNAI ai = new NNAI(ent, cId, false, layers); 58 | ent.ai = ai; 59 | for (String nID : nids.getKeys(false)) { 60 | String data = main.getConfig().getString( 61 | "NeuralNetworks." + id + ".neurons" + /* "." + aIID + */"." 62 | + nID); 63 | String[] bits = data.split(","); 64 | Neuron n = null; 65 | //TODO: Make this configurable 66 | 67 | 68 | if (bits[0].startsWith("omn")) { 69 | String[] splits = bits[0].split("\\|"); 70 | int l = Integer.parseInt(splits[1]); 71 | n = new OutputNeuron(ai, Integer.parseInt(splits[2]), l); 72 | } else if (bits[0].startsWith("imn")) { 73 | String[] splits = bits[0].split("\\|"); 74 | // int l = Integer.parseInt(splits[1]); 75 | int x = Integer.parseInt(splits[2]); 76 | int y = Integer.parseInt(splits[3]); 77 | // int sens_id = Integer.parseInt(splits[4]); 78 | // n = new InputMobNeuron(ai, x, y,(Sensory2D_Numbers) ent.senses.get(sens_id)); 79 | } else if (bits[0].startsWith("ibn")) { 80 | String[] splits = bits[0].split("\\|"); 81 | // int l = Integer.parseInt(splits[1]); 82 | int x = Integer.parseInt(splits[2]); 83 | int y = Integer.parseInt(splits[3]); 84 | int sens_id = Integer.parseInt(splits[4]); 85 | // n = new InputBlockNeuron(ai, x, y,(Sensory2D_Numbers) ent.senses.get(sens_id)); 86 | } else if (bits[0].startsWith("iln")) { 87 | String[] splits = bits[0].split("\\|"); 88 | // int l = Integer.parseInt(splits[1]); 89 | int x = Integer.parseInt(splits[2]); 90 | char y = splits[3].charAt(0); 91 | int sens_id = Integer.parseInt(splits[4]); 92 | // n = new InputLetterNeuron(ai, x, y,(Sensory2D_Letters) ent.senses.get(sens_id)); 93 | } else if (bits[0].startsWith("bn")) { 94 | String[] splits = bits[0].split("\\|"); 95 | int l = Integer.parseInt(splits[1]); 96 | n = new BiasNeuron(ai, l); 97 | } else if (bits[0].startsWith("n")) { 98 | String[] splits = bits[0].split("\\|"); 99 | int l = Integer.parseInt(splits[1]); 100 | n = new Neuron(ai, l); 101 | } else 102 | continue; 103 | 104 | if (bits.length >= 2) { 105 | for (String input : bits[1].split("\\|")) { 106 | // if (input.length() > 0) 107 | // / n.getInputs().add(Integer.parseInt(input)); 108 | } 109 | } 110 | if (bits.length >= 3) { 111 | for (String output : bits[2].split("\\|")) { 112 | // if (output.length() > 0) 113 | // n.getOutputs().add(Integer.parseInt(output)); 114 | } 115 | } 116 | 117 | if (bits.length >= 4) { 118 | if (bits[3].length() > 0) 119 | n.setWeight(Double.parseDouble(bits[3])); 120 | } 121 | if (bits.length >= 5) { 122 | String[] entries = bits[4].split("\\|"); 123 | for (String entries2 : entries) { 124 | if (entries2.length() > 0) 125 | n.setStrengthForNeuron(Integer.parseInt(entries2.split("M")[0]), 126 | Double.parseDouble(entries2.split("M")[1])); 127 | } 128 | } 129 | 130 | } 131 | return ent; 132 | } 133 | 134 | public static void savennokld(Plugin main,NNBaseEntity e, String id) { 135 | main.getConfig().set("NeuralNetworks." + id + ".layers", e.ai.maxlayers); 136 | 137 | StringBuilder sb_sens = new StringBuilder(); 138 | 139 | main.getConfig().set("NeuralNetworks." + id + ".senses", sb_sens.toString()); 140 | 141 | for (Neuron n : e.getAI().getAllNeurons()) { 142 | StringBuilder sb = new StringBuilder(); 143 | if (n == null) { 144 | continue; 145 | } else if (n instanceof OutputNeuron) { 146 | sb.append("omn|" + n.layer + "|" 147 | + ((OutputNeuron) n).responceid + ","); 148 | } else if (n instanceof InputMobNeuron) { 149 | sb.append("imn|" + n.layer + "|" 150 | + ((InputNeuron) n).xlink + "|" 151 | + ((InputNeuron) n).ylink + ","); 152 | } else if (n instanceof InputLetterNeuron) { 153 | sb.append("iln|" + n.layer + "|" 154 | + ((InputNeuron) n).xlink + "|" 155 | + ((InputLetterNeuron) n).letter + ","); 156 | } else if (n instanceof InputBlockNeuron) { 157 | sb.append("ibn|" + n.layer + "|" 158 | + ((InputNeuron) n).xlink + "|" 159 | + ((InputBlockNeuron) n).ylink +","); 160 | } else if (n instanceof BiasNeuron) { 161 | sb.append("bn|" + n.layer + ","); 162 | } else if (n instanceof Neuron) { 163 | sb.append("n|" + n.layer + ","); 164 | } 165 | // for (Integer i : n.getInputs()) { 166 | // sb.append(i + "|"); 167 | // } 168 | sb.append(","); 169 | // for (Integer i : n.getOutputs()) { 170 | // sb.append(i + "|"); 171 | // } 172 | // Add strength, and OS 173 | sb.append(","); 174 | sb.append(n.getWeight()); 175 | sb.append(","); 176 | for (Integer ee : n.getStrengthIDs()) { 177 | sb.append(ee + "M" + n.getStrengthForNeuron(ee) + "|"); 178 | } 179 | 180 | main.getConfig().set("NeuralNetworks." + id + ".neurons." + n.getID(), 181 | sb.toString()); 182 | } 183 | main.saveConfig(); 184 | } 185 | } --------------------------------------------------------------------------------