<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fernando Rosa on Medium]]></title>
        <description><![CDATA[Stories by Fernando Rosa on Medium]]></description>
        <link>https://medium.com/@scriviafernando?source=rss-82fc6081da82------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qXpD_9NO8iP7rNNp</url>
            <title>Stories by Fernando Rosa on Medium</title>
            <link>https://medium.com/@scriviafernando?source=rss-82fc6081da82------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:50:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scriviafernando/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SpaceRace: a smart spawner for more fun!]]></title>
            <link>https://medium.com/apple-developer-academy-federico-ii/spacerace-a-smart-spawner-for-more-fun-d9d06eb584e6?source=rss-82fc6081da82------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9d06eb584e6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[apple-developer-academy]]></category>
            <category><![CDATA[mobile-game-development]]></category>
            <category><![CDATA[create-ml]]></category>
            <category><![CDATA[coreml]]></category>
            <dc:creator><![CDATA[Fernando Rosa]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 14:28:33 GMT</pubDate>
            <atom:updated>2020-04-16T14:28:33.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAMTZAz3qLkw89H3gRC6KQ.png" /></figure><p>Nowadays, creating a 2D videogames for iOS systems it is easier than you think, thanks to the existing development systems. Making it graphically appealing is more complex, and usually it is necessary a visionary designer (we had the chance to meet <a href="https://medium.com/u/e1095e6525cf">Simona Zimona Correale</a>…). By the way, with a little effort of imagination (maybe getting some ideas from other videogames) and a bit of fancy, you can attain a product able to kindle curiosity of the players even without a pixel guru. If you succeed adding a simple gaming mechanics and an intriguing story, you reached your goal: making a player download and play it at least once in his life.</p><p>Obviously, it is necessary a bigger effort if we want to define a game a success. Indeed, if relying on simple mechanisms based on pre-established schemes allows you to quickly create a product to be published in the shortest possible time, in the long run the idea of confronting a simple automaton that simply replicates pre-established behaviors, leads the user inexorably towards the chasm of boredom, whose next step is always the fateful “Delete App”. In order for a video game to be worthy of being played a second time, and then a third and so on, it must have other qualities, whose the sum of which should prompt the user to ask himself at the beginning of each level “What awaits me now?” .</p><p>And this is where our story begins, from the desire to make our game SpaceRace a game that deserves to be played more than once, where every time is different from the previous one. How to do it? Using a branch of Artificial Intelligence known as <a href="https://en.wikipedia.org/wiki/Machine_learning"><strong>Machine Learning</strong></a>, made accessible in iOS systems thanks to<strong> </strong><a href="https://developer.apple.com/documentation/createml"><strong>CreateML</strong></a> and <a href="https://developer.apple.com/documentation/coreml"><strong>CoreML</strong></a>.</p><h4>Machine Learning: learn and predict</h4><p>Learning is a really complex process, which in our case is made relatively simple by the proper use of the most powerful computing unit in the world: the human mind. Sure that being able to replicate the learning method of us humans would have made it possible to make significant progress in their field of study, part of the scientists and researchers involved in Artificial Intelligence gave life to Machine Learning, at the end of the twentieth century.</p><p>The concept behind this discipline is very simple: allowing a machine to learn from observations in order to predict future actions. Like a child who can learn how painful it is to burn himself by touching a lit match flame, so a computer can learn to identify a possible pandemic based on data relating to cases of seasonal flu in certain countries of the world.</p><p>Of course we cannot and we do not want to deal in depth with such a complex topic as Machine Learning, but we think it is useful to say that there are 3 types of ML:</p><ol><li><strong>Supervised Learning</strong>, to predict results;</li><li><strong>Unsupervised Learning</strong>, to find hidden structures in the data;</li><li><strong>Reinforcement Learning</strong>, to improve interactions.</li></ol><p>The common concept between all these techniques is the need to have available observations, structured data, divided into training data and testing data, which allow the machine to build and validate a model that will be the base of its knowledge.</p><p>By studying how Apple has made it possible for developers to build models and use them to make their apps smart, we thought that ML could help us achieve our goal: to give SpaceRace a “<em>mind</em>” to make it more fun.</p><h4>SpaceRace and SpaceCowboys</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*cXQDRJ-qmBtjJg00_1gF8w.png" /><figcaption>SpaceRace by Space Cowboys</figcaption></figure><p>What is SpaceRace? SpaceRace is a 2D video game of scientific disclosure, which aims to provide the user with information relating to the race of man in conquering space and at the same time entertaining him. It is the result of the hard work of the SpaceCowboys team, of which we have been part. It has captivating graphics, a structured story and a simple game mechanics, divided into Planets (worlds) and Missions (levels). In each level the user is engaged in a recovery mission and he has to recover pieces of probes drifting in space being careful to avoid spatial garbage and micro meteorites that can damage his suit and his jetpack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*rFe00V2xFHs49Blx20zAgg.png" /><figcaption>SpaceRace game scene</figcaption></figure><p>As we said at the beginning of our story, a video game must present a game mechanics that pushes the user to face each level with enthusiasm. So we wondered how ML could help us make our game more exciting. To ensure that this research was not carried out blindly, we tried to identify which component of the game we could give intelligence to.</p><p>It was not difficult to understand that the fundamental element of the game, currently devoid of “intelligence” and limited to behave according to predetermined schemes, was the one that most needed an evolutionary leap: the <strong>spawner</strong>. Making it smart would have made our game more fun.</p><h4>Spawn it!</h4><p>In 2D video games (as in all video games) there is a term that stands for the activity of generating entities within the game itself: spawn. In SpaceRace the spawner is responsible for generating three types of objects within each level:</p><ol><li><strong>Space junk</strong>, an object (malus) that upon impact with the player causes damage to the space suite or jet pack, causing respectively a loss of oxygen, of propellant or a temporary collision radar failure, depending on the size of the object itself and the impact coordinate;</li><li><strong>Repair kit</strong>, a set of tools (bonus) that allows the player to repair damage to the space suite or jet pack;</li><li><strong>Refills</strong>, oxygen or propellant containers used by the player to refill the oxygen or propellant tank respectively.</li></ol><p>It is therefore easy to understand how SpaceRace’s gaming experience depends on the <strong>spawner</strong>.</p><p>So once we decided that the spawner needed a modification in order to make it intelligent, to allow it to decide independently where and how to generate objects, we tried to understand what type of ML and which technique could help us achieve our goal.</p><p>To do this, we took into consideration the dataset at our disposal, the fateful observations, from which we could learn, and then generate a model for our spawner, a <em>model to be used to predict the future…</em></p><h4>Predict the future</h4><p>So we decided to build a <em>crystal ball</em> that would allow the spawner to knowthe future position of the player, with a certain precision.</p><p>To do this we have identified our ideal solution in <strong>Supervised Learning</strong> (<strong>SL</strong>), and in particular in <strong>regression.</strong></p><p>SL is one of the three types of ML and it is based on the ability to learn a behavior model, starting from data already observed, which allows to make future predictions starting from new data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AM8CTARZIUstfdAMmq2cTw.png" /></figure><p>Depending on the type of forecast you want, we have two types of SL:</p><ol><li><strong>Classification</strong>, where discrete values are used and where the ultimate goal is to predict the class to which the new data set belongs;</li><li><strong>Regression</strong>, where continuous values are used and where the ultimate goal is to predict the (continuous) result starting from the new data set.</li></ol><p><em>There was nothing more suitable than regression to predict the future position of the player, based on the current data of the player!</em></p><p>This observation enlightened us by showing us the way for the creation of the mind to be provided to our spawner. Therefore we identified useful information to create our data set:</p><p><strong>PVA</strong>, Player Vertical Acceleration;</p><ol><li><strong>PVS</strong>, Player Vertical Speed;</li><li><strong>PAVP</strong>, Player Actual Vertical Position;</li><li><strong>PFVP</strong>, Player Future Vertical Position.</li></ol><p>Now, in order to apply the regression technique to build our model, we needed to collect the observations, i.e. the real data, which we would then use to build our <strong>function matrix</strong> (the set of independent variables PVA, PVS and PAVP ) and our <strong>vector of dependent variables</strong> (the PFVP values). To do this we added a class (<strong>JsonManager.swift</strong>) to the original SpaceRace project that would allow you to save, in a <strong>.json</strong> file, the recordings of the PVA, PVS, PAVP and PFVP values relating to the player during a game session. By inserting a function for recording this data in the <strong>GameScene</strong>,</p><p>&lt;script src=’<a href="https://gitlab.com/Kronos_Rob/spacerace/snippets/1964423.js&#39;">https://gitlab.com/Kronos_Rob/spacerace/snippets/1964423.js&#39;</a>&gt;&lt;/script&gt;</p><p>we obtained a series of observations that can be represented in the following data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGeKJ9KgSz2r2OEQPFxq0Q.png" /><figcaption>Subset of observations recorded during a game session</figcaption></figure><p>What to do with all this data?</p><p>Thanks to these observations we built our model. How? Trusting him …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TnFBK2SA1QPqNVSNTbMrQ.jpeg" /><figcaption><a href="https://simple.wikipedia.org/w/index.php?title=Deep_Thought&amp;redirect=no">Deep Thought</a> Super Computer</figcaption></figure><h4>The answer is… 42</h4><p>Ok it’s not true, we didn’t rely on Deep Thought, also because we couldn’t have waited for all that computational time to finally get a simple 42.</p><p>We have relied on something more powerful that would allow us to obtain a reliable model for our spawner. We therefore created a project in Create ML using regression as a generation template.</p><p>As previously seen, regression is a type of SL that uses an algorithm (based on neural networks) that exploits a mathematical concept, regression analysis, which we could summarize in a simple way like this: <em>given a number of independent variables (explanatory) and a number of associated dependent variables (outcome or target) try to find a relationship between these variables that allows to predict a result.</em></p><p>In the CreateML project we have provided our dataset of observations dividing it into <strong>training data</strong>, used by the ML to try to understand the relationship between the data, and <strong>testing data</strong>, used to verify the forecasts. At this point CreateML did the dirty work for us: processing the observations in the search for relationships between the data, making predictions of results and verifying them, and finally generating a knowledge model to be used with new data.</p><p>All that remained was to test our model in SpaceRace. To do this we imported the model generated by CreateML into our project, and thanks to CoreML we used it to modify the behavior of our spawner in the GameScene.</p><p>&lt;script src=’<a href="https://gitlab.com/Kronos_Rob/spacerace/snippets/1964424.js&#39;">https://gitlab.com/Kronos_Rob/spacerace/snippets/1964424.js&#39;</a>&gt;&lt;/script&gt;</p><p>As you can see by analyzing the code, we relied on our model (<strong>test1_1</strong>) the choice of the position (<strong>verticalFuturePosition</strong>) where it would have generate space junk to hit the player.</p><p>Once the changes were done we did some game sessions and do you know what we found out?</p><h4>It could work!</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4An1BrG2u_4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4An1BrG2u_4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4An1BrG2u_4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ca965a34d7ceb6a1152505744f1c950/href">https://medium.com/media/8ca965a34d7ceb6a1152505744f1c950/href</a></iframe><p>It worked! Simple but effective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*5bfaBmth220qbSEq7mmxOg.gif" /><figcaption>Game session from SpaceRace</figcaption></figure><p>By observing the collision radar on the lower left you can notice how the spawner comes to anticipate the player in his movements, transmitting to the player the feeling of having an intelligent entity in front of him.</p><p>Overall simple, this first approach with ML allowed us to obtain a knowledge-based behavior to be assigned to our spawner!</p><p>So going back to our initial consideration, is this the way to take in order to exploit ML and get a successful video game?</p><h4>Roads… Where we’re going we don’t need roads</h4><p>No, this is not the “road”. This is just one of many “roads” … Using CreateML and CoreML we can apply degrees of complexity that take into account further aspects, thus creating different behaviours such as:</p><ul><li>compassionate spawner, who gives respite to a damaged player and generates more repair kits and less space junk;</li><li>charitable spawner, which generates refills until the player fills his tanks;</li><li>strategic spawner, which generates space junk by forcing the player into a disadvantageous position and which will lead him inexorably to defeat.</li></ul><p>Aren’t you excited? We are! Considering therefore the innumerable possibilities provided by iOS, CreateML and CoreML, it also becomes useless to talk about roads, because as we like saying:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FG3AfIvJBcGo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DG3AfIvJBcGo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FG3AfIvJBcGo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/302de770ad3720ebf2edc0a70fa11874/href">https://medium.com/media/302de770ad3720ebf2edc0a70fa11874/href</a></iframe><h4><strong>From Mean Machine with love</strong></h4><p>We would like to end this story by thanking the Space Cowboys Team, with whom we made SpaceRace during our experience at the Apple Developer Academy. We love you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*RviHqzBhcek6ETS6rpW86A.png" /></figure><p>Mean Machine Team:</p><p><a href="https://www.linkedin.com/in/massimo-maddaluno-95a686162/">Massimo <strong>Maddaluno</strong></a><strong> </strong><br><a href="https://www.linkedin.com/in/roberto-scarpati-3a72321a6/">Roberto <strong>Scarpati</strong></a><br><a href="https://www.linkedin.com/in/fernando-rosa-4a41291b/">Fernando <strong>Rosa</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9d06eb584e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apple-developer-academy-federico-ii/spacerace-a-smart-spawner-for-more-fun-d9d06eb584e6">SpaceRace: a smart spawner for more fun!</a> was originally published in <a href="https://medium.com/apple-developer-academy-federico-ii">Apple Developer Academy | Federico II</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SpaceRace: a smart spawner for more fun!]]></title>
            <link>https://medium.com/@scriviafernando/spacerace-a-smart-spawner-for-more-fun-27982297e2d9?source=rss-82fc6081da82------2</link>
            <guid isPermaLink="false">https://medium.com/p/27982297e2d9</guid>
            <category><![CDATA[mobile-game-development]]></category>
            <category><![CDATA[coreml]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[create-ml]]></category>
            <category><![CDATA[spritekit]]></category>
            <dc:creator><![CDATA[Fernando Rosa]]></dc:creator>
            <pubDate>Sat, 04 Apr 2020 14:41:00 GMT</pubDate>
            <atom:updated>2020-04-04T14:41:00.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAMTZAz3qLkw89H3gRC6KQ.png" /></figure><p>Creare oggi un videogioco 2D per sistemi iOS , avvalendosi delle <a href="https://developer.apple.com/spritekit/">tecnologie di sviluppo esistenti</a>, è semplice, molto più semplice di quanto pensiate. Renderlo graficamente accattivante è una questione un po’ più complessa che il più delle volte richiede la presenza di un designer visionario (noi abbiamo avuto la fortuna di conoscere Simona Zimona Correale…), ma con un piccolo sforzo d’immaginazione (magari prendendo spunto da altre esperienze videoludiche) e un pò di gusto, si può ottenere un prodotto che riesca ad accendere la curiosità nei giocatori anche senza un guru del pixel. Se a tutto questo aggiungete una storia intrigante ed una meccanica semplice allora avrete raggiunto il vostro scopo: far si che un utente scarichi il vostro prodotto e ci giochi almeno una volta nella sua vita.</p><p>Naturalmente affinché un videogioco possa essere definito un successo (o quasi) è richiesto uno sforzo maggiore. Infatti, se affidarsi a semplici meccanismi basati su schemi prestabiliti permette di realizzare velocemente un prodotto da pubblicare nel minor tempo possibile, alla lunga l’idea di confrontarsi con un semplice automa che si limita a replicare comportamenti prestabiliti, porta inesorabilmente l’utente verso il baratro della noia, il cui passo successivo è sempre il fatidico “Delete App”. Affinché un videogioco possa essere degno di essere giocato una seconda volta, e poi una terza e così via, deve possedere altre qualità, la somma delle quali dovrebbe spingere l’utente a chiedersi all’inizio di ogni livello “Cosa mi aspetta ora?”.</p><p>Ed è qui che inizia la nostra storia, dalla volontà di rendere il nostro SpaceRace un videogioco che meriti di essere giocato più di una volta, dove ogni volta sia diversa dalla precedente. Come farlo? Utilizzando una branca dell’Intelligenza Artificiale conosciuta con l’accattivante nome di <a href="https://en.wikipedia.org/wiki/Machine_learning"><strong>Machine Learning</strong></a>, resa accessibile nei sistemi iOS grazie a <a href="https://developer.apple.com/documentation/createml"><strong>CreateML</strong></a> e <a href="https://developer.apple.com/documentation/coreml"><strong>CoreML</strong></a>.</p><h4>Machine Learning: learn and predict</h4><p>Imparare è un processo a dir poco complesso che nel nostro caso è reso relativamente semplice dall’utilizzo appropriato dell’unità di calcolo più potente al mondo: la mente umana. Sicuri che riuscire a replicare il metodo di apprendimento di noi umani avrebbe permesso di fare significativi passi in avanti nel loro campo di studi, parte degli scienziati e dei ricercatori impegnati nell’Intelligenza Artificiale diedero vita, alla fine del XX secolo, a quello che oggi tutti conosciamo come Machine Learning (ML).</p><p>Il concetto alla base di questa disciplina è molto semplice: permettere ad una macchina di imparare dalle osservazioni per prevedere azioni future. Come un bambino che può imparare quanto sia doloroso bruciarsi, toccando la fiamma di un fiammifero acceso, così un computer può imparare ad individuare una possibile pandemia basandosi sui dati relativi ai casi di influenza stagionale in determinati paesi del mondo.</p><p>Naturalmente non possiamo e non vogliamo affrontare in maniera approfondita un argomento così complesso come il Machine Learning, ma credo sia utile dire che esistono 3 tipi di ML:</p><ol><li><strong>Supervised Learning</strong>, per predire risultati;</li><li><strong>Unsupervised Learning</strong>, per individuare strutture nascoste nei dati;</li><li><strong>Reinforcement Learning</strong>, per migliorare le interazioni.</li></ol><p>Il concetto in comune tra tutte queste tecniche è la necessità di avere a disposizione delle osservazioni, dati strutturati, suddivisi in trainig data e test data, che permettano alla macchina di costruire e validare un modello sul quale poi basare la propria conoscenza.</p><p>Studiando come Apple abbia messo a disposizione degli sviluppatori la possibilità di costruire modelli ed utilizzarli per rendere intelligenti le loro app, abbiamo pensato che il ML avrebbe potuto aiutarci nel raggiungere il nostro obiettivo: dare <em>“una mente”</em> a SpaceRace per renderlo più divertente.</p><h4>SpaceRace and SpaceCowboys</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VeLELCsND24N5pbJ3lDiJQ.png" /></figure><p>Cosa è SpaceRace? SpaceRace è un videogioco 2D di divulgazione scientifica, che ha lo scopo di fornire all’utente informazioni relative alla corsa dell’uomo nella conquista dello spazio e allo stesso tempo divertirlo. Frutto del duro lavoro del team SpaceCowboys, di cui abbiamo fatto parte, SpaceRace ha una grafica accattivante, una storia strutturata ed un meccanismo di gioco semplice, articolato su Pianeti(mondi) e Missioni(livelli). In ogni livello l’utente è impegnato in una missione, durante la quale deve recuperare pezzi di sonde alla deriva nello spazio e nel farlo deve stare attento ad evitare immondizia spaziale e micro meteoriti che possono danneggiare la sua tuta e il suo jetpack.</p><p>Come abbiamo detto all’inizio della nostra storia un videogioco deve presentare una meccanica di gioco che spinga l’utente ad affrontare ogni livello con entusiasmo. Quindi ci siamo chiesti come il ML potesse aiutarci a rendere più entusiasmante il nostro gioco. Per far si che questa ricerca non fosse portata avanti alla cieca abbiamo cercato di individuare quale fosse la componente del gioco alla quale potevamo dare un intelligenza.</p><p>Non è stato difficile capire che l’elemento fondamentale del gioco, attualmente privo di “<em>intelligenza</em>” e limitato a comportarsi secondo schemi prefissati, fosse quello che più necessitava di un salto evolutivo: lo <strong>spawner</strong>. Renderlo intelligente avrebbe reso il nostro gioco più divertente.</p><h4>Spawn it!</h4><p>Nei videogiochi 2D (come in tutti i videogiochi) esiste un termine che indica l’attività di generazione di entità all’interno del gioco stesso: <em>spawn</em>. In SpaceRace lo spawner si occupa di generare all’interno di ogni livello tre tipologie di oggetti:</p><ol><li><strong>Space junk</strong>, un oggetto (<em>malus</em>) che all’impatto con il player provoca, a seconda della dimensione dell’oggetto stesso e della coordinata di impatto, un danno alla space suite o al jet pack, procurando rispettivamente una perdita di ossigeno, di propellente o un’avaria temporanea al radar di collisione;</li><li><strong>Repair kit</strong>, un set di strumenti (<em>bonus</em>) che permette al player di riparare i danni presenti alla space suite o al jet pack;</li><li><strong>Refills</strong>, contenitori di ossigeno o di propellente utilizzati dal player per ricaricare rispettivamente il serbatoio di ossigeno o di propellente.</li></ol><p>Risulta quindi semplice capire come l’esperienza videoludica di SpaceRace dipenda molto dallo <strong>spawner</strong>.</p><p>Quindi una volta deciso che fosse lo spawner a necessitare di una modifica che lo rendesse intelligente, per permettergli di decidere autonomamente dove e come generare oggetti, abbiamo cercato di capire quale tipo di ML e quale tecnica potesse aiutarci a raggiungere il nostro scopo.</p><p>Per farlo abbiamo preso in considerazione i dati a nostra disposizione, le fatidiche osservazioni, dalle quali poter imparare, per poi generare un modello per il nostro spawner, un <em>modello da utilizzare per predire il futuro…</em></p><h4><strong>Predict the future</strong></h4><p>Abbiamo così deciso di costruire una <em>sfera di cristallo</em> che permettesse allo spawner di sapere, con un certo gardo di precisione, la posizione futura del player.</p><p>Per farlo abbiamo individuato nel <strong>Supervised Learning</strong> (<strong>SL</strong>), ed in particolare nella <strong>regressione</strong>, la nostra soluzione ideale.</p><p>Il SL è una delle tre tipologie di ML e si basa sulla capacità di imparare un modello di comportamento, a partire da dati già osservati, che permetta di fare previsioni future partendo da nuovi dati.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AM8CTARZIUstfdAMmq2cTw.png" /></figure><p>A seconda del tipo di previsione che si vuole ottenere, abbiamo due tipi di SL:</p><ol><li><strong>Classificazione</strong>, dove si utilizzano valori discreti e dove il fine ultimo è prevedere la classe di appartenenza del nuovo set di dati;</li><li><strong>Regressione</strong>, dove si utilizzano valori continui e dove il fine ultimo è prevedere il risultato (continuo) a partire dal nuovo set di dati.</li></ol><p><em>Non c’era nulla di più adatto della regressione per prevedere la posizione futura del player, basandoci sui dati attuali dello stesso!</em></p><p>Questa osservazione ci ha illuminati indicandoci la via da seguire nella creazione della <em>mente</em> da fornire al nostro spawner. Abbiamo quindi individuato le informazioni utili a creare il nostro data set:</p><ol><li><strong>PVA</strong>, Player Vertical Acceleration;</li><li><strong>PVS</strong>, Player Vertical Speed;</li><li><strong>PAVP</strong>, Player Actual Vertical Position;</li><li><strong>PFVP</strong>, Player Future Vertical Position.</li></ol><p>Ora, per poter applicare la tecnica di regressione per costruire il nostro modello, avevamo bisogno di raccogliere le osservazioni, quindi i dati reali, che avremmo poi utilizzato per costruire la nostra<strong> matrice di funzioni </strong>(l’insieme di variabili indipendenti PVA, PVS e PAVP) e il nostro <strong>vettore di variabili dipendenti</strong> (i valori PFVP). Per fare questo abbiamo aggiunto al progetto originario di SpaceRace una classe (<strong>JsonManager.swift</strong>) che permettesse di salvare, in un file <strong>.json,</strong> le registrazioni dei valori PVA, PVS, PAVP e PFVP relativi al player durante una sessione di gioco. Inserendo una funzione per la registrazione di questi dati nel <strong>GameScene</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CfknzOvpwB3gMXLCHWICeQ.png" /></figure><p>abbiamo ottenuto una serie di osservazioni rappresentabili nel seguente data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGeKJ9KgSz2r2OEQPFxq0Q.png" /><figcaption>Sottoinsieme delle osservazioni registrate durante la sessione di gioco</figcaption></figure><p>Cosa farne con tutti questi dati?</p><p>Come detto in precedenza queste osservazioni ci sono servite per costruire il nostro modello. Come? Affidandoci a lui…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TnFBK2SA1QPqNVSNTbMrQ.jpeg" /><figcaption><a href="https://simple.wikipedia.org/w/index.php?title=Deep_Thought&amp;redirect=no">Deep Thought</a> Super Computer</figcaption></figure><h4>The answer is… 42</h4><p>Ok non è vero, non ci siamo affidati a Deep Thought, anche perché non avremo potuto attendere tutto quel tempo computazionale per ottenere alla fine un semplice 42.</p><p>Ci siamo affidati a qualcosa di più potente che ci permettesse di ottenere un modello affidabile per il nostro spawner. Abbiamo quindi creato un progetto in Create ML utilizzando la regressione come template di generazione.</p><p>Come visto in precedenza, la regressione è un tipo di SL che utilizza un algoritmo (basato sulle <a href="https://en.wikipedia.org/wiki/Artificial_neural_network">reti neurali</a>) che sfrutta un concetto matematico, <a href="https://en.wikipedia.org/wiki/Regression_analysis">regression analysis</a>, che potremmo riassumere in maniera semplice nel seguente modo: <em>dato un numero di variabili indipendenti (explanatory) e un numero di variabili dipendenti associate (outcome o target) si cerca di trovare una relazione tra queste variabili che permetta di prevedere un risultato.</em></p><p>Nel progetto CreateML abbiamo fornito il nostro data set di osservazioni dividendolo in <strong>training data</strong>, utilizzato dal ML per cercare di capire la relazione tra i dati, e <strong>test data</strong>, utilizzato per verificare le previsioni. A questo punto CreateML ha fatto il lavoro sporco per noi: processando le osservazioni nella ricerca di relazioni tra i dati, facendo previsioni di risultati e verificandoli, ed infine generando un modello di conoscenza da utilizzare con nuovi dati.</p><p>Non restava che testare il nostro modello in SpaceRace. Per fare questo abbiamo importato nel nostro progetto il modello generato da CreateML, e grazie a CoreML lo abbiamo potuto utilizzare per modificare nel GameScene il comportamento del nostro spawner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kB91Q1MvSy_8mFl9-C2urQ.png" /></figure><p>Come potete vedere analizzando il codice, abbiamo affidato al nostro modello (<strong>test1_1</strong>)la scelta della posizione (<strong>verticalFuturePosition</strong>) nella quale generare spazzatura spaziale per colpire il player. Una volta terminate le modifiche abbiamo fatto delle sessioni di gioco e sapete cosa abbiamo scoperto?</p><h4>It could work!</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4An1BrG2u_4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4An1BrG2u_4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4An1BrG2u_4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ca965a34d7ceb6a1152505744f1c950/href">https://medium.com/media/8ca965a34d7ceb6a1152505744f1c950/href</a></iframe><p>Ha funzionato! Semplice ma efficace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*5bfaBmth220qbSEq7mmxOg.gif" /></figure><p>Osservando il radar di collisione in basso a sinistra potete osservare come lo spawner arrivi ad anticipare il player nei suoi spostamenti, trasmettendo al player la sensazione di avere di fronte un entità intelligente.</p><p>Semplice nel complesso, questo primo approccio con il ML ci ha permesso di ottenere un comportamento basato sulla conoscenza da assegnare al nostro spawner!</p><p>Quindi tornando alla nostra considerazione iniziale, è questa la strada da intraprendere per sfruttare il ML ed arrivare ad ottenere un videogioco di successo?</p><h4>Roads… Where we’re going we don’t need roads</h4><p>No, questa non è la strada. Questa è solo una delle tante strade… Utilizzando CreateML e CoreML possiamo applicare gradi di complessità che tengano in considerazione ulteriori aspetti, creando così comportamenti diversi come:</p><ul><li>spawner compassionevole, che da tregua ad un player danneggiato generando più repair kit e meno space junk;</li><li>spawner caritatevole, che genera refills fino a quando il player non riempie i suoi serbatoi;</li><li>spawner strategico, che genera space junk costringendo il player in una posizione di svantaggio e che lo porterà inesorabilmente alla sconfitta.</li></ul><p>Non siete eccitati? Noi lo siamo! Considerando quindi le innumerevoli possibilità forniteci da iOS, CreateML e CoreML, diventa anche inutile parlare di strade, perché come piace dire a noi:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FG3AfIvJBcGo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DG3AfIvJBcGo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FG3AfIvJBcGo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/302de770ad3720ebf2edc0a70fa11874/href">https://medium.com/media/302de770ad3720ebf2edc0a70fa11874/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*RviHqzBhcek6ETS6rpW86A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27982297e2d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>