<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.0 20120330//EN" "JATS-archivearticle1.dtd">
<article xmlns:xlink="http://www.w3.org/1999/xlink">
  <front>
    <journal-meta />
    <article-meta>
      <title-group>
        <article-title>Implementation of artificial intelligence in Snake game using genetic algorithm and neural networks</article-title>
      </title-group>
      <contrib-group>
        <aff id="aff0">
          <label>0</label>
          <institution>Piotr Białas Faculty of Applied Mathematics Silesian University of Technology Kaszubska 23</institution>
          ,
          <addr-line>Gliwice, 44-100</addr-line>
          ,
          <country country="PL">Poland</country>
        </aff>
      </contrib-group>
      <fpage>42</fpage>
      <lpage>46</lpage>
    </article-meta>
  </front>
  <body>
    <sec id="sec-1">
      <title>-</title>
      <p>
        Artificial Intelligence is recently growing in many areas.
We see various developments for technical systems, image
processing and multimedia solutions. We can find applications
of intelligent technologies for smart management of energetic
systems [
        <xref ref-type="bibr" rid="ref1">1</xref>
        ]–[
        <xref ref-type="bibr" rid="ref3">3</xref>
        ] and simulation models in thermal sciences [
        <xref ref-type="bibr" rid="ref4">4</xref>
        ],
[
        <xref ref-type="bibr" rid="ref5">5</xref>
        ]. Also in last years gaming industry is using various aspects
of intelligent technologies. There are many interesting system
models which support interactions in real time [
        <xref ref-type="bibr" rid="ref6">6</xref>
        ]. Also
computer systems support interesting application of gamification
ideas [
        <xref ref-type="bibr" rid="ref7">7</xref>
        ].
      </p>
      <p>
        Among techniques of artificial intelligence very high impact
is visible from evolutionary methods. Algorithms are based on
various models of life from animals [
        <xref ref-type="bibr" rid="ref8">8</xref>
        ], insects [
        <xref ref-type="bibr" rid="ref9">9</xref>
        ] or other.
Systems which use various models seen in nature are used
in image processing to track points of interest over images
[
        <xref ref-type="bibr" rid="ref10">10</xref>
        ]. Similarly there are developed many hybrid solutions
composed of neural networks working together with
evolutionary one, like simulation methodologies for dynamic systems
positioning [
        <xref ref-type="bibr" rid="ref11">11</xref>
        ] or smart control in homes [
        <xref ref-type="bibr" rid="ref12">12</xref>
        ]. Among those
methods very interesting is genetic algorithm and its various
versions. One of first propositions was presented in in [
        <xref ref-type="bibr" rid="ref13">13</xref>
        ]
and it improvement was done in [
        <xref ref-type="bibr" rid="ref14">14</xref>
        ].
      </p>
      <p>This article is about artificial intelligence implementation in
the cult game - “Snake”. How did I implement neural network
(NN) and genetic algorithm (GA)? Which type of selection
type I am using, the fitness function that helps me choose the
best performing snake, parameters that are recommended to
learn the fastest way e.g. size of the population, mutation rate
etc. What are the inputs for NN and what are the outputs. To
conclude I will talk about some statistics that I have prepared
on different variations of GA parameters.</p>
    </sec>
    <sec id="sec-2">
      <title>II. WHAT IS GENETIC AGORITHM</title>
      <p>Genetic algorithm is a metaheuristic inspired by the process
of natural selection that belongs to the larger class of
evolutionary algorithms (EA). Genetic algorithms are commonly
used to generate high-quality solutions to optimization and
search problems by relying on bio-inspired operators such as
mutation, crossover and selection. John Holland introduced
c 2019 for this paper by its authors. Use permitted under Creative
Commons License Attribution 4.0 International (CC BY 4.0).
genetic algorithms in 1960 based on the concept of Darwin’s
theory of evolution; afterwards, his student David E. Goldberg
extended GA in 1989.</p>
      <p>Source: https://en.wikipedia.org</p>
    </sec>
    <sec id="sec-3">
      <title>III. HOW DOES GENETIC ALGORITHM WORK</title>
      <p>First of all, we have to describe the snake implementation. It
must have some neural network structure that will decide what
action to take from any given input. This NN is called DNA in
my project. This class has matrixes with weights and a separate
ones with bias, which represent each layer of NN. There are
methods responsible for computing output signal, mutation and
crossover. These last two will be described later in the script.
DNA class is the most important part of the snake – it is its
“brain” that makes every decision. The next step is creating
a function that allows us to calculate its performance. The
performance should include the number of moves the snake
executed without dying and scores.</p>
      <p>For the first step we need to randomly generate the
population of objects, in our case the population of
snakes. Randomly means, that his DNA’s matrixes are
filled with random float values between -1 and 1. In my
case optimum size is 2000 snakes in population.</p>
      <p>Next, we let them play one after another. We start with
the first one and after he dies, we start with another one
repeating it until the last one dies. So now we know how
many steps were executed and how many apples he ate.
Now we calculate the “fitness” of each snake. It helps
us see which one performed the best and which one
should have the higher probability of being chosen for
breeding. How the fitness is calculated is described in
another section.</p>
      <p>Selection. Here we choose which pair of snakes –
“parents” – will give their DNA to the new snake – “child”.
The probability of being chosen is based on fitness. The
bigger it is the bigger the chances are. When we choose
parents, we crossover their DNA – it means we take some
of the weights from the father and some from the mother
and apply it to their child. Again, selection types are
described in another section. We repeat this process as
long as we gain a new population.</p>
      <p>Every new snake after inheriting DNA from his parents
goes through the process of mutation. We set % chances
of mutation occurring – it is called “mutation rate”. Each
value (weight and bias) have the same chance to mutate.
If some weight mutates it changes its value to random
value between -1 and 1. There are few different types of
mutation that are covered later.</p>
      <p>We repeat steps 2 to 5 as long as we get the result we
desire.
- if there is a body part or wall on the right side of the
snake’s head (0 or 1 value)
- a value of sinus of angle on which the food is inclined
relative to the snake
IV. NEURAL NETWORK STRUCTURE, ITS INPUTS AND</p>
      <p>OUTPUTS</p>
      <p>My program is built in this way that we can choose how
many hidden layers we want and how many hidden nodes
will be in each one. My recommendations are 1 hidden layer
with 6 neurons.</p>
    </sec>
    <sec id="sec-4">
      <title>As for the inputs – there are 4:</title>
      <p>- if there is a body part or wall on the left side of the snake’s
head (0 or 1 value)
- if there is body part or wall in front of the snake (0 or 1
value)</p>
      <p>For every input I include the direction the snake is moving
in.</p>
      <p>Why I used the sinus value? Because in range the from -90
and 90 it contains values between -1 and 1, so it demonstrates
in which direction and how strong left or right the apple is.
For example values (0, 1&gt; insinuates that the apple is on right
side, if it is closer to 0, food is more straight in front, if it is
closer to 1, it means that it is much more at the right side of
the snake.</p>
      <p>There are 3 possible outputs. They indicate what will be
snake’s next move.
- turn left
- go forward
- turn right
The snake’s brain chooses the most active one. And again, as
for the inputs, they include current direction, so if we move
South, the action are: left – East, forward – South, right –
West.</p>
    </sec>
    <sec id="sec-5">
      <title>V. TYPES OF CROSSOVERS</title>
      <sec id="sec-5-1">
        <title>A. One-point crossover</title>
        <p>It treats matrixes as one straight line. We split each matrix
of weights and bias in one point. The first half will be inherited
from the father and second one from the mother. Variations
of this method are choosing split points randomly or it can be
fixed in code.</p>
      </sec>
      <sec id="sec-5-2">
        <title>B. Two-point crossover</title>
        <p>The same case as in one-point crossover, but here we have
a range from 2 to how many splitting points we desire. The
child inherits values for change from mother and father. Also
its location can be randomly chosen for every iteration or can
be set in code.</p>
      </sec>
      <sec id="sec-5-3">
        <title>C. Uniform crossover</title>
        <p>We treat each value from matrix as individual. Then we
draw a numbers between 0 and 1 and decide from which parent
we inherit the weight. For example, if we obtain a number and
it is lower than 0.5, we will take it from the father, otherwise
we take it from the mother. The deciding value does not need
to be exactly at half but it is recommended to be.</p>
      </sec>
      <sec id="sec-5-4">
        <title>D. Arithmetic crossover</title>
        <p>The final crossover that I will describe, is a mathematically
calculated crossover. We take corresponding values from each
parent and we take the average from it. The child’s genes are
these average values. There is a variation of this type. We can
take random a percentage from one parent’s weight and the
remaining from other. For example 65% from the father and
the remaining – 35% from mother. The proportion can be fixed
or chosen randomly per each loop.</p>
      </sec>
      <sec id="sec-5-5">
        <title>E. My choice</title>
        <p>In my crossover I chose one random number(a) in range &lt;0,
matrix’s rows) and the second(b) from &lt;0, matrix’s columns).
Using if statement as here:
i f ( ( j &lt; a ) | | ( j == a &amp;&amp; k &lt;= b ) )</p>
        <p>Where j is current row and k is current column. If this
condition is fulfilled the child inherits from the father, otherwise
from the mother. In this scenario the matrixes are being cut
from a curve so the crossover is very flexible.</p>
      </sec>
    </sec>
    <sec id="sec-6">
      <title>VI. TYPES OF SELECTION</title>
      <sec id="sec-6-1">
        <title>A. One-point roulette wheel</title>
        <p>Each snake takes proportional (with its fitness score) space
on a roulette wheel. We set fixed points on the roulette, so
we know who will win. Then we spin the wheel twice. The
2 winners are chosen to be parents. The other modification is
not spinning the wheel but randomly choosing the point. The
chances in both scenarios are the same – the higher the fitness
the higher the probability of being chosen.</p>
      </sec>
      <sec id="sec-6-2">
        <title>B. Two-point roulette wheel</title>
        <p>The same like in the one-point, but here we choose 2 fixed
points opposite each other and when the wheel is spin, the 2
winners become parents. Or we can randomly choose 2 points
and the fitness they land on will decide who the parents are.
(Notice, that this and the previous method can be only applied
for non-negative fitnesses).</p>
      </sec>
      <sec id="sec-6-3">
        <title>C. Rank selection</title>
        <p>We sort snakes by the fittest one and give them ranks. The
best one will get rank one, then rank two and so on. When it is
complete, we perform the one-point roulette wheel selection,
but based on ranks, not fitness. (The higher the rank, the higher
the probability e.g. 1 – 40%, 2 – 30%, 3 – 20%, 4 – 10%). This
method helps us pick the best performing snakes more often.
We can have 3 snakes with fitness 21.8, 21 and 20.9. Based
on their score they will have all similar chances to become
parents, but we require the best one (21.8) to reproduce, so
we allocate ranks. (We can compare this to 40-meter runners
where everybody has a very similar time, but still only the
fastest one wins)</p>
      </sec>
      <sec id="sec-6-4">
        <title>D. Tournament selection</title>
        <p>We choose a group of few snakes (from 2 to even half the
population) and then we set brackets as in the football world
championship. The best performing snake wins and proceeds
the next round. In the end we have only 2 snakes left and they
are the parents. This scenario always allows the best snake
to reproduce because he will win in every group and with
anybody, so the randomness is not so high and it can prevent
the diversity.</p>
      </sec>
      <sec id="sec-6-5">
        <title>E. Random selection</title>
        <p>This is the worst type of selection. We choose parents
randomly without looking at their performance and fitness.
In most cases it does not work.</p>
      </sec>
      <sec id="sec-6-6">
        <title>F. My choice</title>
        <p>In my selection I used the two-point roulette wheel, but
firstly I sort snakes descending by fitness level. Then I set
a variable called “Top” - decimal number between 0 and 1,
which represents the percentage of top preforming snakes that
will participate in roulette. Default value is 0.2 (20%). In that
case I still have randomness throughout the population, but I
do not allow weak snakes to reproduce.</p>
        <p>VII. MUTATION TYPE</p>
      </sec>
      <sec id="sec-6-7">
        <title>A. Whole mutation</title>
        <p>Firstly, we create a variable and set its value between 0 and
1, which, again, represents percentage of probability of being
mutated. When it comes to mutating, we reset weight value
to a random number between -1 and 1.</p>
      </sec>
      <sec id="sec-6-8">
        <title>C. My choice</title>
        <p>I implemented the whole mutation method, because I belive
it gives us more randomness and variation within the
population.</p>
      </sec>
    </sec>
    <sec id="sec-7">
      <title>VIII. FITNESS FUNCTION</title>
      <sec id="sec-7-1">
        <title>A. Introduction</title>
        <p>There are no rules that you need to follow during building
fitness function. But you need to remember that the fitness
should describe the best performing snake in the best possible
way.</p>
      </sec>
      <sec id="sec-7-2">
        <title>B. My choice</title>
        <p>I used steps the snake executed and apples eaten. If the
score is less than 10:</p>
        <p>steps steps 2score</p>
      </sec>
    </sec>
    <sec id="sec-8">
      <title>And if it is larger:</title>
      <p>steps steps 2score</p>
    </sec>
    <sec id="sec-9">
      <title>IX. ADJUSTABLE PARAMETERS</title>
      <sec id="sec-9-1">
        <title>A. Hidden layers and hidden nodes</title>
        <p>It is up to you how many of them you will have, you can
have 0 hidden layers or 2 – it is up to you. 99 % of neural
networks can solve your problem using 1 hidden layer at most.</p>
      </sec>
      <sec id="sec-9-2">
        <title>B. Mutation rate</title>
        <p>You need to adjust it by looking at results of your program.
Mutation is important, because it helps algorithm to jump off
of local minimum by keeping diversity. Recommended values
are from 0.5</p>
      </sec>
      <sec id="sec-9-3">
        <title>C. Population size</title>
        <p>Firstly, you need to see how much can your computer run
without lags. The size determines how diverse the population
will be at the beginning. The size can be from 50 to even
10000 snakes.</p>
      </sec>
      <sec id="sec-9-4">
        <title>D. Top population</title>
        <p>Variable, which describes how many percent of the best
performing snakes will reproduce. I tried values between 5</p>
      </sec>
      <sec id="sec-9-5">
        <title>E. Moves at start and moves for food</title>
      </sec>
      <sec id="sec-9-6">
        <title>B. Close mutation</title>
        <p>The same as whole mutation, except this change the value
randomly +-0.35, but not more than 1 and less than -1. The
changing value can be randomly chosen.</p>
        <p>How long snake will live without eating and how many
additional steps he will get from apple. I gave him 100 at
start and 100 every apple he ate.</p>
        <p>X. STATISTICS</p>
      </sec>
    </sec>
    <sec id="sec-10">
      <title>Plots’ author: Tomasz Siemek</title>
      <p>XI. CONCLUSION</p>
      <p>You do not need to use the same methods as I did. The best
part of genetic algorithm is that you find by yourself which
methods and which parameters are the best in your case. The
NN structure can be different (e.g. more inputs, other inputs).
In this article I described some of types and parameters, there
are many more and you can even develop your own selection
or mutation type.</p>
    </sec>
  </body>
  <back>
    <ref-list>
      <ref id="ref1">
        <mixed-citation>
          [1]
          <string-name>
            <given-names>G.</given-names>
            <surname>Capizzi</surname>
          </string-name>
          ,
          <string-name>
            <given-names>G. L.</given-names>
            <surname>Sciuto</surname>
          </string-name>
          ,
          <string-name>
            <given-names>C.</given-names>
            <surname>Napoli</surname>
          </string-name>
          , and E. Tramontana, “
          <article-title>Advanced and adaptive dispatch for smart grids by means of predictive models</article-title>
          ,
          <source>” IEEE Transactions on Smart Grid</source>
          , vol.
          <volume>9</volume>
          , no.
          <issue>6</issue>
          , pp.
          <fpage>6684</fpage>
          -
          <lpage>6691</lpage>
          ,
          <year>2017</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref2">
        <mixed-citation>
          [2]
          <string-name>
            <given-names>F.</given-names>
            <surname>Bonanno</surname>
          </string-name>
          ,
          <string-name>
            <given-names>G.</given-names>
            <surname>Capizzi</surname>
          </string-name>
          ,
          <string-name>
            <given-names>A.</given-names>
            <surname>Gagliano</surname>
          </string-name>
          , and
          <string-name>
            <given-names>C.</given-names>
            <surname>Napoli</surname>
          </string-name>
          , “
          <article-title>Optimal management of various renewable energy sources by a new forecasting method,” in International Symposium on Power Electronics Power Electronics, Electrical Drives, Automation and Motion</article-title>
          . IEEE,
          <year>2012</year>
          , pp.
          <fpage>934</fpage>
          -
          <lpage>940</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref3">
        <mixed-citation>
          [3]
          <string-name>
            <given-names>F.</given-names>
            <surname>Bonanno</surname>
          </string-name>
          , G. Capizzi,
          <string-name>
            <given-names>S.</given-names>
            <surname>Coco</surname>
          </string-name>
          ,
          <string-name>
            <given-names>A.</given-names>
            <surname>Laudani</surname>
          </string-name>
          , and
          <string-name>
            <given-names>G.</given-names>
            <surname>Lo</surname>
          </string-name>
          <string-name>
            <surname>Sciuto</surname>
          </string-name>
          , “
          <article-title>A coupled design optimization methodology for li-ion batteries in electric vehicle applications based on fem and neural networks,” in 2014 International Symposium on Power Electronics, Electrical Drives, Automation and Motion</article-title>
          . IEEE,
          <year>2014</year>
          , pp.
          <fpage>146</fpage>
          -
          <lpage>153</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref4">
        <mixed-citation>
          [4]
          <string-name>
            <given-names>G.</given-names>
            <surname>Capizzi</surname>
          </string-name>
          ,
          <string-name>
            <given-names>G. L.</given-names>
            <surname>Sciuto</surname>
          </string-name>
          , G. Cammarata, and
          <string-name>
            <given-names>M.</given-names>
            <surname>Cammarata</surname>
          </string-name>
          , “
          <article-title>Thermal transients simulations of a building by a dynamic model based on thermal-electrical analogy: Evaluation and implementation issue,” Applied energy</article-title>
          , vol.
          <volume>199</volume>
          , pp.
          <fpage>323</fpage>
          -
          <lpage>334</lpage>
          ,
          <year>2017</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref5">
        <mixed-citation>
          [5]
          <string-name>
            <given-names>R.</given-names>
            <surname>Brociek</surname>
          </string-name>
          and
          <string-name>
            <given-names>D.</given-names>
            <surname>Słota</surname>
          </string-name>
          , “
          <article-title>A method for solving the time fractional heat conduction inverse problem based on ant colony optimization and artificial bee colony algorithms</article-title>
          ,” in
          <source>International Conference on Information and Software Technologies</source>
          . Springer,
          <year>2017</year>
          , pp.
          <fpage>351</fpage>
          -
          <lpage>361</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref6">
        <mixed-citation>
          [6]
          <string-name>
            <surname>I. Martišius</surname>
          </string-name>
          and R. Damaševicˇius, “
          <article-title>A prototype ssvep based real time bci gaming system,” Computational intelligence and neuroscience</article-title>
          , vol.
          <year>2016</year>
          , p.
          <fpage>18</fpage>
          ,
          <year>2016</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref7">
        <mixed-citation>
          [7]
          <string-name>
            <given-names>D.</given-names>
            <surname>Ašeriškis</surname>
          </string-name>
          and R. Damaševicˇius, “
          <article-title>Gamification patterns for gamification applications</article-title>
          ,” Procedia Computer Science, vol.
          <volume>39</volume>
          , pp.
          <fpage>83</fpage>
          -
          <lpage>90</lpage>
          ,
          <year>2014</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref8">
        <mixed-citation>
          [8]
          <string-name>
            <given-names>D.</given-names>
            <surname>Połap</surname>
          </string-name>
          et al., “
          <article-title>Polar bear optimization algorithm: Meta-heuristic with fast population movement and dynamic birth and death mechanism</article-title>
          ,” Symmetry, vol.
          <volume>9</volume>
          , no.
          <issue>10</issue>
          , p.
          <fpage>203</fpage>
          ,
          <year>2017</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref9">
        <mixed-citation>
          [9]
          <string-name>
            <given-names>R.</given-names>
            <surname>Brociek</surname>
          </string-name>
          and
          <string-name>
            <given-names>D.</given-names>
            <surname>Słota</surname>
          </string-name>
          , “
          <article-title>Application and comparison of intelligent algorithms to solve the fractional heat conduction inverse problem</article-title>
          ,
          <source>” Information Technology and Control</source>
          , vol.
          <volume>45</volume>
          , no.
          <issue>2</issue>
          , pp.
          <fpage>184</fpage>
          -
          <lpage>194</lpage>
          ,
          <year>2016</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref10">
        <mixed-citation>
          [10]
          <string-name>
            <given-names>M.</given-names>
            <surname>Woz</surname>
          </string-name>
          <article-title>´niak and D. Połap, “Bio-inspired methods modeled for respiratory disease detection from medical images,” Swarm and evolutionary computation</article-title>
          , vol.
          <volume>41</volume>
          , pp.
          <fpage>69</fpage>
          -
          <lpage>96</lpage>
          ,
          <year>2018</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref11">
        <mixed-citation>
          [11] --, “
          <article-title>Hybrid neuro-heuristic methodology for simulation and control of dynamic systems over time interval,” Neural Networks</article-title>
          , vol.
          <volume>93</volume>
          , pp.
          <fpage>45</fpage>
          -
          <lpage>56</lpage>
          ,
          <year>2017</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref12">
        <mixed-citation>
          [12] --, “
          <article-title>Intelligent home systems for ubiquitous user support by using neural networks and rule based approach</article-title>
          ,
          <source>” IEEE Transactions on Industrial Informatics</source>
          ,
          <year>2019</year>
          .
        </mixed-citation>
      </ref>
      <ref id="ref13">
        <mixed-citation>
          [13]
          <string-name>
            <surname>J. rey Horn</surname>
            ,
            <given-names>N.</given-names>
          </string-name>
          <string-name>
            <surname>Nafpliotis</surname>
            , and
            <given-names>D. E.</given-names>
          </string-name>
          <string-name>
            <surname>Goldberg</surname>
          </string-name>
          , “
          <article-title>A niched pareto genetic algorithm for multiobjective optimization</article-title>
          ,”
          <source>in Proceedings of the first IEEE conference on evolutionary computation, IEEE world congress on computational intelligence</source>
          , vol.
          <volume>1</volume>
          .
          <string-name>
            <surname>Citeseer</surname>
          </string-name>
          ,
          <year>1994</year>
          , pp.
          <fpage>82</fpage>
          -
          <lpage>87</lpage>
          .
        </mixed-citation>
      </ref>
      <ref id="ref14">
        <mixed-citation>
          [14]
          <string-name>
            <given-names>K.</given-names>
            <surname>Deb</surname>
          </string-name>
          ,
          <string-name>
            <given-names>S.</given-names>
            <surname>Agrawal</surname>
          </string-name>
          ,
          <string-name>
            <given-names>A.</given-names>
            <surname>Pratap</surname>
          </string-name>
          , and T. Meyarivan, “
          <article-title>A fast elitist nondominated sorting genetic algorithm for multi-objective optimization: Nsga-ii,” in International conference on parallel problem solving from nature</article-title>
          . Springer,
          <year>2000</year>
          , pp.
          <fpage>849</fpage>
          -
          <lpage>858</lpage>
          .
        </mixed-citation>
      </ref>
    </ref-list>
  </back>
</article>