<?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 Leo Kuo on Medium]]></title>
        <description><![CDATA[Stories by Leo Kuo on Medium]]></description>
        <link>https://medium.com/@leokuo0724?source=rss-aa3fe4872612------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cgfEWdysTwdIBtbv0mSh7g.png</url>
            <title>Stories by Leo Kuo on Medium</title>
            <link>https://medium.com/@leokuo0724?source=rss-aa3fe4872612------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:43:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leokuo0724/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[Templar’s Final Stand — Post-Mortem (JS13k 2024)]]></title>
            <link>https://leokuo0724.medium.com/templars-final-stand-post-mortem-js13k-2024-73c2cc895c67?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/73c2cc895c67</guid>
            <category><![CDATA[js13kgames]]></category>
            <category><![CDATA[js13k]]></category>
            <category><![CDATA[indie-game]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 08:41:00 GMT</pubDate>
            <atom:updated>2024-09-21T08:41:00.634Z</atom:updated>
            <content:encoded><![CDATA[<h3>Templar’s Final Stand — Post-Mortem (JS13k 2024)</h3><h4>The post-mortem of the Templar’s Final Stand, the entry of JS13k 2024 competition.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1xCTSRD4sv5zPj7y9sKgg.png" /></figure><blockquote>Templar’s Final Stand is a strategy game inspired by 2048. The player takes on the role of a Templar Knight, trying to survive longer by fighting off enemies while navigating the grid.</blockquote><p><strong>Play the game and give me feedback here: </strong><a href="https://js13kgames.com/2024/games/templars-final-stand">https://js13kgames.com/2024/games/templars-final-stand</a></p><p><strong>GitHub repo:</strong> <a href="https://github.com/leokuo0724/Templar-s-Final-Stand">https://github.com/leokuo0724/Templar-s-Final-Stand</a></p><h3>About the JS13k</h3><p>The <a href="https://js13kgames.com/">js13k</a> Games competition is a yearly challenge where developers create a game using JavaScript, with a strict limit of 13 kilobytes (After zipped). This tiny size forces participants to think creatively and optimize their code, making every byte count.</p><p>In this post-mortem, I’ll share my experience, the challenges I faced, and the lessons learned from developing for js13k 2024.</p><h3>Ideation</h3><h4>Theme: T<strong>riskaidekaphobia</strong></h4><p>The theme of this year’s competition is <strong>triskaidekaphobia </strong>(the fear of the number 13). To be honest, that was the first time I had heard about the word!</p><p>After researching its meaning and background, I found that the story of the <strong>Knights Templar</strong>, who were arrested on <strong>Friday the 13th</strong>, is often cited as one of the origins of triskaidekaphobia. I thought this historical event would be a good fitting inspiration for my game.</p><h4>Takeaways from Last Year</h4><p>Last year, I built a game — <a href="https://js13kgames.com/2023/games/mongol-march"><strong>Mongol March</strong></a> in JS13k competition. (you can find the postmortem <a href="https://medium.com/@leokuo0724/mongol-march-navigating-the-js13k-challenge-658693d53a44">here</a>) There were two major takeaways:</p><ul><li>The game should be easy to control and intuitive for players to understand how to play.</li><li>Including audio significantly improves the overall experience.</li></ul><p>With these lessons in mind, I’m making them my focus for this year’s entry.</p><h4>Core Game Mechanism</h4><p>At first, I came up with a rough idea: the game would involve combining numbers, with a penalty if the total equals 13. This concept reminded me of the game <strong>2048</strong>,<strong> </strong>which<strong> </strong>was a good starting point since its controls are simple and familiar to many players. Afterward, I tried to merge the story of <strong>Knights Templar</strong> and <strong>2048-like</strong> game mechanics, resulting in the following key components:</p><ul><li><strong>Actions:<br></strong>In the game, players can move up, down, left or right. The controls are simple but every move has consequences. These actions results in attacking enemies, being attacked, equipping items or upgrading items.</li><li><strong>Rewards:</strong><br><strong>- Upgrade items</strong>: Combining identical items upgrades them, making them stronger.<br><strong>- Equip items</strong>: Equipping items grants additional power.</li><li><strong>Punishment:</strong><br>Equipping items increases your power but also adds weight. When the weight reaches 13, every move will cause damage to the player.</li><li><strong>Enemies:</strong><br>After every 13th move (i.e., at 13, 26, 39…), “elite” enemies will spawn. These powerful enemies have special abilities, such as penetrating shields or attacking in a wider range. Players must carefully strategize to overcome these challenges.</li></ul><h3>Basic Project Structure</h3><p>I built this year’s project on the foundation of <a href="https://github.com/leokuo0724/js13kgames-2023">last year’s entry</a>, using <a href="https://straker.github.io/kontra/getting-started"><strong>Kontra.js</strong></a> as the game engine and <strong>Vite</strong> as the bundler. Naturally, I also used <strong>RoadRoller</strong> to compress the JS code. The Vite settings were largely adapted from <strong>roblouie’s </strong><a href="https://github.com/roblouie/js13k-typescript-starter"><strong>js13k-typescript-starter</strong></a> project.</p><p>However, I realized that it’s a mistake that I didn’t use <a href="https://github.com/google/closure-compiler"><strong>Closure Compiler</strong></a> to minified the code last year. I encountered some issues and ended up skipping the minification before using RoadRoller. This time, I used <a href="https://www.npmjs.com/package/terser"><strong>Terser</strong></a> to minified and uglify JS code before running RoadRoller, and the results were impressive: a compression rate of over <strong>17.7% reducing</strong> the size from 13,680 bytes to 11,256 bytes. It gave me more room to add additional game content!</p><h3>Graphics</h3><p>This time, I stuck with vector art design, which is my strength. The difference is that:</p><p><strong>Last year’s approach:</strong> generate SVG image in html -&gt; get the image element and draw via <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage">drawImage</a> function (Kontra implements that in Sprite class)</p><pre>const SVG_DATA = {<br>  shield: &#39;width=&quot;27.6&quot; height=&quot;27.6&quot; viewBox=&quot;0 0 27.6 27.6&quot;&gt;&lt;circle cx=&quot;13.8&quot; cy=&quot;13.8&quot; r=&quot;13.8&quot; fill=&quot;#AE5D40&quot;/&gt;&lt;path fill=&quot;#79444A&quot; d=&quot;M12 10h3v8h-3z&quot;/&gt;&lt;path fill=&quot;#D1B187&quot; d=&quot;M12 12h3v3l-2 1h-3z&quot;/&gt;&lt;/svg&gt;&#39;,<br>  // store all svg data<br>};<br><br>// generate image elements in html<br>const imgContainer = document.getElementById(&quot;imgs&quot;);<br>Object.entries(SVG_DATA).forEach(([id, data]) =&gt; {<br>  const encoded = encodeURIComponent(<br>    `&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; ${data}`<br>  );<br>  imgContainer?.insertAdjacentHTML(<br>    &quot;beforeend&quot;, `&lt;img id=&quot;${id}&quot; src=&quot;data:image/svg+xml;utf8, ${encoded}&quot; /&gt;`<br>  );<br>});</pre><p><strong>This year’s approach: </strong>control canvas context path to render every shapes. For example, there is a SVG shape:</p><pre>&lt;polygon points=&quot;11.54 74 0 73.99 0 77.21 4.16 77.22 4.15 86.83 7.38 86.83 7.38 77.22 11.53 77.22 11.54 74&quot; fill=&quot;#ae5d40&quot;/&gt;</pre><p>The first thing I did was round the numbers to save space. Then, I used <strong>CanvasRenderingContext2D</strong> to draw the shape. Of course, I wrote scripts to handle both of these steps. Here is my <strong>drawPolygon</strong> function:</p><pre>function drawPolygon(<br>  ctx: CanvasRenderingContext2D,<br>  points: string,<br>  fill: string,<br>  offsetX?: number,<br>  offsetY?: number<br>) {<br>  const pointArray = points.split(&quot; &quot;).reduce((acc, cur, i, arr) =&gt; {<br>    if (i % 2 === 0) {<br>      acc.push({<br>        x: parseFloat(cur),<br>        y: parseFloat(arr[i + 1]),<br>      });<br>    }<br>    return acc;<br>  }, [] as { x: number; y: number }[]);<br><br>  ctx.beginPath();<br><br>  ctx.moveTo(<br>    pointArray[0].x + (offsetX ?? 0),<br>    pointArray[0].y + (offsetY ?? 0)<br>  );<br>  for (let i = 1; i &lt; pointArray.length; i++) {<br>    ctx.lineTo(<br>      pointArray[i].x + (offsetX ?? 0),<br>      pointArray[i].y + (offsetY ?? 0)<br>    );<br>  }<br>  ctx.closePath();<br><br>  ctx.fillStyle = fill;<br>  ctx.fill();<br>  ctx.closePath();<br>}</pre><h4>Results</h4><p>Using context 2D to directly draw shapes allows for convenient control over each individual shape. Additionally, this method is more suitable for drawing vector shapes, as it maintains quality without distortion when scaling. Moreover, by avoiding the use of drawImage, you can leverage Kontra’s tree shaking mechanism to remove unnecessary code, further reducing the overall size!</p><h3>Audio</h3><p>Last year, I didn’t include any audio in my game because it’s not my strong suit. However, based on feedback, I realized that adding audio is essential for enhancing the overall game experience!</p><p>Therefore, I incorporated <a href="https://github.com/keithclark/ZzFXM?tab=readme-ov-file"><strong>ZzFXM</strong></a> early in the development process to evaluate the file size.For the sound effects, thanks to the <a href="https://github.com/KilledByAPixel/ZzFX"><strong>ZzFX generator</strong></a>, I experimented with a few randomly generated sounds and found them suitable for the game. The results were quite good and indeed enhanced the overall game experience.</p><p>Next came the part I’m least familiar with: composing the main theme music. For this, I initially leveraged AI by generating some music for inspiration using keywords in <a href="https://suno.com/"><strong>Suno</strong></a>. Then, I tried creating the music in the <a href="https://keithclark.github.io/ZzFXM/tracker/"><strong>ZzFXM tracker</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhJUfHEYxew4vBSaKULG7Q.png" /><figcaption>ZzFXM tracker</figcaption></figure><h3>Polish time!</h3><p>After finishing the core gameplay and essential elements of the game. It was time to polish.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/leokuo0724/status/1828240937992233219&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/03ec96b501a7874fd81ffdc628db3d68/href">https://medium.com/media/03ec96b501a7874fd81ffdc628db3d68/href</a></iframe><h4>Gameplay — classes</h4><p>The first thing I want to improve is gameplay. In the initial version of the game, the strategy seemed rather static, mainly revolving around collecting weapons, equipment , and potions, and attacking enemies at the right moment.</p><p>However, I wanted to provide players with a different experience, so I ultimately chose to introduce various “classes”, each corresponding to a different strategy, allowing players to enjoy diverse gameplay.</p><ul><li><strong>Knight:</strong> The most basic version, focusing on weapon synthesis to boost attack power.</li><li><strong>Wizard:</strong> Emphasizes avoiding enemies and collecting or synthesizing potions to attack enemies.</li><li><strong>Defender:</strong> Focuses on counterattacks, aiming to collect as many shields as possible and encouraging being attack by enemies.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pjc0OeZky2q7nnoDAeTiMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5MiIiLQ0YlLhT7ntuGQ0jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMiZtJ4_xQY9dLgK18IBdg.png" /><figcaption>Three different classes offer distinct gameplay strategies</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*3S9JQWKYh3e-i9VKA8UlnQ.gif" /><figcaption>The Wizard can attack all enemies with potions but is physically fragile</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*eK9AflAtrL0HR48ozuwwGQ.gif" /><figcaption>The Defender should relay on counterattacks</figcaption></figure><h4>Game Balance</h4><p>After adding more classes, game balance became crucial. The goal is to ensure that the difficulty of all three classes is consistent. This involved extensive playtesting and adjustments based on feedback from my friends.</p><p>In addition to the different initial stats for each class, the appearance rates of items and the values of synthesized items also very depending on the class.</p><h4>Story &amp; prologue</h4><p>To enhance immersion in the game, I added an introductory background stroy at the beginning, allowing players to understand that they are playing as a member of the Knights Templar, needing to evade the soldiers pursuing them under King Philip IV.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/leokuo0724/status/1833312488231997465&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fe37717e7aa97c161146bfda367ffd2/href">https://medium.com/media/7fe37717e7aa97c161146bfda367ffd2/href</a></iframe><h4>Enemy characters</h4><p>During the playtesting process, I received feedback that it was sometimes difficult to distinguish between elite enemies and regular ones at a glance (despite textual descriptions), which led to incorrect movements.</p><p>To address this, I used different weapons to differentiate enemies. For example, an axe represents area attacks, while a spear represents penetrating attacks. This makes the distinctions much clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TqH_6DBbTnE6s0kzsjeVw.png" /><figcaption>Normal enemy and different elite enemies</figcaption></figure><h4>Controls</h4><p>The final aspect of polishing was the controls. I implemented audio mute/unmute functionality and speed control. The speed control allows for adjustments to the animation timing. Since my animations are all created using a custom tween function, it’s easy to control the speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*fXZtrzQgK-LQuOHXTUAWQg.gif" /><figcaption>Speed control on the top left corner</figcaption></figure><h3>Compression</h3><p>The final hurdle before uploading was compression. After all the polishing and improvements, I excitedly checked the file size — only to find that my entry had exceeded the 13KB limit. It wasn’t by much, but it had grown to around 13,600 bytes.</p><p>So, I examined the JavaScript files before compression with RoadRoller to see where further reductions could be made. Ultimately, I discovered two ares where the strings were not being uglified:</p><ol><li>Property names in classes(objects)</li><li>Keys of enums</li></ol><p>By shortening the names in these two parts of the code, I successfully kept the file size under 13KB! While this came at the cost of readability, it proved to be an effective compression strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftjLJDJafvN8PpoB8JrwEQ.png" /><figcaption>For example, there is a “main” prop defined in the class, it won’t be uglified by Terser.</figcaption></figure><p>As for whether Terser provides a configuration option to compress properties within objects, that’s something I’ll need to research further.</p><h3>Summary</h3><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/js13kGames/status/1833973763043471724&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9daddbc16644d57677dbf24ad6674b9/href">https://medium.com/media/f9daddbc16644d57677dbf24ad6674b9/href</a></iframe><p>It’s worth celebrating that I’ve completed my second challenge of creating a game for js13k! I believe the most interesting part of the competition is resource management. The 13KB limit forces us to prioritize our ideas, encouraging creativity and innovation within constraints.</p><p>Each decision — from graphics to audio — requires careful consideration, making the final product not just a game, but a testament to efficient design and strategic thinking. This time, I’m particularly satisfied with completing the audio. However, I believe there’s still room for improvement in the game’s intuitiveness. I will take this as my challenge for next year.</p><p>Finally, I’d like to thank <a href="https://medium.com/u/b916f71e6f5d">Andrzej Mazur</a> once again for organizing this event!</p><p><strong>Play the game and give me feedback here: </strong><a href="https://js13kgames.com/2024/games/templars-final-stand">https://js13kgames.com/2024/games/templars-final-stand</a></p><p><strong>GitHub repo:</strong> <a href="https://github.com/leokuo0724/Templar-s-Final-Stand">https://github.com/leokuo0724/Templar-s-Final-Stand</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73c2cc895c67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mongol March: Navigating the JS13k Challenge]]></title>
            <link>https://leokuo0724.medium.com/mongol-march-navigating-the-js13k-challenge-658693d53a44?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/658693d53a44</guid>
            <category><![CDATA[js13kgames]]></category>
            <category><![CDATA[html5-games]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[js13k]]></category>
            <category><![CDATA[game-design]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Sat, 23 Sep 2023 15:29:53 GMT</pubDate>
            <atom:updated>2023-09-23T15:30:47.801Z</atom:updated>
            <content:encoded><![CDATA[<h4>The post-mortem of the Mongol March, the entry of JS13k 2023 competition.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SutoZFev2JjIY4tx9m_Vrw.png" /></figure><blockquote>Mongol March is a tower attack game based on Tetris-like blocks. As a 13th Mongol Empire’s commander, your duty is strategically arrange the blocks to summon Mongol soldiers and lead them to victory.</blockquote><p><strong>Play game here:</strong> <a href="https://js13kgames.com/entries/mongol-march">https://js13kgames.com/entries/mongol-march</a><br><strong>Give me some feedbacks here:</strong> <a href="https://dev.js13kgames.com/2023/games/mongol-march">https://dev.js13kgames.com/2023/games/mongol-march</a></p><h3>Before JS13k 2023 began</h3><p>Two months ago, I knew nothing about JS13k games. It was because a colleague noticed that I was developing games (<a href="https://leokuo0724.itch.io/love-lights">puzzle game</a>, <a href="https://baseball-against-the-wind.com/">baseball game</a>) and informed me about this interesting competition. JS13k is a competition that imposes a constraint where every entry must be under 13kb after compression. Participants are not allowed to use external libraries or services.</p><p>At first, hearing about this restriction seemed incredible to me because based on my past experience in game development, a single sprite image could easily exceed 13kb. After looking at <a href="https://js13kgames.com/entries">the entries from the past few years of JS13k</a>, I found it even more unbelievable. It’s hard to imagine how these games are compressed to fit within 13kb. This sparked my curiosity, and I wanted to give it a try to see what the experience of creating a 13kb game would be like.</p><h3>Ideation</h3><h4>Theme: 13th century</h4><p>It’s actually quite a challenging theme because it requires a moderate connection to history. I tried to find some information about the 13th century history and discovered that the rise of the Mongol Empire was a significant event during that time. When you talk about the 13th century, you almost always mention the Mongols, so I started brainstorming with the Mongol Empire as the central theme.</p><h4>Using past entries as benchmarks</h4><p>As a first-time participant in JS13k, I want to be mindful of my capabilities while brainstorming. This is to prevent the scope of my idea from becoming too unrealistic, leading to the risk of not being able to complete it or exceeding the size limit. So I used past JS13k entries as benchmarks for determining the scope of my project.</p><p>In the end, I chose <a href="https://github.com/danprince/norman-the-necromancer">Dan Price’s work</a> from last year, <a href="https://js13kgames.com/entries/norman-the-necromancer">“Norman the Necromancer”</a>, as a reference. This game features fantastic visuals, uses simple mechanics but very addictive, and provides a great gaming experience that immerses players into the flow state. It’s exactly what I want in my game!</p><h4>Brainstorming gameplay ideas</h4><p>Due to the theme being focused on the Mongol Empire, I initially thought about a war-themed game. My preliminary concept is similar to a traditional Chinese chess-like board game. Players would summon and place soldiers on the board to engage in battles with the opponent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQV3CeGDIQtVpLX-L1x5Lg.jpeg" /><figcaption>The cards below are soliders, defined the speed, occupied blocks and movement.</figcaption></figure><p>However, I quickly realized that this idea might not work. My girlfriend and I simulated it using a paper prototype and discovered its limitations. The biggest drawback was that there are already many games of this type, and adding new concepts would likely push it beyond the 13kb limit. So I wanted to expand on this idea with two goals in mind:</p><ul><li>Reduce the scope</li><li>Add innovative elements</li></ul><h4>The final concept</h4><p>During the process of placing soldier chess pieces on the paper prototype, I had the idea that if we allow players to plan their strategies in advance and then simply deal with the war scenes later, the scope and concept would become much simpler.</p><p>Furthermore, the concept of “placement” reminded me of the board game Patchwork. In this board game, players need to strategically place patch pieces onto their grids, and leaving empty spaces results in point deductions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*hbWckVxIauAXWY32eMdcaw.jpeg" /></figure><p>Finally, I came up with an idea of main game loop:</p><ul><li><strong>Place blocks into grid:</strong> <br>There will be an empty strategy board at the beginning. Players should make decisions to how to arrange the soldiers.</li><li><strong>Start summoning soldiers to fight:<br></strong>According to the strategy board, summon soldiers to march, attack enemy soldiers, and siege the castle to achieve victory.</li><li><strong>Rewards and penalties:</strong><br>Upon victory, players can choose to receive a power-up reward. Additionally, any unoccupied grids in the strategy board become locked, serving as a penalty and hindrance to the player.</li></ul><h3>Game engine and tools</h3><p>I used to be accustomed to using <a href="https://phaser.io/phaser3">Phaser 3</a> for HTML5 game development. However, due to the size constraints, I chose <a href="https://straker.github.io/kontra/">Kontra.js</a> because it has extensive documentation, and I believed it would allow me to quickly learn how to use it. Additionally, Kontra supports finer-grained control than tree shaking, allowing you to remove unused parts of classes during bundling. This can be quite helpful for size optimization!</p><p>As for bundle tools, very thanks <a href="https://twitter.com/rob_louie"><strong>rob_louie</strong></a><strong> </strong>for creating <a href="https://github.com/roblouie/js13k-typescript-starter/blob/master/vite.config.ts">js13k-typescript-starter</a>. My vite config was mostly based on Rob’s settings. With these configurations, especially <a href="https://github.com/lifthrasiir/roadroller">RoadRoller</a>, the bundle size was significantly reduced. It’s amazing to have these tools to help, and they are truly a lifesaver!</p><h3>Graphics</h3><p>For me, I’m accustomed to creating some concept art first, as it helps me better envision the final look of the game. I find that this approach greatly assists me in the game development process.</p><p>I initially wanted to try pixel art, so I visited <a href="https://lospec.com/palette-list">Lospec</a> to find color palettes. Although in the end, I opted for the more familiar vector art…</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/leokuo0724/status/1692219457601741078%3Fs%3D20&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fabs.twimg.com%252Ferrors%252Flogo46x38.png%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/37fca5945e3921e11e03e24072d6adb5/href">https://medium.com/media/37fca5945e3921e11e03e24072d6adb5/href</a></iframe><p>In fact, I initially thought I should use pixel art to reduce the size, but since I only know how to create vector art, I had to work with my existing skill set.</p><h4>PNG -&gt; SVG sprite -&gt; SVG</h4><p>When I initially tried placing PNG images into the canvas after creating the character, I quickly realized that the quality was poor, as the edges of the images became pixelated.</p><p>So, I changed my approach and used SVG. I made some adjustments to try to reduce the SVG size further.</p><ul><li>During the drawing process, I minimized the number of anchor points</li><li>Merged blocks of the same color together whenever possible</li><li>Use <a href="https://svgomg.net/">SVGOMG</a> to optimize and minify svg file</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*M025yiNcl0XlW718xw-1EQ.png" /><figcaption>Minified by SVGOMG, chose minimum precision</figcaption></figure><p>It initially looked good, but when I imported it into the canvas, I encountered an issue. When using an SVG sprite, the default image sizes were set to 300x150, which made it very challenging to calculate image scaling and positioning. Additionally, using an SVG sprite resulted in image output, which prevented me from using RoadRoller for compression.</p><p>So in the end, I wrote the SVG paths in the script and generated images through code. This way, the SVG paths were encoded and compressed by RoadRoller.</p><pre>const SVG_DATA = {<br>  icon1: &#39;width=&quot;16&quot; height=&quot;16&quot; viewBox=&quot;0 0 16 16&quot;&gt;&lt;path fill=&quot;#4B726E&quot; d=&quot;M4 2v10l4 3 4-3V2H4zm6 6H6l1-1-2-2h2l1-1 1 1h2L9 7l1 1z&quot;/&gt;&lt;/svg&gt;&#39;,<br>  icon2: &#39;width=&quot;16&quot; height=&quot;16&quot; viewBox=&quot;0 0 16 16&quot;&gt;&lt;path fill=&quot;#4B726E&quot; d=&quot;M10 1v2-2h2v5h-1l1 9H4l1-9H4V1h2v2-2z&quot;/&gt;&lt;/svg&gt;&#39;<br>};<br>const imgContainer = document.getElementById(&quot;imgs&quot;);<br><br>Object.entries(SVG_DATA).forEach(([id, data]) =&gt; {<br>  const encoded = encodeURIComponent(<br>    `&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; ${data}`<br>  );<br>  imgContainer?.insertAdjacentHTML(<br>    &quot;beforeend&quot;,<br>    `<br>    &lt;img id=&quot;${id}&quot; src=&quot;data:image/svg+xml;utf8, ${encoded}&quot; /&gt;<br>  `<br>  );<br>});</pre><p>Next time, I might consider using the canvas context to directly draw shapes. This approach perhaps more space-efficient.</p><h3>Soliders</h3><p>When handling the display of soldiers, the general principle is to reuse assets wherever possible. For example, the bodies of soldiers can be the same for each type of soldier. This approach helps to optimize and reduce the overall size of the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPJnna64yEEopbu326QkyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cu4fGE3Qz8aB7_Hv4lR7IA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_3x5QNRTH9msQH4QD8OYg.png" /></figure><p>I created an abstract class called “BaseAttackUnit” to define some basic methods and properties for combat units. This allows various combat-capable units, such as infantry and castles, to inherit these methods and attributes.</p><p>For animations, I opted for the simplest approach. For example, in the case of walking animations, I used a straightforward hopping motion. This simplicity can be quite effective in reducing file size while still conveying the necessary actions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/leokuo0724/status/1695142959216464014%3Fs%3D20&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fabs.twimg.com%252Ferrors%252Flogo46x38.png%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac40e3725f5daf17d4e678823d143b9d/href">https://medium.com/media/ac40e3725f5daf17d4e678823d143b9d/href</a></iframe><h3>Tetris-like block and boards</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNaZGoPuZC5b84rOk8upIw.png" /></figure><p>There are two types of board in the Mongol March. One board is used for player placement, while the other is dedicated to displaying the game. Both boards are composed of grid units, with each grid having two layers. The lower layer represents the background color, while the upper layer is used to display the color of block.</p><p>When the mouse hovers over a grid on the strategy board, the game calculates, based on the current block’s shape, which grids need to change color, and then performs the rendering accordingly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/leokuo0724/status/1695284371744526628%3Fs%3D20&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fabs.twimg.com%252Ferrors%252Flogo46x38.png%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fc59051c86495e1f84b343759b138ad/href">https://medium.com/media/6fc59051c86495e1f84b343759b138ad/href</a></iframe><h3>Summon soldiers to attack</h3><p>When the player finishes placing the blocks, a timeline will appear on the strategy board, scanning grids from left to right. Depending on the type of block placed, different types of soldiers will be summoned.</p><p>On each grid, there is stored information such as the block’s unique ID, soldier type, and additional details like whether it has been scanned or blocked. Utilizing this information allows for displaying different grid states and emitting events for summoning soldiers based on the stored data.</p><p>Due to concerns about performance, I implemented logic for reusing soldiers. Every time a soldier needs to be summoned, the game checks if there are any “dead” soldiers available and “revives” them to be placed back on the front lines. This approach can help optimize performance by reducing the need to create new soldier instances constantly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/leokuo0724/status/1695455503114252775%3Fs%3D20&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fabs.twimg.com%252Ferrors%252Flogo46x38.png%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5c590f296d1a9a5c8ead429ab1039f5/href">https://medium.com/media/c5c590f296d1a9a5c8ead429ab1039f5/href</a></iframe><h3>Final Steps</h3><p>Once I had implemented all I mentioned above, I realized that the file size had already reached around 13,200 bytes. However, there are still some pending features that I haven’t implemented yet, including:</p><ul><li>Level rewards</li><li>Perfect placement reward</li><li>Score display</li><li>Music and sound effects</li></ul><p>I attempted to use <a href="https://github.com/KilledByAPixel/ZzFX">zzfx</a> but realized it was too late, and adding music and sound effects would require an additional 500 bytes of space! So, in the end, I had to make the painful decision to cut music from the game…</p><h4>Level rewards</h4><p>Level rewards involve a mechanism where, after conquering a castle, players can choose whether to enhance their abilities. However, in exchange, the enemies will also receive a slight boost in strength. This is also the only opportunity for players to potentially unlock locked grids on the strategy board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRdM85otykZHmA_boZJkVw.png" /></figure><h4>Perfect placement reward</h4><p>The game encourages players to optimize the placement of units on the strategy board, which is the core of the gameplay. Players need to think about when to summon which type of unit for maximum effectiveness.</p><p>To reward players for perfect arrangement, when they achieve a flawless setup on the strategy board, a powerful Khan is summoned for battle. This design allows late-game players to have a chance at a comeback victory!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*bEnFsznAGlXC2fjaKPGBRA.png" /><figcaption>Summon Khan! (the large one XD)</figcaption></figure><h4>Score display</h4><p>The scoring is calculated based on “battle units killed per wave” + “remaining battle units per wave.” The abilities of the units are also translated into scores, allowing the rewards for each round to be converted into points. With the improvement of unit abilities, players can earn more points per wave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xPzqaSd3JTuJ5XfOZ7Fog.png" /></figure><h3>Finally, I finished!</h3><p>In the end, I found that the file size was still larger than 13,312 bytes even after compression. So, I made adjustments to remove unnecessary text and increased the compression level with RollRoader. Finally, I submitted my first JS13k entry!</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/leokuo0724/status/1700920202786136547%3Fs%3D20&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fabs.twimg.com%252Ferrors%252Flogo46x38.png%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/97772bc83c834c2e7ba3f2f3255a5e9b/href">https://medium.com/media/97772bc83c834c2e7ba3f2f3255a5e9b/href</a></iframe><p>However, when I had my colleagues play the submitted game, I found a problem. The game lacked clear instructions and wasn’t very intuitive, which led to my colleagues having to figure out how to play for a while. Since I couldn’t make substantial adjustments to the game at that point, I decided to write a clearer game introduction and also created an instructional video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIm5lySN3Q4E%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIm5lySN3Q4E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIm5lySN3Q4E%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/af2b065270728a49072665cf07209c5d/href">https://medium.com/media/af2b065270728a49072665cf07209c5d/href</a></iframe><h3>Afterword</h3><p>I found the process of participating in JS13k to be incredibly enjoyable. Not only I learned a lot from game development. What’s most valuable is that fellow developers in the competition are always willing to offer advices, and the organizers are actively involved in fostering the community.</p><p>When I saw the positive reviews from everyone on the voting website, it was incredibly fulfilling. Additionally, everyone provided insightful feedback, which was very rewarding for me! The next step for me is to port the game to mobile platforms and develop it further to create a fully polished product for publication.</p><p>If I participate next year, I will likely try the following:</p><ul><li>Directly use the canvas context for drawing graphics.</li><li>Consider music and sound effects as essential parts of the game experience.</li><li>Design a well-crafted in-game tutorial, as it significantly affects the game’s overall experience.</li><li>Allocate time for play testing and gather player feedback to improve the game before submission.</li></ul><blockquote>Thank you for watching! Here’s the <a href="https://github.com/leokuo0724/js13kgames-2023">GitHub repository</a> for my game. Remember to <a href="https://js13kgames.com/entries/mongol-march">give it a try</a>, watch the <a href="https://youtu.be/Im5lySN3Q4E?si=YxUEsrXQf7AQtf-m">introduction video</a> I’ve created, and if you could <a href="https://dev.js13kgames.com/2023/games/mongol-march">provide feedback</a>, I would greatly appreciate it.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=658693d53a44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to integrate Phaser into React]]></title>
            <link>https://leokuo0724.medium.com/how-to-integrate-phaser-into-react-a7119e428228?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7119e428228</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[phaser]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 07:26:59 GMT</pubDate>
            <atom:updated>2023-07-02T07:27:37.410Z</atom:updated>
            <content:encoded><![CDATA[<h4>The benefits and how to communicate between Phaser and React/Redux</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IG2KH3r5Tc7sdOfC3m-BOA.png" /></figure><p>When I was trying to create an HTML5 game, I encountered some challenges regarding whether to use React and how to integrate a game engine. Eventually, I decided to integrate the Phaser game engine into React, and the outcome was quite satisfactory. In this article, I will explain why I chose to integrate Phaser into React and provide a step-by-step implementation guide from my perspective.</p><h3>The disadvantages of using React and Phaser for game development</h3><p>When it comes to creating an HTML5 game, it is not recommended to use React directly for game development. React was not specifically designed for game development, and it has certain limitations in this context. One of the advantages of React is its responsiveness, but its design logic based on functional programming can make it challenging to implement certain game scenarios.</p><p>For example, let’s consider the task of moving a game object from one position to another on the screen. In React, we would need to store the state of the object and use a hook to handle the animation and response. However, when scaling this to multiple objects, maintaining the states and code can become increasingly difficult. Managing the states and keeping track of code logic for a large number of objects can quickly become cumbersome.</p><p>In summary, the disadvantages of using React for game development include:</p><ul><li><strong>Functional programming limitations:</strong> React’s design philosophy, which emphasizes functional programming, may not align well with the requirements of game development. Games often involve complex interactions, animations, and real-time updates, which can be more challenging to implement using React’s functional programming approach.</li><li><strong>Lack of game-specific tools:</strong> React does not provide out-of-the-box tools and features specifically tailored for game development. Game development typically requires functionalities like physics engines, sprite management, collision detection, and game loop management, which are not natively available in React.</li><li><strong>Performance concerns:</strong> While React is known for its efficient rendering and virtual DOM updates, game development requires highly optimized performance to deliver smooth gameplay experiences. React’s reconciliation algorithm and virtual DOM may introduce overhead that could impact game performance, especially in scenarios with intensive animations and real-time updates.</li><li><strong>State management complexities:</strong> React provides mechanisms like state and hooks, managing game state across multiple components and handling complex game logic can become more challenging and less intuitive compared to using a dedicated game engine.</li></ul><p>Regarding Phaser, it is indeed a popular 2D game framework for creating HTML5 games. It utilizes both the Canvas and WebGL renderers to render HTML canvas in web browsers. While it is possible to directly use Phaser to develop an HTML5 game, there are some disadvantages to consider:</p><ul><li><strong>Inconvenience in creating game UI:</strong> In Phaser, creating a game UI involves creating individual game objects and specifying their positions. This process can be more cumbersome compared to using UI frameworks specifically designed for building interfaces. Additionally, the fidelity of UI elements in Phaser is limited to pixels rather than vector-based graphics, which can result in lower visual quality.</li><li><strong>Hard to mange high level game states:</strong> For example, if we want to make a baseball game. We properly need to store some data like teams information, players information and even in-game records. It’s hard to manage all data in Phaser.</li></ul><h3>What are the benefits that integrate Phaser into React?</h3><p>Integrating Phaser into React offers several benefits that can help overcome the limitations of both frameworks individually. Here are some advantages of combining Phaser and React:</p><ul><li><strong>Leveraging Phaser’s game engine features:</strong> You can utilize the powerful game development capabilities provided by Phaser. This includes features such as scene management, game object creation, physics engines, input handling, and animation control. Phaser’s well-designed and optimized features can greatly enhance the game development process.</li><li><strong>Utilizing React’s UI rendering capabilities:</strong> By using React for UI components and rendering, you can take advantage of its virtual DOM and component-based architecture. This allows for fast and efficient UI updates.</li><li><strong>Effective data management with React:</strong> You can use React to handle high-level game states, such as player scores, game progress, and in-game variables. React’s data management capabilities ensure that changes in game data are efficiently.</li></ul><h3>How to integrate Phaser into React</h3><p>We need to build a basic React app firstly. In this article, I will skip this part and focusing on how to combine Phaser and React.</p><p>After create a react app, run yarn add phaser to add Phaser package.</p><p>Then, add a div in index.html file. Phaser will render a canvas into the div later.</p><pre>&lt;body&gt;<br>   &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>   &lt;!-- add the following line --&gt;<br>   &lt;div id=&quot;phaser-container&quot;&gt;&lt;/div&gt;<br>&lt;/body&gt;</pre><p>Set Phaser game config.</p><pre>const config: Phaser.Types.Core.GameConfig = {<br>  type: Phaser.AUTO,<br>  parent: &#39;phaser-container&#39;, // exactly equal to the div id in html<br>  scale: {<br>    mode: Phaser.Scale.ScaleModes.RESIZE,<br>    width: window.innerWidth,<br>    height: window.innerHeight,<br>  },<br>  scene: [GameScene], // put scences into the array<br>};</pre><h3>How to communicate between Phaser and React</h3><p>In this part, I used Redux to manage states. Let’s install @reduxjs/toolkit and react-redux packages firstly.</p><p>yarn add @reduxjs/toolkit react-redux</p><p><strong>The core concept of communication between Phaser and React is through the use of a Redux store.</strong> By storing states that need to be accessed and modified by both frameworks in the Redux state, we establish a shared data source.</p><p>On the Phaser side, we can use the dispatch function to mutate the shared states. When there is a need to modify the state from within Phaser, we can dispatch Redux actions, which in turn update the shared state and trigger the necessary updates in the React components.</p><pre>import { createSlice, PayloadAction } from &#39;@reduxjs/toolkit&#39;;<br><br>const gameInfoSlice = createSlice({<br>  name: &#39;gameInfoSlice&#39;,<br>  initialState: {<br>    pitchingInfo: {<br>      isPitching: false, // define if the pitcher is pitching currently<br>      handedness: &#39;R&#39;, // define the handedness of the pitcher<br>    }<br>  },<br>  reducer: {<br>    setIsPitching: (state, action: PayloadAction&lt;{ isPitching: boolean }&gt;) =&gt; {<br>      const { isPitching } = action.payload;<br>      state.pitchingInfo.isPitching = isPitching;<br>    },<br>    setPitchHandedness: (state, action: PayloadAction&lt;{ handedness: &#39;R&#39; | &#39;L&#39; }&gt;) =&gt; {<br>      const { handedness } = action.payload;<br>      state.pitchingInfo.handedness = handedness;<br>    },<br>  }<br>});<br><br>export { setIsPitching, setPitchHandedness } = gameInfoSlice.actions<br>export const gameInfoReducer = gameInfoSlice.reducer;</pre><p>Configure and export store:</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br><br>import { gameInfoReducer } from &#39;./slices/game-info&#39;;<br><br><br>export const store = configureStore({<br>  reducer: {<br>    gameInfo: gameInfoReducer,<br>  },<br>});</pre><h4>Scenario A: Redux state changed -&gt; Phaser need to be responsive</h4><p>For instance, we substitute pitcher from right handedness to left handedness in game UI. Phaser should make pitcher object change from right-handed to left-handed.</p><pre>// Just an example for getting pitcher data by id<br>const currentPitcherData = useMemo(() =&gt; {<br>  if (!currentPitcherId) return undefined;<br>  return getDataById(currentPitcherId);<br>}, [currentPitcherId, getDataById]);<br><br>// Pitcher handedness<br>useEffect(() =&gt; {<br>  if (!currentPitcherData) return;<br>  dispatch(setPitchHandedness({ handedness: currentPitcherData.handedness.pitching })); // &#39;R&#39; | &#39;L&#39;<br>}, [currentPitcherData, dispatch]);</pre><p>From Phaser side, we subscribe state change event in a scene. Therefore, we could know when we need to modify the game object!</p><pre>// GameScene<br>export default class GameScene extends Phaser.Scene {<br>  public pitcher: PitcherSprite; // for example we have a custom pitcher object<br><br>  constructor() {<br>    super(&#39;game&#39;);<br>    this.pitcher = new PitcherSprite();<br>  }<br>  <br>  create() {<br>    // listen for state changes, TODO: it&#39;s better to deal with unsubscribe after shutdown the scene<br>    store.subscribe(this.stateUpdate);<br>  }<br>  <br>  stateUpdate() {<br>    const newState = store.getState();<br>    const pitchHandedness = newState.gameInfo.pitchingInfo.handedness;<br>    this.pitcher.setHandedness(pitchHandedness); // set handedness after state updated<br>  }<br><br>}</pre><h4>Scenario B: Phaser modify a redux state</h4><p>By calling store.dispatch($action) :</p><pre>import { setIsPitching } from &#39;../store/slices/game-info&#39;;<br><br>export class PitcherSprite extends Phaser.GameObjects.Sprite {<br><br>  // just an example<br>  constructor(scene: Phaser.Scene, atlasKey: string) {<br>    super(scene, 0, 0, atlasKey);<br><br>    this.anims.create({<br>      key: &#39;start_pitching&#39;,<br>      frames: this.anims.generateFrameNames(this.texture.key, {<br>        prefix: &#39;pitcher&#39;,<br>        suffix: &#39;.png&#39;,<br>        start: 0,<br>        end: 34,<br>        zeroPad: 5,<br>      }),<br>      repeat: 0,<br>      frameRate: 24,<br>    });<br>  }<br><br>  startPitching() {<br>    this.play(&#39;start_pitching&#39;);<br>    store.dispatch(setIsPitching({ isPitching: true })); // notify React that is pitching now<br>  }<br><br>}</pre><h3>Demo and conclusion</h3><p>By taking advantage of the strengths of both React and Phaser, we can achieve a smoother game development workflow. React handles UI rendering and state management, while Phaser focuses on game mechanics and rendering. This integration allows for efficient collaboration between the two frameworks, resulting in a more streamlined and powerful game development experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0zMDq1hOPXic_FWW2R_FQ.gif" /></figure><h3>Reference:</h3><p><a href="http://orta.io/notes/games/phaser-redux">An architecture for Phaser JS + Redux</a><br><a href="https://redux.js.org/api/store#subscribelistener">Redux Store</a><br><a href="https://redux-toolkit.js.org/introduction/getting-started">Getting Started with Redux Toolkit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7119e428228" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【iOS】#32 管理 Localizable 資料於 Google Sheet]]></title>
            <link>https://leokuo0724.medium.com/ios-32-%E7%AE%A1%E7%90%86-localizable-%E8%B3%87%E6%96%99%E6%96%BC-google-sheet-f4d977c0a4f7?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4d977c0a4f7</guid>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apps-script]]></category>
            <category><![CDATA[localization]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Sun, 05 Sep 2021 09:39:22 GMT</pubDate>
            <atom:updated>2021-09-05T09:39:22.258Z</atom:updated>
            <content:encoded><![CDATA[<h4>在 Google Sheet 上管理 Localizable 資料，輸出對應格式</h4><p>在處理多國語系的時候，會發現當文本變多的時候，很難去管理這些資料。我們需要切換多個 Localizable.string 去變更不一樣的文本。有時還有可能漏改，導致文本沒有對應的值。</p><p>這時我們需要額外的工具來管理這些 Localizable 的資料。</p><p>網路上有些現成工具可以幫助我們管理，例如像 <a href="https://phrase.com/">Phrase</a> ，它可以幫助我們管理不同語言的文本，並且轉換成不同樣的檔案格式。</p><p><a href="https://phrase.com/">Phrase (Frm. Memsource)-the Complete Localization Solution</a></p><p>雖然 Phrase 功能很強大，但是並非免費的管理平台。若我們只是想管理 iOS 開發上會用到的 Localizable.string 格式，其實可以透過 Google Sheet 管理，並撰寫 Apps Script 輸出相對應的格式。</p><h3>新增 Google Sheet 儲存文本</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9W5l_zm6et0yg-oOZKgxbA.png" /></figure><p>先開一個 google sheet，填入 key 以及對應的語言 value。上圖先以英文與繁體中文作為示範，若想要有更多的語言可以再新增多個欄位。</p><h3>進入指令碼編輯器撰寫 Apps Script</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fsbwrz7UgmSxvLNsh0_DOA.png" /></figure><p>點選工具 -&gt; 指令碼編輯器，接著會開啟分頁顯示以下畫面：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uET4yS13FNCciugK2t9Pg.png" /></figure><p>在指令碼編輯器中，可以輸入指令對剛才新增的 Google Sheet 操作。Apps Script 是 based on JavaScript，語法與 JS 一致。</p><p>因為我們想將 Google Sheet 上的資料製作成 GET API，需要使用 doGet 這個 function。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/228d8dbfbb23e51cc9708e08d6e5eb5d/href">https://medium.com/media/228d8dbfbb23e51cc9708e08d6e5eb5d/href</a></iframe><p>首先先拿到對應的工作表：</p><pre>var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(&#39;localizable&#39;) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwucaodPT90BsEagOqc3VQ.png" /><figcaption>工作的名字在紅框處</figcaption></figure><p>getData function 則是取得資料並轉換格式的地方，其中第二個參數是語言版本所在的 index，修改 index 來讀不一樣的語言（以此範例來說，1是英文版、2是中文版）。</p><p>首先，得到想要的資料範圍，getRange 有四個參數，分別是起始的行、欄為以及最終的行、欄位。</p><pre>var rows = <br>sheet.getRange(2, 1, sheet.getLastRow()-1, sheet.getLastColumn()).getValues()</pre><p>rows 會得到一個二維陣列：</p><pre>[<br>  [ &#39;Control_Save&#39;, &#39;Save&#39;, &#39;儲存&#39; ], <br>  [ &#39;Control_Delete&#39;, &#39;Delete&#39;, &#39;刪除&#39; ],<br>  [ &#39;Control_Next&#39;, &#39;Next&#39;, &#39;下一步&#39; ],<br>  [ &#39;Control_Confirm&#39;, &#39;Confirm&#39;, &#39;確認&#39; ]<br>]</pre><p>接著遍歷陣列，輸出 localizable.string 的格式(“key” = “value”;)：</p><pre>for(i=0; i&lt;rows.length; i++) {</pre><pre>  var dataRow = rows[i]</pre><pre>  // 輸出 &quot;key&quot; = &quot;value&quot;; 的格式，並換行 <br>  result += &quot;\&quot;&quot; + dataRow[0] + &quot;\&quot;&quot; + &quot; = &quot; + &quot;\&quot;&quot; + dataRow[version] + &quot;\&quot;;\n\n&quot;</pre><pre>}</pre><p>最後 return 文字型態</p><pre>return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.TEXT)</pre><h3>部署</h3><p>在部署之前可以使用 console.log 做檢查，點選上方的「執行」即可 run 指令碼。第一次執行時會確認是否授權，點選允許即可。</p><p>要部署時，點選頁面右上方藍色按鈕「部署」-&gt; 「新增部署作業」，接著會看到以下視窗：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beKtXYAZjC4w8YyEL0tx4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDR6LJFRyCZUd51AeqPDtQ.png" /></figure><p>點選上方齒輪將網頁應用程式與 API 執行檔打勾。存取設定為所有人，意味著所有人透過這個網址都可以 Get 資料，不需經過身份驗證。</p><p>接著部署後即可拿到網址，輸入網址後即可看到輸出的文字格式，丟到 API 測試的網站中，可以看到有拿到其中的資料：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2niN5cNU8xpPTfLQG6kB_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qs7Ucb-xQt1WrdlFERFo4w.png" /></figure><p>目前已經拿到英文版本的 API url，若要拿到中文本的 localizable.string ，將剛才的 getData 第二個參數改為 2，去索引中文的欄位。然後再進行一次部署，拿到另外一個中文文本的 API url。</p><h3>應用</h3><p>到這邊算是告一個段落，以後更新 Google Sheet，到部署的網址中即可拿到 localizable 的資料。使用 Google Sheet 可以清楚的知道 key 與對應的值，也比較不會漏掉該填的欄位。</p><p>不過目前只能進入網址中全選，然後回到 Xcode 中的 localizable.sting 自行貼上，之後再來寫一篇如何使用 Python 一鍵更新 localizable.string。</p><h3>參考資料</h3><p><a href="https://developers.google.com/apps-script">Apps Script | Google for Developers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4d977c0a4f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【iOS】#31 多語系設定 Localization]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-31-%E5%A4%9A%E8%AA%9E%E7%B3%BB%E8%A8%AD%E5%AE%9A-localization-ffe31a772677?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe31a772677</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[localization]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Sat, 03 Apr 2021 12:57:26 GMT</pubDate>
            <atom:updated>2021-04-03T12:57:26.748Z</atom:updated>
            <content:encoded><![CDATA[<h4>設定多國語系，讓 App 根據不同語言顯示不同文本</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RsihKgNaVxEWIzdm_Ah8zg.png" /></figure><p>為了讓 App 根據使用者手機語言設定，顯示不同樣的文本，我們需要對 iOS App 進行 Localization (本地化)，以下將介紹三個部分的多語系處理：</p><ul><li>Storyboard 中的文本</li><li>程式碼中的文本</li><li>App 顯示名稱</li></ul><h3>新增多國語言設定</h3><p>不管是想要在 Storyboard 或者 Code 中進行多語系設定，都先要在 Info 中設定。在 Project 的 Info 中，可以找到 Localizations 設定。按下 「+」新增其他想要設定的語言</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*0pxm4rQ_p0irP-9NpB3hUg.png" /></figure><p>然後將 storyboard 的部分都打勾</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*_kowd2PHUk7-xZsut7Z8Nw.png" /></figure><h3>Storyboard 中的文本</h3><p>點選 storyboard 檔案後，到右邊欄位的 Localization 將欲設定的語系都打勾</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*JOZn2AiZjIj5vSGiwivxcw.png" /></figure><p>打勾後左手邊的 storyboard 會變成可下拉的選單，其中 .strings 即為文本設定的檔案</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*2MHbYytMKN5R3YIw5X1Oyg.png" /></figure><p>打開後大致上會長成下方這樣。如果不清楚是哪一個元件的話，可以利用它提供的 ObjectID 去找元件</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*hs4jrEXWkBM_2eU2vDhJLQ.png" /></figure><p>Storyboard 元件的 ObjectID 可以點選左邊欄位的第四個 Icon 查看</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*TH77gK7v8rPMNdgj556wtw.png" /></figure><h3>程式碼中的文本</h3><p>Storyboard 適合設定靜態的文本，若是本身就直接用程式碼寫的，或者需要動態修改的文本，勢必需要從程式中設定 Localization</p><p>先新增一個 Strings File，並且<strong>命名為 Localizable</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*3tyvT_a5gQsS3CcgMErHiQ.png" /></figure><p>點選 Localizable.strings 檔案，一樣在右手邊的欄位將 Localization 打開</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*WsimhajHJS21X6TIRfeCVQ.png" /></figure><p>打開後此時 Localizable.strings 一樣會變成可下拉，其中的檔案就是本地化語言的設定檔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*IZApKoZ0utM9XfbmJceDAw.png" /></figure><p>設定的方式如上圖所示，為 Key Value Pair，並且結尾用「;」，要記得不同檔案的 Key 名稱不要打錯。上方 <strong>%d 的部分是要帶入參數顯示</strong>，亦可以使用 %f 來寫是浮點格式</p><pre>let noRecordStr = <strong>NSLocalizedString</strong>(&quot;GameVC.noRecord&quot;, comment: &quot;&quot;)</pre><pre>recordLabel.text = noRecordStr</pre><p>在程式中使用時，利用 NSLocalizedString，第一個參數為 LocalizKey ，第二個參數是用來附註，讓開發人員更好了解這個 Key 代表什麼用途</p><pre>// &quot;GameVC.bestRecord&quot; = &quot;最佳紀錄：%ds&quot;</pre><pre>let bestRecordStr = NSLocalizedString(&quot;GameVC.bestRecord&quot;, comment: &quot;&quot;)<br>let record = 100</pre><pre>recordLabel.text = <strong>String.localizedStringWithFormat(bestRecordStr, record)</strong></pre><p>若要帶入參數，需使用 String.localizedStringWithFormat，第二個參數帶入數值，將會顯示在 %d 的部分，達到動態改變文本的目的</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*63m02OXD1Zk-qz0lsi5MLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*qI-DtXAmaX7EKJ1aDPH3kg.png" /></figure><h3>App 顯示名稱</h3><p>新增命名為 InfoPlist 的 Strings File，並且跟上述步驟相同，打開 Localization 設定</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*1BAShN0MIueNN7KX-vs8Cg.png" /></figure><p>在檔案中輸入以下程式碼，Value 的部分設定成欲顯示的 App 名稱。請記得 Key 一定要是 CFBundleDisplayName 才會設定成功</p><pre>&quot;CFBundleDisplayName&quot; = &quot;App Name&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*A3cmIrPncu-LnRXf5xOpmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*z5XaDz-tEXRzkcnIhCNHiA.png" /></figure><h3>參考資料</h3><ul><li><a href="https://medium.com/@Wei_Wei/%E6%94%AF%E6%8F%B4%E5%A4%9A%E8%AA%9E%E7%B3%BB%E7%9A%84%E6%96%B9%E6%B3%95-a187188ba29e">支援多語系的方法</a></li><li><a href="https://franksios.medium.com/ios-localization-%E6%9C%AC%E5%9C%B0%E5%8C%96-7b16b58bb9df">iOS 關於多國語系的那些事(Localization)</a></li><li><a href="https://medium.com/swlh/app-localization-in-swift-ios-swift-guide-baa2c2e4298e">App Localization in Swift — iOS Swift Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe31a772677" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-31-%E5%A4%9A%E8%AA%9E%E7%B3%BB%E8%A8%AD%E5%AE%9A-localization-ffe31a772677">【iOS】#31 多語系設定 Localization</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【iOS】#30 Dispatch Group 處理多個非同步操作]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-30-dispatch-group-%E8%99%95%E7%90%86%E5%A4%9A%E5%80%8B%E9%9D%9E%E5%90%8C%E6%AD%A5%E6%93%8D%E4%BD%9C-583fe2225a8f?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/583fe2225a8f</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dispatchgroup]]></category>
            <category><![CDATA[gcd]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Thu, 01 Apr 2021 05:35:04 GMT</pubDate>
            <atom:updated>2021-04-01T05:35:04.716Z</atom:updated>
            <content:encoded><![CDATA[<h4>GCD, Dispatch Group</h4><p>前陣子在面試時，遇到一個考題，有關於發 api 然後呈現抓到的圖片在 App 上。不過<strong>每次 api 的 response 只會有一個圖片網址</strong>，目標是按下一個按鈕後，呈現多張圖片在 App 中</p><p>在實作的過程中，就發現一些問題。先解析一下流程：<strong>抓 api -&gt;圖片解析 -&gt; -&gt; 圖片裝入陣列 -&gt; Reload Collection View</strong>。在這個過程中，需要等待前一個步驟有結果後，才能進行下一個動作，否則就沒有資料可以執行</p><p>所以一開始我解決的方式是使用 Closure，等待一個動作結束後執行下一個。然而很快就遇到下一個問題：</p><p>這個 api response 僅有一個圖片網址，我們需要的是多個圖片。如果<strong>按照我原本的做法，就會每抓到一個圖片就 Reload Collection View 一次</strong>，非常沒有效率</p><p>到最後我是多寫一個判斷，去看圖片抓了幾個，再一起 Reload Collection View，但程式碼不太簡潔也不太好讀</p><p>所以主考官給了一個建議，可以使用 Dispatch Group 改寫！</p><h3>Dispatch Group</h3><p>透過 Group 可以將多個 task 整合同步。當多個 task 附加到 Group 上時，可以安排這些 task 在同一個 queue 或者不同 queue 上進行非同步操作。當所有 task 都執行完畢時，Group 可以執行完成的操作</p><p>在 Dispatch Group 中有幾個 Function：</p><ul><li>enter：宣告 task 進入 group</li><li>leave：宣告 task 在 group 已經執行結束</li><li>wait：等待前一個提交的 task 執行完畢</li><li>notify：當 group 中所有 task 皆執行完畢</li></ul><h4>範例</h4><p>先建立<a href="https://dog.ceo/api/breeds/image/random">抓取 Api</a> 的 function 如下：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cdfe3c155b2272fc2bd1029816a86a2/href">https://medium.com/media/4cdfe3c155b2272fc2bd1029816a86a2/href</a></iframe><p>在一般執行的情況下，會像下圖，call function 從上到下，然而因為 fetchApi 需要一段時間運行，所以是先 print 出 executed，最後才是 api 抓到的結果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*HMPbTTfIhBdhgpWTEYj13A.png" /></figure><p>而加上 Dispatch Group 的結果如下，會等待所有 task 結束後，才 print 出 fetch done。在使用 group 時，要記得在 task 結束後使用 leave，否則會讓 group 以為 task 還在執行中</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*vajkD6n3zTzMuweLhw_VuQ.png" /></figure><p>不過上面的方式<strong>不能確保哪個 Api 先被抓到</strong>，因為這是非同步的操作，只能知道最後會通知 group 然後做 completion。假設如果要等待第一個 fetchApi 結束再進行第二個的話，可以使用 wait()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*7HSX3p639tvSKN4bNfH2cw.png" /></figure><p>wait 會讓當前 thread 暫時 block 住不繼續執行，等待目前在 group 中的 task 都執行結束後，再繼續下去。所以上面的程式碼在執行到第一個 fetchApi 時，會先等待他執行完，再執行以下程式碼，最後都執行結束後 notify 再進行 completion handler</p><p>這算是第一次接觸 GCD 的應用，過往只有概念以及使用 DispatchQueue.main.async。若有不清楚的地方還請大家見諒 XD，也歡迎大家提出來討論喔～</p><h3>參考資料</h3><ul><li><a href="https://ali-akhtar.medium.com/concurrency-in-swift-grand-central-dispatch-part-2-1b0b025ee381">Concurrency in Swift (Grand Central Dispatch Part 2)</a></li><li><a href="https://riptutorial.com/ios/example/28278/dispatch-group">iOS - Dispatch Group | ios Tutorial</a></li><li><a href="https://medium.com/@shawnloveapp/dispatchgroup%E6%93%8D%E4%BD%9C-6365cb4f0fdc">DispatchGroup操作</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=583fe2225a8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-30-dispatch-group-%E8%99%95%E7%90%86%E5%A4%9A%E5%80%8B%E9%9D%9E%E5%90%8C%E6%AD%A5%E6%93%8D%E4%BD%9C-583fe2225a8f">【iOS】#30 Dispatch Group 處理多個非同步操作</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【iOS】#29 Game Center 排行榜設定]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-29-game-center-%E6%8E%92%E8%A1%8C%E6%A6%9C%E8%A8%AD%E5%AE%9A-390460eaf8b4?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/390460eaf8b4</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[leaderboard]]></category>
            <category><![CDATA[gamecenter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 10:10:30 GMT</pubDate>
            <atom:updated>2021-03-15T14:37:05.508Z</atom:updated>
            <content:encoded><![CDATA[<h4>使用 GameKit 連接 Game Center</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YO1YGzBdF4MopFui3XKnSw.png" /></figure><p>這次針對上次發布的 <a href="https://apps.apple.com/tw/app/set-%E7%A5%9E%E5%A5%87%E5%BD%A2%E8%89%B2%E7%89%8C/id1557245767#?platform=iphone">Set 神奇形色牌</a> 新增排行榜內容，因為有玩家提到說想要看其他人的成績如何。現階段的 App 只有做到 Local 的排行榜，所以這次利用 Game Center 的功能來實作線上排行榜。</p><p>Game Center 是 apple 提供的線上多人遊戲中心，可以設定排行榜、成就等內容，玩家可以看到其他人的遊戲資料，或者朋友的遊戲資料，增加社交性。</p><blockquote><strong>進入 App 功能 Tab 新增排行榜</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ca2OMaVLqsaY16A5Lq-kmQ.png" /></figure><p>進入 App Store Connect 的後台中，選擇「功能」，可以看到 Game Center 的部分，按下排行榜旁的「+」新增新排行榜</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-X2U07tjcrBJIenk02K2aA.png" /></figure><p>排行榜的類型有兩種，一種是會按照日期刷新，例如一週排行；另一種是永遠不會重置的經典排行榜，依據遊戲設定。這邊我選擇的是「經典排行榜」</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-z58aNptotDAchy8O7Mrg.png" /></figure><p>接著其他資料：</p><ul><li>名稱：內部名稱，顯示在 App Store Connect，方便管理</li><li>ID：這個 ID 是從程式碼存取時，需要使用到的</li><li>格式類型：根據積分格式設定</li><li>提交類型：看要顯示最佳或者是最新的玩家積分</li><li>排序方式：成績要升冪或降冪排列</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHLJq7A83z9gGJ9otSs34A.png" /></figure><p>接著設定本地化語言，顯示的名稱、格式以及是否要增加後綴。例如 Set game 是比秒數，後綴可填上秒，到時候排行榜時就會顯示 XX秒</p><blockquote><strong>Xcode 設定打開 Game Center 功能</strong></blockquote><p>在專案中，enable game center feature。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*q2WjCFxFIe2sYsC-u4AjOQ.png" /></figure><p>按下上圖右下方的 Capability 選擇 Game Center 即可</p><blockquote><strong>認證使用者 Authenticate</strong></blockquote><p>記得先 import GameKit，才能使用相關 SDK</p><pre>import GameKit</pre><p>接著在 view controller 上委派 GKGameCenterControllerDelegate，它協定的內容是當 Game Center 的頁面關閉時要執行什麼行為，以下設定把這個 game center 的 view controller 關閉</p><pre>func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {</pre><pre>    gameCenterViewController.dismiss(animated: true)</pre><pre>}</pre><p>一開始進入遊戲時，使用者必須登入 Game Center 才能取得其資料，所以在 viewDidLoad 中呼叫 authenticatePlayer。在使用者沒登入 Game Center 的情況下，即會顯示登入 Game Center 的頁面；反之則會顯示某某某登入 Game Center 的提示在上方</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92d6fb8bd863394c04fa21e60d4f6763/href">https://medium.com/media/92d6fb8bd863394c04fa21e60d4f6763/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*oXmJLN23zZiMGB8-Knpn_A.gif" /><figcaption>轉圈圈的 Activity Indicator 需額外設定，不包含在上面程式碼中喔～</figcaption></figure><blockquote><strong>提交排行榜資料</strong></blockquote><pre>GKLeaderboard.submitScore(score: 100, context: 0, player:  GKLocalPlayer.local, leaderboardIDs: [&quot;com.leokuo0724.set_game.find_10_leaderboard&quot;], completionHandler: nil)</pre><p>使用 submitScore 即可提交成績。</p><p>其中 score 為要提交的成績、player 是當前玩家、leaderboardIDs 輸入在 App Store Connect 中排行榜設定的 ID</p><blockquote><strong>查看排行榜</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32152c3a65310955b1b93775c8cf84d4/href">https://medium.com/media/32152c3a65310955b1b93775c8cf84d4/href</a></iframe><p>一樣在要顯示排行榜的 view controller 中，設定 GKGameCenterControllerDelegate</p><p>利用 GKGameCenterViewController 函式，可以呼叫出排行榜。其中參數可以設定玩家的 Scope 或者 時間的範圍</p><h3>Demo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*TiN5491RAwI39Vpc3ON-ZQ.gif" /><figcaption>如果想要讓登入提示在別的地方跑出來，可以調整<a href="https://developer.apple.com/documentation/gamekit/adding_an_access_point_to_your_game"> GKAccessPoint</a>，預設是從正上方跳出</figcaption></figure><h3>參考資料</h3><p><a href="https://developer.apple.com/documentation/gamekit">Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=390460eaf8b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-29-game-center-%E6%8E%92%E8%A1%8C%E6%A6%9C%E8%A8%AD%E5%AE%9A-390460eaf8b4">【iOS】#29 Game Center 排行榜設定</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【iOS】#27 Set(神奇形色牌) Part3: 上架流程]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-27-set-%E7%A5%9E%E5%A5%87%E5%BD%A2%E8%89%B2%E7%89%8C-part3-%E4%B8%8A%E6%9E%B6%E6%B5%81%E7%A8%8B-1ce8569ba38b?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ce8569ba38b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-publish]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 15:12:11 GMT</pubDate>
            <atom:updated>2021-03-10T15:12:11.340Z</atom:updated>
            <content:encoded><![CDATA[<h3>【iOS】#28 Set(神奇形色牌) Part3: 上架流程</h3><h4>App Store 上架流程記錄</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MeT80eRytqGQlRA2Uxjng.png" /></figure><p>要上架 App Store 需要經過幾項流程：</p><ol><li>加入 <a href="https://developer.apple.com/programs/enroll/">Apple Developer Program</a>，付款開通成為蘋果開發者。</li><li>在 KeyChain Access 程式中，生成憑證檔</li><li>準備 iOS Distribution Certificate</li><li>建立 APP ID</li><li>建立 Profile</li><li>在 Xcode 設定 Signing</li><li>在 <a href="https://appstoreconnect.apple.com/login">App Store Connect</a> 建立 APP</li><li>打包 APP 上傳</li><li>TestFlight 平台測試 (optional)</li><li>上傳截圖與填寫必要資料</li><li>提交等待審查</li></ol><blockquote><strong>1. 加入 </strong><a href="https://developer.apple.com/programs/enroll/"><strong>Apple Developer Program</strong></a></blockquote><p>開通 Apple 開發者帳號後，才可把 App 上架至 App Store。目前費用是 $3400 NTD / 年。</p><p>選擇利用個人名義申請的話，就可以不用管 D-U-N-S Number，若是企業才需要這個編碼。</p><p>確定刷卡完成後，會等待一段時間開通，Apple 官方是說等 48 小時左右。我的經驗是在週六付款，隔週週一開通成功。成功後會收到 Apple 的來信，就代表可以使用開發者帳號了！</p><blockquote><strong>2. 在 KeyChain Access 程式中，生成憑證檔</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*6Qclff-jlgCLGtXC7jCi_w.png" /></figure><p>在預設的 KeyChain Access 程式中，找到 Request a Certificate From a Certificate Authority</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrqfiKd2k9cMOGKWYRWPdQ.png" /></figure><p>接著選擇存在 disk 中</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*zChtvKL8GUBQUBUYVIZU7A.png" /></figure><blockquote><strong>3. 準備 iOS Distribution Certificate</strong></blockquote><p>至<a href="https://developer.apple.com/account">開發者後台</a>中，選擇 Certificates, Identifiers &amp; Profiles</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBct0AFBuShtPEVCamZoRg.png" /></figure><p>點選 Certificates 旁的「+」後，會進入以下頁面，選擇想要生成的憑證類型。若是要上架 iOS APP 可以選擇 Apple Distribution 或 iOS Distribution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNoq6WsnTpOlI77OrBVSNQ.png" /></figure><p>關於各個憑證的差別，以下這篇有詳細的表格解說～</p><p><a href="https://qiita.com/Arime/items/e9816a4f1fd08b1406c0">Certificates, Identifiers &amp; Profiles - Apple Developer (After the WWDC 2020) - Qiita</a></p><p>接下來把剛才使用 KeyChain Access 生成的 Certificate Upload 上去</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Jszo4B1tbk7W3VtOxlOvA.png" /></figure><p>最後把 .cer 憑證檔案下載下來並打開，即完成安裝</p><blockquote><strong>4. 建立 APP ID</strong></blockquote><p>同樣在後台的 Certificates, Identifiers &amp; Profiles 中，點選左邊欄位的 identifiers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*JxsJwdMb-hP74apTLK_EAQ.png" /></figure><p>按下「＋」-&gt; 「APP ID」-&gt; 「APP」步驟後，會進入以下畫面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsRZiF0Jx0Zr8IZGqxjv3g.png" /></figure><p>Bundle ID 輸入的要跟 Xcode 專案的一樣（在專案的 General Tab 中可以找到 Bundle Identifier），記得 Bundle ID 要是獨一無二的 。</p><p>Capabilities 中可以選擇這個 APP 會用到的功能，例如 Game Center, 推播等等，最後按下「Register」即可成功註冊 APP ID</p><blockquote><strong>5. 建立 Profile</strong></blockquote><p>一樣在後台的 Certificates, Identifiers &amp; Profiles 中，切換到 Profiles 並點選「＋」進行新增</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bDkPc1cl3ykfc3henor_g.png" /></figure><p>選擇 App Store</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phbcYRQuDI4lck-kINWuAQ.png" /></figure><p>在 Generate a Provisioning Profile 中選擇剛建立好的 APP ID</p><p>再來選擇剛建立好的憑證以及 Profile 的名稱，即可完成建立！最後再把 Profile 下載下來。</p><blockquote><strong>6. 在 Xcode 設定 Signing</strong></blockquote><p>在專案的 Signing &amp; Capabilities 中做設定。可以把「Automatic Manage Signing」 打開，或者使用手動的方式。</p><p>自動的話只需要從下拉選單選擇 Team；手動的話需要指定本地的 Profile 上傳</p><blockquote><strong>7. 在 </strong><a href="https://appstoreconnect.apple.com/login"><strong>App Store Connect</strong></a><strong> 建立 APP</strong></blockquote><p>剛剛的後台是開發者的後台，而 App Store Connect 是管理你上架 App 的地方。點選「我的 App」-&gt; 「＋」-&gt;「新的 App」</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_7CbjsVBRn3xREteUDaog.png" /></figure><p>選擇平台、名稱、語言以及剛建立的 Bundle ID，SKU 可以直接輸入 Bundle ID 即可</p><blockquote><strong>8. 打包 APP 上傳</strong></blockquote><p>回到 Xcode 中，在裝置的部分選擇使用 Build Any iOS Device (arm64)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*tsxGtUNT4g_hdtKJRtUMxA.png" /></figure><p>點選「Product」-&gt;「Archive」打包</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*6iX9ZE2GidQGDEKmItlvWg.png" /></figure><p>接著點選 Distribute App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsdfVTDgk-bQoKnfW8l9Mw.png" /></figure><p>然後就按照預設的一路下一步囉！Singing 的部分再選擇要自動管理或手動。如果一切沒問題的話，即可上傳成功！</p><p>過程中如果有遇到 <strong>Provisioning profile “xx_Distribution” doesn’t include signing certificate “iPhone Developer: “</strong> 這個問題，可以參考一下這篇解決方式：</p><p><a href="https://blog.csdn.net/quantum7/article/details/80641630">iOS配置证书：Provisioning profile &quot;xx_Distribution&quot; doesn&#39;t include signing certificate &quot;iPhone Developer_柳鲲鹏-CSDN博客</a></p><blockquote><strong>9. TestFlight 平台測試 (optional)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-kIH-Ed4gpmruitcSrsBg.png" /></figure><p>一般來說 App 上架前會先經過 alpha test, beta test，確認沒問題後才會進行上架。TestFlight 即為進行測試的平台。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GcmEpThv8UxCH3qworedQw.png" /></figure><p>一開始上傳的版本會呈現「缺少出口合規資訊」，填完必要的資訊後過不久，就會更改為「正在測試」。</p><p>內部群組中的測試帳號，test app 不需通過 Apple 審核即可進行測試。</p><p>外部群組可以通過邀請網址或者手動輸入增加測試的人數，app 需經過 Apple 的審核才可進行測試。不過這邊的審核不是正式上架的 Apple 審核，正式的還需要上傳截圖、填寫一些資料，並且完整通過 <a href="https://developer.apple.com/app-store/review/guidelines/">App Store Review Guidelines</a> 才可發布。</p><p>測試的帳號會接收到電子郵件，在裝置下載 TestFlight 後，即可在裡面看到 App ，可下載下來做實機測試。</p><blockquote><strong>10. 上傳截圖與填寫必要資料</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlQXfltXuggpajvT24lcQw.png" /></figure><p>在 App Store Tab 中，有需多資料需要進行填寫與上傳，基本上沒有太多困難的地方，按下提交後若有缺少的部分，它也會告訴你</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQDJi_oJrz6WwkHkLYTp9Q.png" /></figure><p>其中 Apple 有規定要「隱私權政策 URL」，可以參考一下這篇提供的網址，方便生成隱私權政策 URL</p><p><a href="https://blog.niclin.tw/2019/01/05/%E5%A5%BD%E7%94%A8%E7%9A%84%E9%9A%B1%E7%A7%81%E6%AC%8A%E6%94%BF%E7%AD%96-url-%E8%87%AA%E5%8B%95%E7%94%9F%E6%88%90/">好用的隱私權政策 URL 自動生成</a></p><blockquote><strong>11. 提交等待審查</strong></blockquote><p>按下提交之後，就等待 Apple 官方的審查吧！根據經驗通常在晚上睡覺的時間 Apple 就會審查結束了～</p><p>如果出問題再看官方的描述去修正囉！</p><h3>Apple Store</h3><p>最後如果大家想玩的話，可以下載來玩喔！剛開始玩可能會有點難度 XD，打算之後改版來個簡單或者輔助的模式～</p><p><a href="https://apps.apple.com/us/app/set-%E7%A5%9E%E5%A5%87%E5%BD%A2%E8%89%B2%E7%89%8C/id1557245767">‎Set 神奇形色牌</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ce8569ba38b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-27-set-%E7%A5%9E%E5%A5%87%E5%BD%A2%E8%89%B2%E7%89%8C-part3-%E4%B8%8A%E6%9E%B6%E6%B5%81%E7%A8%8B-1ce8569ba38b">【iOS】#27 Set(神奇形色牌) Part3: 上架流程</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【iOS】#27 Set(神奇形色牌) Part2: 儲存排行榜]]></title>
            <link>https://leokuo0724.medium.com/ios-27-set-%E7%A5%9E%E5%A5%87%E5%BD%A2%E8%89%B2%E7%89%8C-part2-%E5%84%B2%E5%AD%98%E6%8E%92%E8%A1%8C%E6%A6%9C-36fb2485a527?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/36fb2485a527</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Sat, 06 Mar 2021 11:11:35 GMT</pubDate>
            <atom:updated>2021-03-06T11:11:35.061Z</atom:updated>
            <content:encoded><![CDATA[<h4>使用 UserDefaults 儲存名次資料</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElElqFnwqGMV7ByDc7FKuQ.png" /></figure><blockquote><strong>前篇連結</strong></blockquote><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/ios-26-set-%E7%A5%9E%E5%A5%87%E5%BD%A2%E8%89%B2%E7%89%8C-part1-%E9%81%8A%E6%88%B2%E8%A6%8F%E5%89%87%E8%A8%AD%E5%AE%9A-svg-%E6%8E%A7%E5%88%B6-69e341240beb">【iOS】#26 Set(神奇形色牌) Part1: 遊戲規則設定、svg 控制</a></p><p>我設定的 Set 遊戲模式目前只有一種：從牌面上找到 10 組 Set。排行榜的部分則是記錄玩家所花費的時間，花越少時間者排名越高。</p><blockquote><strong>使用 UserDefaults 儲存資料</strong></blockquote><p>UserDefaults 可以用來存少量的資料，會一直存在本地直到刪除 App。</p><p>UserDefaults 可以存的資料有 String, Number, Date, Data, Dictionary, URL，也可以存成 Array 的格式，不過型別也要是上述幾種。若想要存自定義型別，需先經過 JSONEncode 成 Data 的型別。</p><p>不過目前遊戲需要的排行榜資料很單純，沒有使用者名稱，僅存秒數成績。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92e4d1b189899dd8db634b3287b50681/href">https://medium.com/media/92e4d1b189899dd8db634b3287b50681/href</a></iframe><pre>let userDefaults = UserDefaults.standard</pre><pre>var records: [Int] = userDefaults.object(forKey: &quot;findTenRecords&quot;) as? [Int] ?? []</pre><p>UserDefaults 是利用 Key-Value 儲存資料。上述程式碼先從 UserDefaults 中取得 findTenRecords 的資料</p><pre>// 加入後，sort 由小到大<br>records.append(result)<br>records.sort { $0 &lt; $1 }<br>if records.count &gt; 10 {<br>    records = records.dropLast()<br>}</pre><p>把新的秒數 append 到陣列中，並且由秒數小排到大。由於預計只存1~10 名的資料，所以陣列若超過十個元素則拿掉最後一個</p><pre>userDefaults.set(records, forKey: &quot;findTenRecords&quot;)</pre><p>最後再寫入 UserDefaults 的 findTenRecords key 中，即可記錄之</p><h3>Demo</h3><p>其實找十組 Set 應該要花蠻久的，為了 Demo 需求，我先改成找到一組就成功～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*TiN5491RAwI39Vpc3ON-ZQ.gif" /></figure><h3>參考資料</h3><p><a href="https://cocoacasts.com/ud-3-how-to-store-an-array-in-user-defaults-in-swift">How to Store an Array in User Defaults in Swift</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36fb2485a527" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【iOS】#26 Set(神奇形色牌) Part1: 遊戲規則設定、svg 控制]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/ios-26-set-%E7%A5%9E%E5%A5%87%E5%BD%A2%E8%89%B2%E7%89%8C-part1-%E9%81%8A%E6%88%B2%E8%A6%8F%E5%89%87%E8%A8%AD%E5%AE%9A-svg-%E6%8E%A7%E5%88%B6-69e341240beb?source=rss-aa3fe4872612------2</link>
            <guid isPermaLink="false">https://medium.com/p/69e341240beb</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[set]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Leo Kuo]]></dc:creator>
            <pubDate>Fri, 05 Mar 2021 15:26:11 GMT</pubDate>
            <atom:updated>2021-03-05T15:26:11.403Z</atom:updated>
            <content:encoded><![CDATA[<h4>製作一個 Set 遊戲 App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vqz8ldZ70XZ9Nk0fjVExTQ.png" /></figure><p>前陣子 Peter 跟我說到這款遊戲，是史丹佛大學 Swift 課程的期末作業。實際下載其他人製作的 Set game，玩了一下後發現蠻燒腦的，決定自己也來做。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*yyjzzQQ3qHYHRMTW07oDUg.png" /><figcaption>Set 卡牌樣貌</figcaption></figure><h3>遊戲規則</h3><p>先來了解一下 Set 的遊戲規則，這原本是一款卡牌遊戲，遊戲的規則就是從一堆卡牌中，找到可以組成 “Set” 的牌組。總而言之就是一種找牌組的遊戲。</p><h4>何謂 “Set”</h4><p>Set 遊戲中會有 81 張牌（四種特徵，每種特徵有三種，所以總共有 3⁴ = 81 種不同卡片），每一張牌的樣式都不一樣。是由以下特徵進行排列組合而成：</p><ul><li>形狀：菱形、圓角矩形、S型</li><li>顏色：紅色、綠色、藍色</li><li>填充樣式：實心、空心、斜線</li><li>形狀數量：1–3 個</li></ul><p>要組成一個 Set 要有三張牌，並且符合以下規則：</p><ul><li>三張特徵都一樣，例如都是菱形</li><li>三張特徵都不一樣，例如分別為菱形、圓角矩形、S型</li></ul><p>四種特徵都要符合以上特徵，所以其實選定兩張牌時，要組成 Set 的可能性只有一種。看看以下範例：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ybjTvOf6A5rVLc9UG7eRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gg_dvjKrgo8fehW0JuyxLQ.png" /><figcaption>以上皆為 Set (傳統的 Set 中的S型形狀看起來不太順，所以我就它改成了三角形 XD)</figcaption></figure><h3>App 構想</h3><p>玩法的部分，可以有很多種模式變化。市面上的 App 免費版的通常都是限時模式，例如給定 1 分鐘，看可以找出幾組 Set。</p><p>不過實際玩起來發現 1 分鐘太短，所以我製作的版本是找10組 Set，並記錄下所花的時間，作為排名。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNMBxcppR-6CAuDoJA_Z-w.png" /><figcaption>到遊戲頁面後，隨機給 12 張卡牌</figcaption></figure><h3>App 架構</h3><p>用 SetProp struct 記錄卡牌的資訊，包含形狀、數量、填充、顏色：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*j199UwmwdHwgbpHf1wqe3Q.png" /></figure><p>有關 Set 卡牌的處理，我使用了 SetCardHelper 做統一管理：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*1_yHmi89Qkfs5xQ2vB_U6A.png" /></figure><ul><li>allCards：所有卡牌 (81張)</li><li>remainCards：除了場面上的其他牌 (69張)</li><li>currentCards：場面上的牌 (12張)</li><li>currentSets：場面上的牌可組為幾個 Set</li><li>selected：玩家目前選的牌組，key 記錄在 currentCards 中的 index</li><li>setFoundCount：記錄玩家已經找出幾個 Set</li></ul><h3>App 實作</h3><blockquote><strong>判斷是否為 Set</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/595bbd75e8e384a58e6b32e59b819175/href">https://medium.com/media/595bbd75e8e384a58e6b32e59b819175/href</a></iframe><p>這邊使用泛型的寫法，使用 T 代表某一種型態，並宣告為 Comparable，代表這類型皆遵從 Comparable 協議，可以進行比較</p><pre>func isSet&lt;T: Comparable&gt;(_ first: T, _ second: T, _ third: T) -&gt; Bool {<br>    if first == second, second == third {<br>        return true<br>    }<br>    if first != second, second != third, third != first {<br>        return true<br>    }<br>    return false<br>}</pre><p>根據規則，三卡牌特徵一致 return true；三卡牌特徵不一致 return true，除此之外皆是 false</p><p>然後再把選中的卡牌們在 checkSingleSet 中，進行四種特徵的判斷，最後得到這三張是否為 Set</p><blockquote><strong>控制 svg 顏色</strong></blockquote><p>Set 卡牌總共有 81 張，非常的多，如果要使用圖檔的話，設計師會畫到瘋掉… 所以把顏色、數量交給程式生成比較方便</p><p>Xcode 雖然支援 svg 圖片，不過不像網頁開發那樣，容易更換它的填充顏色，所以這邊我使用了 SwiftSVG 這個套件</p><p><a href="https://github.com/mchoe/SwiftSVG">GitHub - mchoe/SwiftSVG: A simple, performant, and lightweight SVG parser</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72d297c9730deab7e7b9280c86eab5d4/href">https://medium.com/media/72d297c9730deab7e7b9280c86eab5d4/href</a></iframe><p>svgURL，先從 Bundle.main.url 中找到專案中的 svg 檔，接著從 SetProp 中決定要有幾個 UIView 。每個 UIView 的 layer 中再畫形狀，在 layer 的 fillColor 中即可設定顏色</p><p>為了達到響應式的設計，所以上述程式碼中，會去計算 layer 的位置，讓它至於 UIView 中央</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*fB7eQ6B6KG6VnOh_0bgF3A.png" /><figcaption>使用 CollectionView Cell，Cell 由外至內為 UIView -&gt; StackView -&gt; UIView(存形狀，可能不只一個)</figcaption></figure><h3>Demo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*S6Pu_MQAVNN4VU0Bc40BIw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69e341240beb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/ios-26-set-%E7%A5%9E%E5%A5%87%E5%BD%A2%E8%89%B2%E7%89%8C-part1-%E9%81%8A%E6%88%B2%E8%A6%8F%E5%89%87%E8%A8%AD%E5%AE%9A-svg-%E6%8E%A7%E5%88%B6-69e341240beb">【iOS】#26 Set(神奇形色牌) Part1: 遊戲規則設定、svg 控制</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>