<?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 Maxim Kerstens on Medium]]></title>
        <description><![CDATA[Stories by Maxim Kerstens on Medium]]></description>
        <link>https://medium.com/@maximkerstens?source=rss-6569fbb4dc8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z1woSNApuxH2gV5KpDSdDQ.jpeg</url>
            <title>Stories by Maxim Kerstens on Medium</title>
            <link>https://medium.com/@maximkerstens?source=rss-6569fbb4dc8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:02:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maximkerstens/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[Vue.js explained through Pokemon #5 Transitions & animation]]></title>
            <link>https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-5-transitions-animation-7bfc70e01d3d?source=rss-6569fbb4dc8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bfc70e01d3d</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Maxim Kerstens]]></dc:creator>
            <pubDate>Sun, 05 Mar 2017 08:24:41 GMT</pubDate>
            <atom:updated>2017-03-05T08:50:09.392Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the fifth article in my tutorial series that tries to explain Vue.js concepts by recreating the battle scene from Pokemon.</p><p><a href="https://medium.com/coding-artist/vue-js-pokemon-battle-tutorial-380cd72eb681#.uxu24s175">Original tutorial</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-ac49516ba5d3#.tsdw87je2">#1 Single file components</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-2-refs-promises-event-bus-79b705498f0#.b469349ut">#2 Attacks: $refs, Promises &amp; event bus</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-b4779c83b245">#3 Vuex: state management</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-4-damage-calculations-a3065f0b1761#.66tlul63e">#4 Damage calculations</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-5-transitions-animation-7bfc70e01d3d#.x63vnlh2c">#5 Transitions &amp; animation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nzpjpGL1gTdSlhtvdyCZQ.jpeg" /></figure><p>Let’s spruce our battle stage up in this article we’re going to be adding some basic animations on the pokemon when they attack or get hit.</p><p>We’ll also add a transition for when a pokemon enters the battle stage or faints and disappears.</p><p>Lastly we’ll be added attack effectiveness messages (damage reports like; the amount of damage an attack did, or show when it was super effective).</p><p>For animations we’ll be using <a href="https://github.com/julianshapiro/velocity">velocity.js</a>, Vue has a standard transition implementation baked in.</p><h3>Transitions</h3><p><a href="https://vuejs.org/v2/guide/transitions.html">Transitions</a> are a type of animation that’s applied to elements that (dis)appear through v-if or v-show conditions.</p><p>In order to define a transition we’ll have to wrap the elements we want to apply the transition to with a &lt;transition&gt; component. On this component we can define the name of the transition we’ll use. Next to that we’ll also need to create a few CSS classes that actually define the animation of the transition, these class names would be prefixed with the transition’s name.</p><p>A &lt;transition&gt; component also give you the option to use hooks, this way, instead of using CSS, you could use javascript to animate the element.</p><h4>Transitioning pokemon components</h4><p>When a pokemon enters a screen or faints we’ll simply make the pokemon enter from the top and leave from the bottom while we apply a fade effect.</p><p>We’ll name this transition ‘pokemon-image’.</p><p>Let’s create a style tag in <em>pokemon.vue</em> and define the transition css classes there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15d1db1cbe8c77ddcf7473451c718a89/href">https://medium.com/media/15d1db1cbe8c77ddcf7473451c718a89/href</a></iframe><p>We have defined 4 CSS classes to define the transition, however, Vue allows you to define up to 6 classes for every stage of a transition.</p><p>Let’s go over these stages so you’ll know when the CSS classes we’ve defined above are being added to the element:</p><ul><li><strong>{transition}-enter:</strong> Starting state for enter. Added before element is inserted, removed one frame after element is inserted.</li><li><strong>{transition}-enter-active:</strong> Active state for enter. Applied during the entire entering phase. Added before element is inserted, removed when transition/animation finishes.</li><li><strong>{transition}-enter-to:</strong> Ending state for enter. Added one frame after element is inserted (at the same time <em>{prefix}-enter</em> is removed), removed when transition/animation finishes.</li><li><strong>{transition}-leave:</strong> Starting state for leave. Added immediately when a leaving transition is triggered, removed after one frame.</li><li><strong>{transition}-leave-active:</strong> Active state for leave. Applied during the entire leaving phase. Added immediately when leave transition is triggered, removed when the transition/animation finishes.</li><li><strong>{transition}-leave-to</strong>: Ending state for leave. Added one frame after a leaving transition is triggered (at the same time <em>{prefix}-leave</em> is removed), removed when the transition/animation finishes.</li></ul><p>Now that we have defined our transition’s animation, let’s add it around the pokemon’s image:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07213b9914077c3878ac64443569985e/href">https://medium.com/media/07213b9914077c3878ac64443569985e/href</a></iframe><p>As you can see we assigned 2 attributes to the transition component.</p><p>By defining <em>appear</em> we’re actually saying ‘also apply the animation on the initial render’. <em>Name</em> describes the prefix for the de CSS classes.</p><p>That’s all we had to do to get our start/faint animations working.</p><h4>Attack/hit animations</h4><p>Next we’re going to add 2 new animations, we want to show the action of a pokemon actually attacking or taking damage.</p><p><a href="http://velocityjs.org/">Velocity</a> simplifies that task greatly, it’s an animation engine with the same API as jQuery.animate.</p><p>It comes with a <a href="http://velocityjs.org/#uiPack">UI-pack</a> that bundles some basic effects, but it also let’s you define your own sequenced effects.</p><p>For simplicity’s sake we’re just going to be using a few of the predefined effects in this step, in the next step we’ll implement our own custom defined animations.</p><p>We can use Velocity on its own, which is good since we don’t have jQuery or Zepto installed.<br>Because of that, Velocity attaches itself to the window object, so you can trigger an effect through the Velocity function:</p><p><strong>Velocity</strong>(<em>element</em>, <em>predefined effect</em>)</p><p>Let’s go ahead and open up <em>Pokemon.vue </em>and add our the animations in the attack method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b9fb2407515e6b8ecb8af719a6d75f6/href">https://medium.com/media/7b9fb2407515e6b8ecb8af719a6d75f6/href</a></iframe><p><em>this.pokemonImageId</em> is the actual id of our pokemon’s image(which will be either player-pokemon or opponent-pokemon), we’ll be executing the <em>callout.pulse</em> effect. This effect will quickly expand and shrink the pokemon’s image once.</p><p>We’ll place this line above the first time we change the <em>battleText</em> property in our attack method.</p><p>Next we’ll show the defending pokemon taking a hit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df14cd8dadc336c02d3ae979c63d101d/href">https://medium.com/media/df14cd8dadc336c02d3ae979c63d101d/href</a></iframe><p>We’ll place this piece of code right after defining the <em>attackPower</em> constant.</p><p>That’s livened up the battle a little.</p><h3>Attack effectiveness</h3><p>In the original game, when the effectiveness multiplier wasn’t 1, you would see a string appear describing its strength (immune, weak, super effective or even critical hit).</p><h4>Functionality</h4><p>We can implement this by firing an <em>attack.effect</em> event in the <em>Damage</em> class we created.</p><p>Every pokemon component will have to listen to the event in order for them to update their battle text, so we’ll have to prefix the event with the pokemon component’s type.</p><p>We’ll also need to implement a very simple queue-like behaviour for this, since it’s possible an attack can be very effective, as well as a critical hit.</p><p>Let’s get started and open up Pokemon.vue, we’ll add 2 new data properties called <em>attackEffect</em>, set it to false and battleEffectQueue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/609361f5e25569c9707eb4d21b6dbeca/href">https://medium.com/media/609361f5e25569c9707eb4d21b6dbeca/href</a></iframe><p>When there’s an attack effect, we’ll fill the battleEffect property with a string, after the animation is done we’ll set it back to false again.</p><p>Let’s implement that in a new method called <em>showAttackEffect</em>, which we’ll place right under <em>calculateDamage</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea9e7b2c59be30042589060b4bc80c66/href">https://medium.com/media/ea9e7b2c59be30042589060b4bc80c66/href</a></iframe><p>We’ll also need to set up a watcher, We can do this by defining the property we want to watch for changes, if a change happens we can say what should happen.</p><p>Which is perfect for our queue, we’ll want to watch the <em>attackEffect</em>, if it’s set to false and there’s something in our <em>battleEffectQueue</em>, we can update the <em>attackEffect</em> again.</p><p>We’ll do this by adding a watch property to our Vue instance definition (right after the computed properties). This will always be an object.</p><p>Next we define a method, the method’s name should match the data property we’re watching. This method will always get 2 parameters: the newly set value and the previous value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3033f24cb0e6121f815f09c1e6085595/href">https://medium.com/media/3033f24cb0e6121f815f09c1e6085595/href</a></iframe><p>We’re nearly done in this component, there’s just 2 small tidbits left to do; listen for the <em>{type}.attack.effect</em> event and find a way to pass that <em>type</em> to the damage class.</p><p>We should setup the event listener once the component has mounted, so let’s add a mounted method to our Vue instance definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5724dbcf51fe8248ffc1b55bcb0c48a0/href">https://medium.com/media/5724dbcf51fe8248ffc1b55bcb0c48a0/href</a></iframe><p>Lastly we’ll edit the <em>calculateDamage</em> method, we’ll pass the <em>otherPokemon</em> property. This way we can tell the attack effects (if there are any) that they have to displayed on that other pokemon component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c878ccb21fea4d8c4ac29f541067ea07/href">https://medium.com/media/c878ccb21fea4d8c4ac29f541067ea07/href</a></iframe><p>It’s time to start firing the events, let’s open up <em>Damage.js</em> and tweak the <em>power</em> method to take its new argument and pass it along to the methods that will be firing the attack effect event:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce0051ef9c46e3f1d169676aea35e08e/href">https://medium.com/media/ce0051ef9c46e3f1d169676aea35e08e/href</a></iframe><p>Next we’ll start firing the attack effects in <em>calculateTypeEffect</em>. If the multiplier that’s calculated there is not 1 we’ll fire specific events at the end of the method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7162a9e37db68fbbd6d0e3f8f376547/href">https://medium.com/media/c7162a9e37db68fbbd6d0e3f8f376547/href</a></iframe><p>Lastly we’ll do the same for critical hits:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fed6fa5d647e3e58ed2980edf6a576b/href">https://medium.com/media/8fed6fa5d647e3e58ed2980edf6a576b/href</a></iframe><h4>Template</h4><p>Now that we’ve got the functionality out of the way, it’s time to display the attack effects.</p><p>We’ll do this by placing a new div right above the component’s pokemon image. When there’s an effect we want it to fade in and go up before disappearing again.</p><p>Let’s go back to <em>Pokemon.vue</em> and add the HTML:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac6f7ac43c0c98de01cd4dd8ee0a6452/href">https://medium.com/media/ac6f7ac43c0c98de01cd4dd8ee0a6452/href</a></iframe><p>Remember that we defined the <em>attackEffect</em> property with a false value and we’re resetting it to false after it was set to a string?</p><p>the <em>v-if</em> directive picks up on that, it will show the div if <em>attackEffect</em> is not false.</p><p>Next, let’s add the styling for our div in the style tag:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42581fafd95dc61cbf20102198a4b024/href">https://medium.com/media/42581fafd95dc61cbf20102198a4b024/href</a></iframe><h4>Transitions</h4><p>It’s time to add some flair to our attack effects.</p><p>We could just define a CSS transition again, or use one of Velocity’s predefined animations, but let’s build a custom transition.</p><p>I’m even going to be taking it a little bit further, if we look ahead you’ll probably also want to add attack-specific animations. We can’t start defining them in our pokemon component because it will bloat quickly.</p><p>Instead, let’s make an animation registry, where we can define every animation (or later on even split that into pieces).</p><p>How would we go about this? The only way to make <a href="https://vuejs.org/v2/guide/transitions.html#Reusable-Transitions">reusable transitions</a> is by defining them as components. These components will have a transition component as their root element.</p><p>We will assign them content (the HTML you would place between the component’s opening and closing tag) and render them in the component’s template function, within the root transition element. You would use the <a href="https://vuejs.org/v2/guide/components.html#Single-Slot"><em>&lt;slot&gt;&lt;/slot&gt;</em> element</a> for this.</p><p>Vue offers functional components, these allow for a very simple setup where state isn’t really important. We’ll be using Velocity to animate, so we’ll be making use of <a href="https://vuejs.org/v2/guide/transitions.html#JavaScript-Hooks">javascript hooks</a> for the transitions.</p><p>Let’s put that into code, let’s create a new file in the <em>src/</em> folder, called <em>animations.js</em>. We’ll keep this simple for now, the file will export an object.</p><p>This object will have an animations property, which will be an array containing our animation definitions.</p><p>We’ll also add a register method, this method will convert our animations into components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ea2fdd0660141e14e5ee968fa7c84fc/href">https://medium.com/media/8ea2fdd0660141e14e5ee968fa7c84fc/href</a></iframe><p>As you can see we define our transition templates in 4 properties:</p><ul><li><strong>tag</strong>: The name of the tag you’ll be using for this component (it will also be used to name the transition in case you want to also throw in a CSS-based animation).</li><li><strong>onAppear</strong>: Should the transition also happen when the html content is rendered for the first time.</li><li><strong>css</strong>: Are there any CSS animations with the same name that should be loaded?</li><li><strong>events</strong>: These are the actual animation hooks you want to apply on the element when it appears/disappears.</li></ul><p>The <em>register</em> method take Vue as a parameters, loops through the defined animations and registers them as components.</p><p>Let’s open up <em>main.js</em> and implement it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba4190c359c23878fd8e1d029296aeae/href">https://medium.com/media/ba4190c359c23878fd8e1d029296aeae/href</a></iframe><p>All that’s left to do is open <em>Pokemon.vue again </em>and wrap the div we used to render <em>attackEffect</em> in our custom <em>&lt;transition-attack&gt;</em> component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3695a1cc5a932d580b600bd0ceea9654/href">https://medium.com/media/3695a1cc5a932d580b600bd0ceea9654/href</a></iframe><p>That concludes this article, I’ve shown you how you can implement CSS transitions, transitions based on javascript hooks and how to build reusable transitions.</p><p>You can find the code on github (code specific to this article is in the chapter-5 branch)</p><p><a href="https://github.com/happyDemon/learning-vue-through-pokemon">happyDemon/learning-vue-through-pokemon</a></p><p>See you next time</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bfc70e01d3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js explained through pokemon]]></title>
            <link>https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-4-damage-calculations-a3065f0b1761?source=rss-6569fbb4dc8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3065f0b1761</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[damage-calculation]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[pokemon]]></category>
            <dc:creator><![CDATA[Maxim Kerstens]]></dc:creator>
            <pubDate>Fri, 03 Mar 2017 07:16:46 GMT</pubDate>
            <atom:updated>2017-03-05T08:50:49.848Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vue.js explained through pokemon #4 Damage calculations</h3><p>This is the fourth article in my tutorial series that tries to explain Vue.js concepts by recreating the battle scene from Pokemon.</p><p><a href="https://medium.com/coding-artist/vue-js-pokemon-battle-tutorial-380cd72eb681#.uxu24s175">Original tutorial</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-ac49516ba5d3#.tsdw87je2">#1 Single file components</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-2-refs-promises-event-bus-79b705498f0#.b469349ut">#2 Attacks: $refs, Promises &amp; event bus</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-b4779c83b245">#3 Vuex: state management<br></a><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-4-damage-calculations-a3065f0b1761#.66tlul63e">#4 Damage calculations</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-5-transitions-animation-7bfc70e01d3d#.x63vnlh2c">#5 Transitions &amp; animation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOH5fsK1SSe5zteaDvAb8Q.jpeg" /></figure><p>Welcome to the fourth installment, this time around we won’t be learning about specific Vue concepts, rather about specific pokemon attack damage calculations.</p><p>I’m sure you’ve noticed from the previous article that there’s pokemon that have attacks that do more damage than some pokemon do. You might also be missing the fact that the original game didn’t always hand out the same damage.</p><p>At first the damage formulas might seem daunting, but let’s break the down piece by pieces</p><h3>The damage formula</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*1qmKthzqDTITVxzYNcUBmg.png" /><figcaption><a href="http://bulbapedia.bulbagarden.net/wiki/Damage">http://bulbapedia.bulbagarden.net/wiki/Damage</a></figcaption></figure><p>In order to calculate an attack’s damage we’ll have to take quite a few things into consideration:</p><ul><li>Level: attacking pokemon’s level</li><li>Power: the attack’s power</li><li>A: the attacking pokemon’s attack stat (if it’s a physical type) or special stat (if it’s a special attack, one that adds a status effect).</li><li>D: the defending pokemon’s defense stat.</li></ul><p>We’ll discuss the modifier in the next step.</p><h3>Modifier formula</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*RkFK2i5frI-H1sb-a5QasA.png" /><figcaption><a href="http://bulbapedia.bulbagarden.net/wiki/Damage">http://bulbapedia.bulbagarden.net/wiki/Damage</a></figcaption></figure><ul><li>STAB: short for same-type-attack-bonus, meaning that if the attack type is one of the pokemon’s, a bonus is added.</li><li>Type: Will compare the attack type to the defending pokemon’s type through a chart. This chart maps out how effective the attack between types will be. (0 for no effect, 0.5 for weak, 2 for super effective).</li><li>Critical: Will add double damage, the probability of it happening is based on the pokemon’s level &amp; speed.</li><li>other: this is a modifier that comes from items or that can occur in specific attack situation. Most of the time this is just 1.</li><li>Lastly a random percentage is applied between 85% &amp; 100%</li></ul><h3>Implementation</h3><p>Let’s translate the battle formulas into a <em>Damage</em> class we can use in our components.</p><h4>Type chart</h4><p>We’ll also need a list of each type’s weaknesses and strength to calculate type effectiveness.</p><p>Let’s create a data folder, we’ll create a file there called <em>typeChart.js</em> and place the following in there:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff69034a5cc17379cfebaa817da1571/href">https://medium.com/media/0ff69034a5cc17379cfebaa817da1571/href</a></iframe><p>Each type consist of an object with 3 properties:</p><ul><li>immunes: attacks against these types will do zero damage.</li><li>weaknesses: attacks against these types will do half the damage.</li><li>strengths: attacks against these types will do double damage.</li></ul><h4>Damage class</h4><p>Let’s go back to our <em>src</em> folder and create a file called <em>Damage.js</em>.<br>We’ll be creating our class here.</p><p>The reason why we’re defining the damage calculations in a class is just because we can split our code into multiple functions, each having their own responsibility. This makes it easier to read and maintain the code.</p><p>Let’s dive in, through a constructor we’ll need to assign the class some basic properties like the attacking pokemon, the defending pokemon and the attack definition that’s being used. We’ll also import the type char for easy reference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eac659a6cbb6973c3d543f9970314f67/href">https://medium.com/media/eac659a6cbb6973c3d543f9970314f67/href</a></iframe><p>Next let’s create a new method in the class called <em>calculateStatsPower</em>, here we’ll translate the damage formula, without the modifier included:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f12a27c07acd20639f5dc2440024b41c/href">https://medium.com/media/f12a27c07acd20639f5dc2440024b41c/href</a></iframe><p>Next we’ll start defining our modifiers, each will get its own method.<br>Let’s start with calculating STAB:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab23749659e05e51838fb3f946247122/href">https://medium.com/media/ab23749659e05e51838fb3f946247122/href</a></iframe><p>Remember the pokedex.json file? Each pokemon has a type property that’s an array. Here we’re just checking if the attack type if present.</p><p>Next let’s calculate the type effect. We’ll have to check attack’s type for strengths and weaknesses. We’ll do this for every type the opponent’s pokemon has:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dac73231f1eaf68ea82da4b5504dd04/href">https://medium.com/media/6dac73231f1eaf68ea82da4b5504dd04/href</a></iframe><p>Let’s get on to calculating the critical hit, this one’s a doosie.</p><p>Calculating the actual modifier isn’t that hard. If it happens the modifier’s strength is based on the attacking pokemon’s level (higher leveled pokemon should get a bigger bonus).</p><p>We’ll also have to create a random number (0–255), in order for the critical hit to land that random number should be lower than a threshold.</p><p>This threshold will be based on the attacking pokemon’s speed. If the attack type is normal we’ll divide the speed by 512, if it’s any other attack type we’ll divide the attacking pokemon’s speed by 256.</p><p>This way normal attacks have half the chance to deliver critical hits.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb64cabb56d07a09c6dc7d19d5b90629/href">https://medium.com/media/eb64cabb56d07a09c6dc7d19d5b90629/href</a></iframe><p>The other modifier we can’t really implement yet since we don’t have items or attacks that give boosts. We’ll define the method anyway and just return 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94d890e6a95055d65f16a7121359de66/href">https://medium.com/media/94d890e6a95055d65f16a7121359de66/href</a></iframe><p>Let’s call all those calculation methods in a method called ‘<em>power</em>’, this is the only method we’ll be calling from the outside.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca0b315615d63976d7b4210c594113a2/href">https://medium.com/media/ca0b315615d63976d7b4210c594113a2/href</a></iframe><h4>Finalising</h4><p>Last, but not least, we’ll import our damage class in <em>Pokemon.vue</em> and replace the contents of our old <em>calculateDamage</em> method.</p><p>Right after the import statement we already have for our Vuex helper we’ll put this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7fb24500e2a46dfedce7b6159e20459/href">https://medium.com/media/d7fb24500e2a46dfedce7b6159e20459/href</a></iframe><p>and we’ll replace the <em>calculateDamage</em> method with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ee0b89f0db85fad8e74931f54b49e88/href">https://medium.com/media/5ee0b89f0db85fad8e74931f54b49e88/href</a></iframe><p>That’s it, we’re done implementing pokemon’s attacks for now.</p><p>You could still implement ‘categorised attacks’, the original game offers: normal, special and status as attack categories. Implement the battle logic for them in the <em>calculateOther </em>and<em> calculateStatsPower </em>method of the <em>Damage</em> class. Item effects could be taken into account, program in multi-stage attacks, you’re free to do whatever you’d like.</p><p>In the next article we’ll be looking at animation and transitions, we’ll also start displaying attack effects like ‘critical hit’, ‘very effective’, ‘not very effective’ and ‘had no effect’. We’ll also display the damage done.</p><p>You can find the code on github, code specific to this article has been posted under the chapter-4 branch.</p><p><a href="https://github.com/happyDemon/learning-vue-through-pokemon">happyDemon/learning-vue-through-pokemon</a></p><p>If you have any questions or suggestions, just open up a ticket on the repo and I’ll be sure to get to it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3065f0b1761" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js explained through pokemon]]></title>
            <link>https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-b4779c83b245?source=rss-6569fbb4dc8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4779c83b245</guid>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Maxim Kerstens]]></dc:creator>
            <pubDate>Thu, 02 Mar 2017 07:28:51 GMT</pubDate>
            <atom:updated>2017-03-05T08:49:44.708Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vue.js explained through pokemon #3 Vuex: state management</h3><p>This is the third article in my tutorial series that tries to explain Vue.js concepts by recreating the battle scene from Pokemon.</p><p><a href="https://medium.com/coding-artist/vue-js-pokemon-battle-tutorial-380cd72eb681#.uxu24s175">Original tutorial</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-ac49516ba5d3#.tsdw87je2">#1 Single file components</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-2-refs-promises-event-bus-79b705498f0#.b469349ut">#2 Attacks: $refs, Promises &amp; event bus</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-b4779c83b245">#3 Vuex: state management</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-4-damage-calculations-a3065f0b1761#.66tlul63e">#4 Damage calculations</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-5-transitions-animation-7bfc70e01d3d#.x63vnlh2c">#5 Transitions &amp; animation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBIwcqG7VFbGcffV1bY7Jw.png" /></figure><p>In this article we’re going to start tackling our state in a different way.</p><p>Let’s continue on the event-based implementation of last tutorial:</p><p><a href="https://github.com/happyDemon/learning-vue-through-pokemon/tree/chapter-2-events">GitHub - happyDemon/learning-vue-through-pokemon at chapter-2-events</a></p><p>In the previous articles we talked about isolated state, the data that each component carried with it. This is great for small apps, but when your app starts growing you’ll soon notice your data methods filling up, making it harder to see what data is contained.</p><p>Our pokemon app is still small, but once we start adding a more traditional attack system it’ll grow quickly, when we add more pokemon and items it’ll become unmanageable if we keep all our stored data together in a component.</p><p>Our main focus is separating the data while still keeping everything reactive and logically stored. Preferably by the means of a common standard, so friends or colleagues can jump in when needed.</p><p>Enter <a href="https://vuex.vuejs.org/en/#">Vuex</a>, it’s a state management library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.</p><p>This brings a bunch of benefits, one thing you should note is that you won’t be able to change Vuex <a href="https://vuex.vuejs.org/en/state.html">state</a> directly, unlike local state, to ensure the predictability.</p><p>Instead you can commit <a href="https://vuex.vuejs.org/en/mutations.html"><em>mutations</em></a> to the state tree or dispatch <a href="https://vuex.vuejs.org/en/actions.html"><em>actions</em></a>.</p><p><a href="https://vuex.vuejs.org/en/mutations.html"><em>Mutations</em></a> are functions that directly change a specific part of the state tree.</p><p><a href="https://vuex.vuejs.org/en/actions.html"><em>Actions</em></a> are meant to commit mutations, they have a more async-nature to them. An action could do a request to your server, take the required data from its response and commit what is needed. In the simplest of uses it can be used to commit multiple mutations.</p><p>But wait, there’s something missing, what about computed properties?<br>Vuex offers <a href="https://vuex.vuejs.org/en/getters.html">getters</a> as an alternative.</p><p>Retrieving getters is a little more verbose than computed properties, but I personally don’t mind the tradeoff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*vmhxmp5jRp-4Rtfh3skrgQ.png" /><figcaption>Vuex state changes</figcaption></figure><p><strong>Note:</strong> As a general rule you should presume that everything you define in a store shouldn’t be accessed directly. There are wrappers in place.</p><p>By this I mean that within actions, getters or mutations you shouldn’t try to access the state, getters, mutations or actions through ‘<em>this</em>’.</p><p>Let’s rethink our app’s state and translate it to Vuex.</p><h3>New data structure</h3><p>Let’s begin in <em>App.vue</em>, at the moment we have our player and opponent pokemon grouped and hard coded.</p><p>We’ll want to change that to having a pokedex and selecting the 2 pokemon from that list. This will also affect the pokemon component.</p><p>We’ll also want to separate the <em>fightOptions</em> computed property into a getter.<br>We’ll add a mutation that allows us to change a player’s or opponent’s HP.<br>Lastly, resetting all the pokemon’s HP will have to made into an <em>action</em>.</p><p>Since we’re extracting our data to a global store, we don’t need to assign a pokemon to a pokemon component, we’ll just retrieve it in the component itself.</p><p>In <em>Pokemon.vue</em> We’ll want to change any statement that tries to change the parent component’s state. This means we’ll have to create a mutator for handling HP changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMiS376A1cFRfncahnUB4w.jpeg" /><figcaption>Store definition overview</figcaption></figure><p>That’s nice and all, but let’s convert that to actual code.</p><p>Let’s pull in vuex</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53bffa29b948c0fe886f5815eca9d6fc/href">https://medium.com/media/53bffa29b948c0fe886f5815eca9d6fc/href</a></iframe><h4>Defining the store</h4><p>While you’re waiting for that to install let’s create a ‘<em>store</em>’ folder, this is where we’ll define our Vuex store.<br>Within it we’ll also add a ‘<em>data</em>’ folder, we’ll make our <em>pokedex.js</em> there:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c24d00f10c1158d5cd4c03a9ff2eb1/href">https://medium.com/media/d4c24d00f10c1158d5cd4c03a9ff2eb1/href</a></iframe><p>Feel free to add any pokemon you’d like, I used <a href="http://bulbapedia.bulbagarden.net/wiki/List_of_Pok%C3%A9mon_by_base_stats_(Generation_I)">bulbapedia</a>’s generation 1 chart for stats and attacks.</p><p>Let’s go back to the ‘store’ folder and get into defining our state.</p><p>We’ll create an <em>index.js</em> file, here we’ll import Vuex and connect it with Vue.</p><p>Next we’ll define our store with the needed state, getters, mutations and actions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1ed77079ca2fcf3b8c3c29527efe6e2/href">https://medium.com/media/b1ed77079ca2fcf3b8c3c29527efe6e2/href</a></iframe><p>Remember when I said nothing should be accessed directly?</p><p>Each of our getters and mutation methods will always get <em>state</em> as their first parameter. This will always be the most recent version of the state we have defined.</p><p>The action that we defined will get the state’s context assigned, this means we actually get a reference to the store. We can access the state through this, as well as other actions, mutations and getters.</p><p>If we want to retrieve or change anything we’ll have to do it through that first parameter.</p><p>Most of the comments explain enough, however I’m using <a href="https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operatoren/Destructuring_assignment#Object_destructuring">object destructuring</a> for <em>setHP </em>and<em> reset</em>.</p><p>The reason for this is because mutations only get 2 parameters.<br>If you want to assign more data you’ll have to group it in an object.<br>object destructuring is a nice way to show what properties you’re expecting.</p><h4>Glue it in</h4><p>Now that we have our store defined, let’s make use of it.</p><p>It’s time to open <em>main.js</em>, we’ll import the store and assign it to our root Vue definition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b01a942f1f15fe5849bb005b57354a37/href">https://medium.com/media/b01a942f1f15fe5849bb005b57354a37/href</a></iframe><p>Once the store has been assigned, you can access it through <em>this.$store</em> from the instance it’s been assigned to, as well as every child instance (components).</p><h3>Accessing the store</h3><p>We can access anything we’ve defined in our store, <em>state</em> an <em>getters</em> are pretty straight forward, <em>mutations</em> can be called through <em>commit</em>:</p><ul><li>state: this.$store.state.<strong>property</strong></li><li>getters: this.$store.getters.<strong>property</strong></li><li>mutations: this.$store.commit(‘<strong>mutation</strong>’, payload)</li><li>actions: this.$store.dispatch(‘<strong>action</strong>’, payload)</li></ul><p>Remember, we can’t set values on state and getters, that’s what mutations and actions are for.</p><p>You can reference state and getters as shown above, however you could also map them as computed properties, that way you can reference them in your Vue instance like you’re used to doing.</p><p>The same is true for mutations and actions, you would reference these in your Vue instance’s methods.</p><p>You would end up with something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/757f400935aef32f1581e64bc76c0015/href">https://medium.com/media/757f400935aef32f1581e64bc76c0015/href</a></iframe><p>That works, but Vuex comes with a few helpers that can reduce our code; <em>mapState</em>, <em>mapGetters, mapMutations </em>and<em> mapActions</em>.</p><p>These helpers use the same footprint for their parameters, i’ll show you a few examples with <em>mapState</em> and <em>mapGetters</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1fd1b2516aa8be0cd10a910d58ebfdd/href">https://medium.com/media/e1fd1b2516aa8be0cd10a910d58ebfdd/href</a></iframe><p>I’m using the <a href="https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a> here because those functions return an object, both object need to be merged into the computed property object.</p><h4>Implementing the store</h4><p>Let’s start by opening App.vue, first let’s get rid of the pokemon attribute on the pokemon components</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb1e6df8f645917b001afb23e9b041bb/href">https://medium.com/media/bb1e6df8f645917b001afb23e9b041bb/href</a></iframe><p>On to the script tag, let’s import the Vuex helper we need, just like in the previous example.</p><p>We’ll start by cleaning our data method and remove everything until <em>battleText</em>, <em>battleOptions</em> and <em>menu</em> are left.</p><p>We’ll map the needed computed properties (<em>player</em> and <em>playerAttacks</em>).</p><p>While we’re at it, let’s change all the strings that references <em>this.player.pokemon.name</em> to literal strings, so they’re cleaner.</p><p>We’ll also map the <em>reset</em> action as <em>resetPokemon</em> in our methods and replace the old code that reset the pokemon’s HP directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1225f088877556916d8ebb7634711023/href">https://medium.com/media/1225f088877556916d8ebb7634711023/href</a></iframe><p>Lastly we’ll also need to find a way to actually set the player and opponent pokemon.</p><p>Vue.js has various <a href="https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks">lifecycle hooks</a>, we’re already using one, the mounted method on the Vue instance definition, where we set up our event listeners.</p><p>We’re going to be using the create hook to setup the pokemon. By doing it in this hook we’ll be sure that the pokemon are set before <em>App.vue </em>gets mounted (displayed in the DOM). This also means we’re setting up the global store before it gets accessed through the computed properties we setup.</p><p>As you can see in the snippet above, we placed the created method right above our existing mounted method.</p><p>Now that our battle stage is ready, let’s dive into <em>Pokemon.vue</em>.</p><p>Let’s go over our to do list:</p><ul><li>Let’s remove the pokemon prop, it’s not needed anymore</li><li>We’ll also setup computed properties for the local pokemon (the one this component was set up for) and it’s opponent.</li><li>The pokemon image :src needs to change since we switched to the <em>pokemon.images{front,back}</em> structure instead of just a string. We’ll setup a computed property for this.</li><li>All references to <em>this.pokemon</em> and <em>this.opponent</em> need to be replaced.</li><li>Changes made to pokemon HP need to be changed to using the <em>setHP</em> mutator.</li><li>We’ll also need to change the way the width of the HP bar is calculate since we’re there’s a slim chance the pokemon will have a 100 HP stat.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c2b5bbd0b0d6fb8692fda59be1ce8ee/href">https://medium.com/media/1c2b5bbd0b0d6fb8692fda59be1ce8ee/href</a></iframe><p>Under the data method you can see that I renamed the opponent property to <em>otherPokemon</em>, I did this because I’m using state mapping to retrieve the opponent data from the global state under the computed properties.</p><p>You can see we map 2 properties from the global state under computed properties:</p><ol><li><em>local</em> maps to the pokemon that’s assigned to this component.</li><li><em>opponent</em> maps to the pokemon it’s fighting.</li></ol><p>Don’t forget that we defined both these properties in our store to be an object that carries an <em>hp</em> property (the hp that we reduce with attacks) and a <em>pokemon</em> property that stores the pokemon definition.</p><p>The image property has also been added to decide on which image to use (an opponent would need the image that shows the pokemon from the front, while the player’s pokemon needs to be shown from the back).</p><p>Under methods we map the <em>setHP</em> mutator for easy access and implemented it in the attack method, where we used to directly change the opponent’s HP.</p><p>For preparation for the next article I also created a <em>calculateDamage</em> method, currently it just returns the attack’s power, unchanged. But we’ll want to add some calculations later based on stats.</p><p>Remember the getter’s we defined in our global store? <em>opponentAttacks</em>, <em>playerAttacks</em>.</p><p>In pickRandomAttack we’re using the getter we need to retrieve a list of attack names from the local pokemon.</p><p>That’s it, we’ve successfully yanked out most of our state and stored it globally.</p><p>As always you can find the code on github:</p><p><a href="https://github.com/happyDemon/learning-vue-through-pokemon/tree/chapter-3">GitHub - happyDemon/learning-vue-through-pokemon at chapter-3</a></p><p>In the next article we’ll focus on how the traditional pokemon game calculates damage based on the pokemon’s stats &amp; type.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4779c83b245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js explained through Pokemon]]></title>
            <link>https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-2-refs-promises-event-bus-79b705498f0?source=rss-6569fbb4dc8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/79b705498f0</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Maxim Kerstens]]></dc:creator>
            <pubDate>Sun, 26 Feb 2017 15:28:09 GMT</pubDate>
            <atom:updated>2017-03-05T08:50:36.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vue.js explained through Pokemon #2 $refs, Promises &amp; event bus</h3><p>This is the second article in my tutorial series that tries to explain Vue.js concepts by recreating the battle scene from Pokemon.</p><p><a href="https://medium.com/coding-artist/vue-js-pokemon-battle-tutorial-380cd72eb681#.uxu24s175">Original tutorial</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-ac49516ba5d3#.tsdw87je2">#1 Single file components</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-2-refs-promises-event-bus-79b705498f0#.b469349ut">#2 Attacks: $refs, Promises &amp; event bus</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-b4779c83b245">#3 Vuex: state management<br></a><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-4-damage-calculations-a3065f0b1761#.66tlul63e">#4 Damage calculations</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-5-transitions-animation-7bfc70e01d3d#.x63vnlh2c">#5 Transitions &amp; animation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Za34zL74j-bgyXNwf1rFYw.png" /></figure><p>In this second installment we’ll be bringing back the attack functionality.</p><p>There are several ways we can do this.</p><ol><li>Hack it together with $refs and Promises</li><li>Use an event bus that does the heavy lifting</li><li>Separate the logic/data further with Vuex, a state management library.</li></ol><p>We’ll be looking at the first 2 options in this article since they’re not too hard to explain and implement.</p><p>Let’s dive right in.</p><h3>Attack functions</h3><p>First thing’s first, let’s define our attack functions.</p><p>Open up Pokemon.vue, we’re going to be adding an <em>attack()</em> and a <em>pickRandomAttack()</em> method.</p><p>Let’s define them under a newly created methods property:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c468fd839eb5b26992b4c01ae0c5116/href">https://medium.com/media/4c468fd839eb5b26992b4c01ae0c5116/href</a></iframe><p>As you can see at this time the attack function doesn’t really offer a way to notify its caller of a faint or when to continue to the next action. We’ll tackle this next.</p><p><strong>A small note </strong>We’re accessing the pokemon component’s parent state through <em>this.$parent</em>. As you can guess it returns the Vue Instance of the component that the pokemon component is referenced in. In our scenario we’re sure that <em>App.vue</em> will always be the parent, so it’s possible to use it. In other scenario’s where you’re not sure you’ll have to find a way around this (through events or a state manager).</p><h3>Promise-based approach</h3><p>If you don’t know about promises you can quickly read up on the use case and API <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise">here</a>.</p><p>Basically promises allow us to cleanly define a chain of command.<br>It starts by defining a function that can either pass or fail, with <em>then() </em>we can define what happens when it gets resolved successfully. With <em>catch()</em> you can define what should happen when it fails.</p><p>Let’s describe our chain of command.</p><p>When a user selects an attack:</p><ol><li>We reduce the opponent’s HP</li><li>Wait a second for the HP bar to drop</li><li>If the opponent is alive, select a random attack and reduce the player’s HP</li><li>wait a second for the HP bar to drop</li></ol><p>After step 1 &amp; 3 we’ll also update the battle text with something like ‘{<em>pokemon}</em> used {<em>attack}</em>‘.</p><p>At the beginning of step 3 and at the end of step 4 we’ll check if there’s enough HP left, if not We’ll fail the promise and show that the pokemon has fainted.</p><p>After a success we’ll have to reset the battle text to ‘What will {<em>pokemon.player.name}</em> do?’.</p><p>Let’s translate this process into a promise resolution:</p><ul><li>Promise: attack opponent pokemon</li><li>Fails on (<em>reject</em>): opponent’s HP drop to 0</li><li>Succeeds on (<em>resolve</em>): opponent has HP left</li><li>On success (<em>then</em>): return a new promise that selects a random attack from the opponent and use it on the player.</li><li>Fails on (<em>reject</em>): player HP drop to 0</li><li>Succeeds on (<em>resolve</em>): player has HP left</li><li>On success (<em>then</em>): reset the battle text</li><li>on fail (<em>catch</em>): change the battle text and show <em>endOptions</em> menu</li></ul><p>Let’s pour that into code, open up <em>App.vue</em> and add this code under the <em>resetBattle</em> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff9984334db7df643a92e863805c9826/href">https://medium.com/media/ff9984334db7df643a92e863805c9826/href</a></iframe><h4>Constructor</h4><p>As you can see, you create a promise by assigning a function in its constructor. This function get 2 parameters assigned: a resolve callback and a reject callback. As you guessed correctly, you should call these one success/failure.</p><p>Do you remember from last tutorial that we added a <em>ref</em> attribute to the pokemon components?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab5f6722096881ae2225aa9c755b9f8c/href">https://medium.com/media/ab5f6722096881ae2225aa9c755b9f8c/href</a></iframe><p>Because of that we can access its state and methods through <em>this.$refs</em> with the assigned name.</p><p>We’ll have to adjust the attack function so it also takes the <em>resolve</em> and <em>reject</em> callbacks as parameters.</p><h4>then</h4><p>The first then will be called if the opponent still has HP left.<br>In which case a random attack is selected and performed on the player’s pokemon.</p><p>We do this by returning another promise (since the previous promise has already succeeded).</p><h4>then</h4><p>The second then is called if the player’s pokemon still has HP left.</p><p>This time we’ll just want to reset the battle text so the player can keep on playing.</p><h4>catch</h4><p>Catch will be called when a pokemon faints. This could be either the opponent or the player’s pokemon.</p><p>It’s good to know that if the promise is rejected when the player attacks, it won’t reach the opponent’s new promise.</p><p>We’ll have to call the reject callback and assign it the name of the pokemon that has fainted.</p><p>Let’s go back to <em>Pokemon.vue</em> and adding the <em>resolve</em>/<em>reject</em> callbacks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3bce1bef7c7805391a1c6012fb2e996/href">https://medium.com/media/a3bce1bef7c7805391a1c6012fb2e996/href</a></iframe><p>That’s it for promises, the attacks are working.</p><p>You can find a copy of the code right here:</p><p><a href="https://github.com/happyDemon/learning-vue-through-pokemon/tree/chapter-2-promisses">GitHub - happyDemon/learning-vue-through-pokemon at chapter-2-promisses</a></p><h3>Event based approach</h3><p>Taking this approach is a little bit different. It takes a little bit more code, but it’s more verbose.</p><p>The main difference with a promise based approach is that each event has its own name, so the code will be easier to read and understand.</p><p>We’ll be using <a href="https://github.com/gocanto/vuemit">vuemit</a> to do the heavy lifting for us. This package allows us to define events globally, while still allowing us to access the state we want.</p><p>Let’s start off by pulling it in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0be40163566413b99621c42092b07b37/href">https://medium.com/media/0be40163566413b99621c42092b07b37/href</a></iframe><p>Once that’s done we’ll have to add it to our <em>main.js</em>, right after loading <em>Vue.js</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e45a1cf27ae25067831e963a8f5de83/href">https://medium.com/media/7e45a1cf27ae25067831e963a8f5de83/href</a></iframe><h3>Events</h3><p>Let’s take a look at a more traditional Javascript approach.</p><p>We’ll want to make use of 4 events:</p><ul><li><em>player.attack(attackName)</em>: performs the player’s pokemon attack.</li><li><em>opponent.attack()</em>: performs the opponent’s pokemon attack.</li><li><em>attack.completed()</em>: resets the battle text.</li><li><em>fainted(pokemonName)</em>: changes the battle text and show <em>endOptions</em></li></ul><p>Let’s register these once the <em>App.vue</em> has been <a href="https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram">mounted</a>, this means we’ll register the events once the app has been loaded and is ready to use.</p><p>You can define it on the Vue instance definition, I tend to put it right after any data definitions (after the data method &amp; computed property).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32420d18f6e7fd8c8c215084f5087bf3/href">https://medium.com/media/32420d18f6e7fd8c8c215084f5087bf3/href</a></iframe><p>As you can see it’s nearly the same logic we used when defining the promises.</p><p>However it reads more cleanly, it’s been logically named and ordered.</p><h3>Implementation</h3><p>Let’s switch out the promise-based implementation with our event-based implementation by changing the <em>processAttack</em> method to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6db4bd0eae4028af42764ea813cef897/href">https://medium.com/media/6db4bd0eae4028af42764ea813cef897/href</a></iframe><p>It’s as simple as that, we don’t need more than that one line of code, all that’s left to do is rewrite the attack function.</p><p>We’ll just have to replace the places where we used the <em>resolve</em> and <em>reject</em> callbacks previously.</p><p>Let’s open up <em>Pokemon.vue</em> and change the <em>attack</em> method accordingly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1ebf188c72411d06889e551a1fa1876/href">https://medium.com/media/b1ebf188c72411d06889e551a1fa1876/href</a></iframe><p>There we have it, that’s how you would use events instead of promises.</p><p>You can find the code for this approach right here:</p><p><a href="https://github.com/happyDemon/learning-vue-through-pokemon/tree/chapter-2-events">GitHub - happyDemon/learning-vue-through-pokemon at chapter-2-events</a></p><p>Next time we’ll be looking into using <a href="https://github.com/vuejs/vuex">Vuex</a> to make it easier to manage state, so we can start preparing for implementing some more heavier logic that doesn’t really belong inside the components.</p><p>As always you can get the most recent code on github:<br><a href="https://github.com/happyDemon/learning-vue-through-pokemon">https://github.com/happyDemon/learning-vue-through-pokemon</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79b705498f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js explained through pokemon]]></title>
            <link>https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-ac49516ba5d3?source=rss-6569fbb4dc8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac49516ba5d3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Maxim Kerstens]]></dc:creator>
            <pubDate>Fri, 24 Feb 2017 14:42:43 GMT</pubDate>
            <atom:updated>2017-03-05T08:50:22.914Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vue.js explained through pokemon #1 Single file components</h3><p><a href="https://medium.com/coding-artist/vue-js-pokemon-battle-tutorial-380cd72eb681#.uxu24s175">Original tutorial</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-ac49516ba5d3#.tsdw87je2">#1 Single file components</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-2-refs-promises-event-bus-79b705498f0#.b469349ut">#2 Attacks: $refs, Promises &amp; event bus</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-b4779c83b245">#3 Vuex: state management<br></a><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-4-damage-calculations-a3065f0b1761#.66tlul63e">#4 Damage calculations</a><br><a href="https://medium.com/@maximkerstens/vue-js-explained-through-pokemon-5-transitions-animation-7bfc70e01d3d#.x63vnlh2c">#5 Transitions &amp; animation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUXn3MdnINFkEmqe92Nfcw.png" /></figure><p>Recently I came across an article called <a href="https://medium.com/coding-artist/vue-js-pokemon-battle-tutorial-380cd72eb681#.uxu24s175">Vue.js Pokemon Battle Tutorial</a> and felt all kinds of nostalgia.<br>After that I was surprised how fast I read through it and how easy it was to actually rebuild a pokemon battle stage.<br>It got me to a point where I thought to myself, I could build on this tutorial to touch on other facets of Vue.js that were left uncovered.</p><p>This is going to be a multipart series that will range from shifting to a component-based approach to little, more general, tidbits like using animations and promises.</p><p><strong>Note </strong>I will be using short-hand syntax for things as event and property binding. It’s also advised to go through the previous tutorial since it explains the basics.</p><p>This series is meant for people who do have a basic understanding of Vue js.</p><h3>Single file components</h3><p>In this first article I wanted to talk about using single file <a href="https://vuejs.org/v2/guide/components.html">.vue components</a>.</p><p>The attack-feature will be the next article, our main focus here separating style and data.</p><p>In short single file components are .vue files, these normally consist of 3 parts;</p><blockquote>a &lt;template&gt; tag that encapsulates the component’s HTML<br>a &lt;style&gt; tag where you can specify styles that get injected into your page.<br>a &lt;script&gt; tag where you define your component’s logic (local Vue instance).</blockquote><h3>Splitting into components</h3><p>Why would you want to split up your app in components? <br>The short answer is because it allows you to organise your code more clearly. It isolates data (state), html (template) and even styles.</p><p>In the simplest manner we could separate the app into 3 parts, 2 components:<br>1. Battle stage <br>2. Opponent (pokemon)<br>3. Player (pokemon).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzck0WCOLJ6fi6gImwUVTQ.png" /></figure><p><strong>Battle stage<br></strong>The main component will house the main styling, the functionality for the menu, the app’s data and it will act like the glue for its 2 child components (pokemon).</p><p><strong>Pokemon<br></strong>Each pokemon component will house the pokemon’s image, HP bar and attack functionality.</p><h3>Getting started</h3><p>Let’s start by setting up a new project, we’ll be using <a href="https://github.com/vuejs/vue-cli">vue-cli</a> to do the hard work for us.<br>It’s a tool that scaffolds boilerplate code, saving you a lot of time on setup.</p><p>There are a lot of project templates you can choose from (you can check official ones <a href="https://github.com/vuejs-templates">here</a>).</p><p>The one we’ll be using for this project is called <a href="https://github.com/vuejs-templates/webpack-simple">webpack-simple</a>. It sets up the project with webpack, Vue and and vue-loader. That last package is responsible for parsing the .vue files into a useable format.</p><p>Start off by installing vue-cli globally with npm, next create a new project based on the webpack-simple template, lastly <em>cd</em> into the project and install the dependencies.</p><p>Optionally as a last step you can run the compilation and open the project in a browser screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/537c43b87f57027a38529099464bc0e6/href">https://medium.com/media/537c43b87f57027a38529099464bc0e6/href</a></iframe><p>Alright, you’ll notice a few files, what we’re interested in is the <em>src/ </em>folder.<br>This is where all the code will live.</p><p>We won’t have to touch <em>main.js</em> for now, as it stands it’s loading Vue.js and the App.vue component that came with the boiler plate.</p><h3>Defining the battle stage</h3><p>We’ll be using the CSS provided by <a href="https://medium.com/u/39cab1e520f8">Michael Mangialardi</a>’s previous tutorial.</p><p>Let’s open up src/App.vue and replace the style tag with what you can find <a href="https://gist.github.com/happyDemon/9c115972dfb18b41f87ffe1563d5c451">here</a>.</p><p>That’s all for styling, let’s talk data.</p><p>We’ll want to work with a few things:</p><h4>Pokemon</h4><p>This key will contain the 2 pokemon: <em>opponent</em> &amp; <em>player</em>,<br>each pokemon will have a name, image, HP, level and a list of attacks.</p><h4>Action description</h4><p>Just a string that tells the user what’s happening.</p><h4>The main menu options</h4><p>These are the ‘main’ options (fight, pokemon, item bag and run).</p><h4>Which menu is being shown</h4><p>We’ll be making use of 3 actual menu’s, the main (options)menu, the battle option menu that lists the player’s pokemon’s attacks and the end of battle menu, asking if the user wants to give it another go.</p><p>Within the script tag of <em>App.vue</em> We’ll place our data function.</p><p>A small reminder, as opposed to a normal Vue instance definition, we’ll have to return an object from the data function. Normally <em>data </em>is a property within the Vue instance.</p><p>By returning the data object from a function we’re telling Vue that this data is meant for only this instance of this component. If we had multiple instances they’d all share the same data, that wouldn’t be practical and kind of beat the point of having components. Isolated state is what we’re after.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/221f3f446adc41dbb1c74b3246764946/href">https://medium.com/media/221f3f446adc41dbb1c74b3246764946/href</a></iframe><p>Next we’ll start building our stage’s HTML within the template tag of the file. We won’t be showing any Pokemon just yet, we’ll first focus on showing the basic interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dd1b0dea4d9676fd4b5bd80530ee6af/href">https://medium.com/media/7dd1b0dea4d9676fd4b5bd80530ee6af/href</a></iframe><h4>Main options menu</h4><p>As you can see, 4 menu items are defined. We’ll have to define a click event handler to make them work.</p><p>Let’s create our first method, define a methods property right after the data function and add the <em>ProcessOption</em> method to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53efb412fc379d9c3b4be89776c32a94/href">https://medium.com/media/53efb412fc379d9c3b4be89776c32a94/href</a></iframe><h4>Fight option menu</h4><p>This menu will show the player’s pokemon’s attacks. The way they’re currently set up is a little bit different from the original tutorial, we’ll have to retrieve the keys of the player’s pokemon to display them.</p><p>We can do this in 2 ways:</p><ol><li>Once the component’s been mounted we could grab the keys and assign them to a data property.</li><li>We could use a computed property to return the keys (which could come in handy if you decide to build the switch-pokemon feature).</li></ol><p>Let’s do the latter. Computed properties can be accessed in the same way your data properties are accessed. The main difference is that these can not be set manually, they usually depend on one or more data properties that have a need to be transformed (think of filtered lists as an example).</p><p>Let’s add it by defining a <em>computed</em> property between you <em>data</em> function and <em>methods</em> property on the Vue instance. To the <em>computed</em> property we’ll add a method called <em>fightOptions</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc2a4b33e5ad09c89b0a87a7e8e24bce/href">https://medium.com/media/dc2a4b33e5ad09c89b0a87a7e8e24bce/href</a></iframe><p>We’ll still have to define a method <em>processAttack</em>, but we can’t do that just yet. First we’ll need to define our <em>pokemon</em> components. We’ll come back to this in the next article.</p><h4>End options menu</h4><p>Our last menu, this is shown once a pokemon has fainted.<br>If the player wants to have another go we’ll have to reset both pokemon’s HP, reset the battle text and go back to the main menu.</p><p>We’ll have to add a resetBattle method after our <em>processOption</em> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9177ffb68b5311dc6f19e978f8baa267/href">https://medium.com/media/9177ffb68b5311dc6f19e978f8baa267/href</a></iframe><p>That’s it for the stage component for now, it’s time for our next component.</p><h3>Pokemon component</h3><p>This component is where we’ll see the most code-clean up.</p><p>Let’s think about this, the pokemon component should render the pokemon’s-specific UI (meaning the pokemon’s image, name, level and HP bar) as well as handle the pokemon’s attack.</p><p>We’ll have to define a few properties so we can make use of the <em>pokemon</em> data, the <em>position</em> on the screen and which <em>type</em> it is (player or opponent).</p><p>Next to that we’ll need to define some data properties that assign classes to the <em>main box</em>, <em>hp box</em> and <em>hp bar</em>, defines the pokemon’s <em>image element id</em> and we’ll need a property that defines the <em>inverse type</em> (for the player’s pokemon this would be opponent for example).</p><p>We’ll also have to add a few computed properties to get the <em>alive</em> status of the pokemon, as well as one that controls the <em>HP bar style</em> (color and width).</p><h4>Create a new .vue file</h4><p>Let’s start off by creating a new .vue file called <em>Pokemon.vue</em> and define our template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c2ffa794871518550d48f447bf8fc35/href">https://medium.com/media/5c2ffa794871518550d48f447bf8fc35/href</a></iframe><p>In the next few steps we’ll go over all the variables that are being assigned in the template.</p><h4>Data</h4><p>Let’s open a script tag and start our Vue instance definition.</p><p>Within the data function we’ll mostly be returning the ‘style identifiers’, meaning classes and id. Next to that we’ll set the reverse type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4173a5ccf3a6b5d48fada442a59ee21a/href">https://medium.com/media/4173a5ccf3a6b5d48fada442a59ee21a/href</a></iframe><p>Both the this.position and this.type variables are actually props being referenced.</p><h4>Component properties</h4><p>Components can be assigned <a href="https://vuejs.org/v2/guide/components.html#Props">properties</a> (props for short), think of these as state that’s being passed down from a parent. If any changes are made to this data, this component will be get them and can act accordingly. These are accessible in the same way data and computed properties can be called.</p><p>For the pokemon data we’ll want to use a dynamic prop (meaning that it should be passed while prefixed with <em>v-bind:</em> or simply <em>:</em>), the position (top or bottom) and type (player or opponent) prop can just be literal strings since they won’t change.</p><p>This has no effect on how you define them in your component, just something to note when actually referencing the component (we’ll see that later on).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0eea1004faa71b9bbe41943e462c834f/href">https://medium.com/media/0eea1004faa71b9bbe41943e462c834f/href</a></iframe><h4>Computed properties</h4><p>The last part of our data, we’ll want 2 computed properties that change automatically.</p><p>We want to define the HP bar’s style:</p><ul><li>Calculate the HTML element’s width</li><li>Change the background color when HP drops below a certain point.</li></ul><p>We’ll also want an alive property that checks if the pokemon’s HP is above 0.</p><p>Let’s add it after the data method on the Vue instance definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b5230e5b9c376781c95b5c081662699/href">https://medium.com/media/5b5230e5b9c376781c95b5c081662699/href</a></iframe><p>Alright, we’re there, all data and styling has been defined. Let’s add our component to the stage.</p><h3>Back to App.vue</h3><p>Now that our pokemon component is ready to use we’ll have to import it into <em>App.vue</em>, define them in the Vue instance definition and reference it in the template tag.</p><p>Let’s replace <em>export default</em> in the script tag with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0eda39b4360e77415c6304cdee53c292/href">https://medium.com/media/0eda39b4360e77415c6304cdee53c292/href</a></iframe><p>Now we can reference the Pokemon component through a &lt;pokemon&gt; tag in our template.</p><p>Let’s add them for our player and opponent pokemon at the top of the template, right after <em>div.battle-scene</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab5f6722096881ae2225aa9c755b9f8c/href">https://medium.com/media/ab5f6722096881ae2225aa9c755b9f8c/href</a></iframe><p>Remember the props?</p><p>We’re assigning the pokemon data as a dynamic prop, so the component gets updates to that data. Instead of just <em>: </em>you could prefix it with <em>v-bind:</em>.</p><p>The position and type data are meant for styling and context respectively.</p><p>But wait, what’s that <a href="https://vuejs.org/v2/api/#ref">ref</a> attribute doing there?</p><p>I’ve added it in preparation for the next article, by assigning a ref attribute you are essentially naming the child component.</p><p>When you do this you can actually access the component’s Vue instance through <em>this.$refs</em> in <em>App.vue</em>.</p><p>These are non-reactive, however, they are useful for calling any methods on that Vue instance.</p><h4>Building the project</h4><p>All that’s left to do is build the project from the command line.</p><p><strong>npm run dev</strong></p><p>You should have a working copy now.</p><h3>Closing note</h3><p>I hope you’ve learned some new things about single file components.</p><p>In the next article we’ll add the attack functionality back based on Promises and explore a second approach using a simple Event Bus.</p><p>You can always find the latest version of the code on github:</p><p><a href="https://github.com/happyDemon/learning-vue-through-pokemon/tree/master">GitHub - happyDemon/learning-vue-through-pokemon: This repo contains the code for my tutorial series &#39;Learning Vue.js through pokemon&#39;</a></p><p>Or code specific to this article:<br><a href="https://github.com/happyDemon/learning-vue-through-pokemon/tree/chapter-1">https://github.com/happyDemon/learning-vue-through-pokemon/tree/chapter-1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac49516ba5d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>