<?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 Andres Mariscal on Medium]]></title>
        <description><![CDATA[Stories by Andres Mariscal on Medium]]></description>
        <link>https://medium.com/@andresmariscal?source=rss-ef949f997562------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*337d7kODgEX8fgiS.</url>
            <title>Stories by Andres Mariscal on Medium</title>
            <link>https://medium.com/@andresmariscal?source=rss-ef949f997562------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:19:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andresmariscal/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[Unbeatable Tic Tac Toe — An android app using Kotlin]]></title>
            <link>https://medium.com/@andresmariscal/unbeatable-tic-tac-toe-an-android-app-using-kotlin-4f4d2576e6fd?source=rss-ef949f997562------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f4d2576e6fd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andres Mariscal]]></dc:creator>
            <pubDate>Mon, 23 Jan 2017 03:14:04 GMT</pubDate>
            <atom:updated>2017-03-08T20:28:57.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jx9uKkgrfXXd8sM32tgepw.png" /></figure><p>Everyone has played tic tac toe at least once in his life rather in a piece of paper in the classroom or, for those who are very young people, in a smartphone or tablet. So today we are going to explore how to create an unbeatable Tic Tac Toe using Kotlin in Android development.</p><p>The tic tac toe is really easy to understand there are only three scenarios in the game: Cross wins, Nought wins or a draw and if a perfect game from both sides means always a draw. If some of the players make a mistake then for sure the other player will win. So to make a computer player with an unbeatable AI we need to teach it how to always win no matter the seed that the opponent chooses, it will win. Therefore it’s necessary that an algorithm could calculate all the possible moves available for the computer player and determinate the best move. <a href="http://neverstopbuilding.com/minimax">Minimax</a> algorithm suits very good for this!</p><blockquote>An explanation will be given shortly about the minimax algorithm. If you want to go deeper, then click in the link below for a detailed explanation</blockquote><blockquote><a href="http://neverstopbuilding.com/minimax">http://neverstopbuilding.com/minimax</a></blockquote><p>First we need to define the components involved in the game:</p><p>Each cell from the board’s game has to keep a state. Rather if it’s empty or the cross seed has taken the cell, or if nought seed has taken the cell. The Definition of an enum represents those states, just like is described below.</p><pre>enum class <strong>Seed</strong> {<br> <strong>EMPTY, CROSS, NOUGHT</strong><br>}</pre><p>Then define the cell that contains the seed and its corresponding location defined by a row and a column. The initial value of the seed has to be empty and as the game follows each cell will be keeping its corresponding value</p><pre>class <strong>Cell</strong>(val <strong>row</strong>:Int, val <strong>col</strong>:Int) {<br>   var content: Seed = Seed.<strong>EMPTY</strong><br>   fun clear() {<br>     content = Seed.EMPTY<br>   }<br>}</pre><p>Now, the game board is in charge to hold all the components of the game. Also the board will know the result of each move being done, for that reason we have to define all the possible winning scenarios such as vertical, horizontal or diagonal victory.</p><pre>class <strong>Board</strong> {<br><br>    val ROW = 3<br>    val COL = 3<br><br>    var <strong>cells</strong> = <em>array2d</em>&lt;Cell?&gt;(ROW, COL) <strong>{ </strong>null <strong>} </strong><br><br>    val <strong>winningPatterns</strong>: Array&lt;Int&gt; = <em>arrayOf</em>(<br>            0b111000000, 0b000111000, 0b000000111, // rows<br>            0b100100100, 0b010010010, 0b001001001, // columns<br>            0b100010001, 0b001010100)              // diagonals<br><br><br>    ...<br><br>    fun isDraw(): Boolean {<br>        ...<br>    }<br><br>    fun hasWon(thePlayer: Seed): Boolean {<br>        ...<br>    }<br>}</pre><blockquote>In kotlin, instantiate a multidimensional array is not that simple as in java. For more information about multidimensional arrays take a look to these links</blockquote><blockquote><a href="http://stackoverflow.com/questions/28548647/create-generic-2d-array-in-kotlin">Generic arrays</a></blockquote><blockquote><a href="http://stackoverflow.com/questions/27512636/two-dimensional-int-array-in-kotlin">Two dimensional array</a></blockquote><blockquote><a href="https://discuss.kotlinlang.org/t/multi-dimensonal-arrays-are-a-pain-point-in-kotlin/561">Pain point in kotlin</a></blockquote><p>Now lets define our interfaces before getting into the AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*VyIEFlL0P1Mz2w1K5qYmcg.png" /></figure><p>Once we’ve done with the interface, now it’s time to explain how the computer is going to play 🤔 !</p><p>The minimax algorithm intents to minimize the end of the goal score based on a tree decision by saying:</p><ul><li>If the player wins then he/she gets 10 points</li><li>If the computer wins the player looses 10 points</li><li>If no one wins then zero points for both</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*SJIROS97bK2GKSdenJsNtg.png" /></figure><p>If the player does the correct move then he or she earns 10 points otherwise in the next move the opponent will have the chance to take away the 10 points . But how!, how does the computer knows which move to make next?</p><p>As we mentioned before, the computer makes the decision by predicting the player’s moves creating a sequence of trees and evaluating which is the best path in how to take away the player’s points in the closest node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*q90ErLWPxfQejf35jkpNgA.png" /></figure><p>As you can see in the image shown above, following the option <strong>1</strong> and the left edge branch shows how the computer reaches <strong>-10 </strong>score,<strong> </strong>unlike the player the main objective of the computer is to block the player’s path.</p><p>Well, but how do we create this monster? We have to create a computer player that maintain it’s corresponding movements the opponents movements as well. In order to do so the computer needs a reference from the board. Once the computer has the board it’ll be able to predict possible moves until the computer obtains the -10 score or at least obtain zero points.</p><pre>class <strong>AIPlayerMinimax</strong>(<strong>board</strong>: Board) {<br><br>    val ROW = board.ROW<br>    val COL = board.COL<br><br>    var cells = board.cells<br><br>    var <strong>mySeed</strong>: Seed<br>    var <strong>oppSeed</strong>: Seed<br><br>    init {<br>        mySeed = Seed.EMPTY<br>        oppSeed = Seed.EMPTY<br>    }<br><br>    fun setSeed(seed: Seed) {<br>        mySeed = seed<br>        <strong>oppSeed</strong> = when (mySeed) {<br>            Seed.CROSS -&gt; Seed.NOUGHT<br>            else -&gt; Seed.CROSS<br>        }<br>    }<br><br>    fun move(): Array&lt;Int&gt;? {<br>        val result = <strong>minimax</strong>(7, mySeed)<br>        return <em>arrayOf</em>(result[1], result[2])<br>    }<br><br>    fun <strong>minimax</strong>(depth: Int, player: Seed): Array&lt;Int&gt; {<br>        ...<br>    }<br><br>    ...<br>}</pre><p>We have to define a maximum depth in building the tree, more the depth the more unbeatable the computer gets. Careful! by giving a high value to the depth of the algorithm your CPU will work a lot, because the algorithm is recursive.</p><p>Then, evaluating the cells of the game board generates all the movements allowed. Along we advance in the depth of the tree, each level’s depth alternates the players, that way the computer could begin predicting the best possible move to block the player’s next move.</p><p>Using the bestRow and bestCol variables to store the best movement the computer could make.</p><ul><li>At the beginning a -1 value is assigned to both variables.</li><li>As advancing in the tree, to see whats the best movement a comparison of the movements allowed with the variables bestRow and bestCol is made.</li><li>If it is, then the value of the bestRow is changed for the newest value and the same for the bestCol. Then just jump to the next level.</li><li>If not, a skip to the next level will happen.</li><li>Once the last level it’s reached, simply returns to bestRow and bestCol.</li></ul><pre>fun <strong>minimax</strong>(depth: Int, player: Seed): Array&lt;Int&gt; {<br>    val <strong>nextMoves</strong>: MutableList&lt;Array&lt;Int&gt;&gt; = <strong>generateMoves</strong>()<br><br>    var bestScore = when (mySeed) {<br>        player -&gt; Int.MIN_VALUE<br>        else -&gt; Int.MAX_VALUE<br>    }<br>    var currentScore: Int<br>    var bestRow = -1<br>    var bestCol = -1<br><br>    if(nextMoves.isEmpty() || depth == 0){<br>        bestScore = evaluate()<br>    } else {<br>        nextMoves.<em>forEach </em><strong>{<br>            </strong>cells[<strong>it</strong>[0]][<strong>it</strong>[1]]?.content = player<br><br>            if (player == mySeed){<br>                currentScore = <strong>minimax</strong>(depth - 1, oppSeed)[0]<br>                if(currentScore &gt; bestScore) {<br>                    bestScore = currentScore<br>                    bestRow = <strong>it</strong>[0]<br>                    bestCol = <strong>it</strong>[1]<br>                }<br>            } else {<br>                currentScore = <strong>minimax</strong>(depth - 1, mySeed)[0]<br>                if(currentScore &lt; bestScore) {<br>                    bestScore = currentScore<br>                    bestRow = <strong>it</strong>[0]<br>                    bestCol = <strong>it</strong>[1]<br>                }<br>            }<br>        cells[<strong>it</strong>[0]][<strong>it</strong>[1]]?.content = Seed.EMPTY<br>        <strong>}<br>    </strong>}<br>    return <em>arrayOf</em>(bestScore, bestRow, bestCol)<br>}</pre><p>This way the computer will know how to advance throughout the game, always with the intention to block the player’s movement or if a movement that gets the player it’s -10 points its found the computer will take the points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*heqkysA9bll86G1V20wjJg.gif" /></figure><p>Basically that is all, the intention of this article was to get in touch with kotlin language and share with everyone it’s implementation from the algorithm minimax.</p><p>You can find the source code in <a href="https://github.com/mariizcal/KotlinTicTacToe">https://github.com/mariizcal/KotlinTicTacToe</a></p><p><a href="https://play.google.com/store/apps/details?id=com.mariizcal.tictactoe">Click here to download the app from google play store</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f4d2576e6fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>