<?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 Ansh Gaikwad on Medium]]></title>
        <description><![CDATA[Stories by Ansh Gaikwad on Medium]]></description>
        <link>https://medium.com/@anshyg2002?source=rss-32fa483c1cb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_HRAIQALD9x4y_Vl9LRHlA.jpeg</url>
            <title>Stories by Ansh Gaikwad on Medium</title>
            <link>https://medium.com/@anshyg2002?source=rss-32fa483c1cb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:23:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anshyg2002/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[Quick Introduction to Image Tracking using AR Foundation]]></title>
            <link>https://medium.com/dscvitpune/quick-introduction-to-image-tracking-using-ar-foundation-dea7d2fbdfe9?source=rss-32fa483c1cb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dea7d2fbdfe9</guid>
            <category><![CDATA[augmented-reality]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ansh Gaikwad]]></dc:creator>
            <pubDate>Sun, 20 Dec 2020 05:13:28 GMT</pubDate>
            <atom:updated>2020-12-20T05:13:28.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eo12qQK74bOtMLKd6co5Eg.jpeg" /></figure><p><a href="https://en.wikipedia.org/wiki/Augmented_reality"><strong>Augmented Reality</strong></a> development has been on a hype since late 2017 when Google launched its <a href="https://developers.google.com/ar"><strong>ARcore</strong></a><strong> </strong>SDK for android devices and Apple launched its <a href="https://developer.apple.com/documentation/arkit"><strong>ARkit</strong></a><strong> </strong>SDK for IOS devices.</p><p>But there was a big drawback to that, as developers weren&#39;t able to build cross-platform apps for android and IOS devices as both of them had different SDK tools.</p><p>Then Unity launched the <a href="https://docs.unity3d.com/Packages/com.unity.xr.arfoundation@4.1/manual/index.html"><strong>AR Foundation</strong></a> SDK where AR developers were able to build <strong>cross-platform apps</strong> by just switching the platform inside the Unity engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dll-ktet4Y5bULYULU3eLQ.png" /><figcaption>AR Foundation Chart</figcaption></figure><h3><strong>Today’s Outline</strong></h3><p>Today, we will be implementing a basic AR app based on “<strong>Image tracking</strong>” with <strong>absolutely no code required</strong> by Unity’s AR Foundation.</p><h3>What is Image Tracking?</h3><p><strong>Image Tracking</strong> is an augmented reality feature that gives apps the ability to detect 2D images, triggering digitally augmented content to appear in the form of videos, slideshows, 360° panoramas, sound, text, 3D animations, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*gZMVIZjSgzpXgkfQA_-l4g.gif" /><figcaption>Example of an Image Tracking Handheld AR app</figcaption></figure><h3>Requirements</h3><ol><li>An installation of a stable <a href="https://unity.com/"><strong>Unity Engine</strong></a> on Windows or MAC</li><li>An <strong>AR supported</strong> Android or IOS device.</li></ol><h3>Let’s Get Started</h3><p>Create a Unity 3D project and call it “<strong>Image Tracking</strong>” or whatever you like. You can select whatever template you like as we will be changing it later in our Scene. Fill up any Project Name and Location as per your convenience. Click on create when you are done filling up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjK9g4QY5xzNWbNkuCHvBA.png" /><figcaption>Creating a new project</figcaption></figure><h3>Setting up Unity 3D for AR Development</h3><p>There are some <strong>build setting</strong> that we must be aware of before deploying an AR application. I will be walking you through the build settings for deploying an AR app for Android. But in case you are an IOS user, then give a response below, I will then share a tutorial below which IOS users can follow for setting up the build settings for IOS.</p><p><strong>Step 1</strong>: Open up the Build Settings -&gt; Switch platform to Android -&gt; And click on Player Settings</p><p><strong>Step 2</strong>: Open up the drop-down menu for Other Settings and change the package name to some like “<em>com.yourcompanyname.yourappname</em>”.</p><p><strong>Step 3</strong>: Disable Multithreaded Rendering as ARcore doesn&#39;t support it yet.</p><p><strong>Step 4</strong>: Enable Auto Graphics API as ARcore doesn&#39;t support the Vulkan Graphics API.</p><p><strong>Step 5</strong>: Set the minimum API level to be 24, as its the minimum API level required by ARcore.</p><p><strong>Step 6</strong>: Leave the rests to default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*9r3yuQoqr3h-5kVB9Y4IEQ.png" /><figcaption>Setting up build settings</figcaption></figure><h3>Installing the AR foundation package</h3><p>Now, head over to the <a href="https://docs.unity3d.com/Packages/com.unity.package-manager-ui@1.8/manual/index.html#:~:text=Use%20the%20Unity%20Package%20Manager,update%20packages%20for%20each%20project."><strong>Unity package manager</strong></a> by <strong>Window -&gt; Package Manager</strong> and Install the latest stable build of AR foundation and ARcore or ARkit considering your current platform Android or IOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Qkb6_akTWVWwHH3RUIG0OA.png" /><figcaption>Installing AR Foundation Packages</figcaption></figure><p>Note: The <a href="https://docs.unity3d.com/Packages/com.unity.xr.arsubsystems@4.1/manual/index.html"><strong>AR SubSystems</strong></a><strong> </strong>package is automatically installed after installing the AR Foundation package.</p><h3>Setting up our AR Scene</h3><p>Note we have an extra column named <strong>XR</strong> while importing inside the scene. If you are unable to see that kindly recheck if you have installed the correct packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGO7rhqYFf7E04CMN3GVwg.png" /><figcaption>Setting up the AR Scene — I</figcaption></figure><p>Moving forward, we will be needing <a href="https://docs.unity3d.com/Packages/com.unity.xr.arfoundation@4.1/manual/index.html"><strong>AR Session Origin</strong></a> and <strong>AR Session</strong>. Note that we have an <strong>AR Camera</strong> inside the AR Session Origin. This will be the Default Camera of our scene and therefore we can go and delete the Main Camera imported after selecting the 3D Template.</p><p>Don’t forget to save your scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJjrzy4BAHz6QP6V6eYAHg.png" /><figcaption>Setting up the AR Scene — II</figcaption></figure><h3>Implementing Image Tracking</h3><p>Let&#39;s go to AR Session Origin and add the “<a href="https://docs.unity3d.com/Packages/com.unity.xr.arfoundation@4.1/manual/tracked-image-manager.html"><strong>AR Tracked Image Manager</strong></a>” Script after clicking the add components button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ZMTQrDOm5yeM2Q1Pn-Q4_A.png" /><figcaption>Adding AR Tracked Image Manager Script</figcaption></figure><p>So, here we will be having <strong>three</strong> components:</p><ol><li><strong><em>Reference Library</em></strong><em>: The images which you want to track.</em></li><li><strong><em>Max number of moving images</em></strong><em>: As the name suggests.</em></li><li><strong><em>Tracked Image Prefab</em></strong><em>: The prefab to display after the image is tracked.</em></li></ol><p>So, as we have seen that we have to provide a Reference Library to the AR Tracked Image Manager Script, we will go ahead and create one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ohK6nYRNnXdazYWnjukUw.png" /><figcaption>Creating a Reference Image Library</figcaption></figure><p>After creating the Reference Image Library we should add an Image which will be the used for tracking. You can get some images from <a href="https://github.com/AnshGaikwad/ImageTrackingAR/tree/master/Assets/Images"><strong>here</strong></a>.</p><p><strong>Note</strong>: You can add as many images as you want just click on Add Images and drag the image inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*BA1KB1vCEHYGniDKcvJfKA.png" /><figcaption>Adding Image to the Reference Image Library</figcaption></figure><p>Great, now as our <strong>Reference Image Library</strong> is ready, we will be now needing the <strong>Tracked Image Prefab</strong>.</p><p>Now, as we are going to implement a<strong> video poster</strong> we will create a Cube Prefab and then add the video player to it. You can get some videos from <a href="https://github.com/AnshGaikwad/ImageTrackingAR/tree/master/Assets/Videos"><strong>here</strong></a>. So, let&#39;s do it.</p><p><strong>Step 1</strong>: Create a 3D Object Cube and Set up the dimensions.</p><p><strong>Step 2</strong>: Drag it down to our Assets folder and then add the video player to it.</p><p><strong>Step 3</strong>: You may enable “<em>loop</em>” and disable “<em>wait for first frame</em>” as per your wish.</p><p>Well now, we have the prefab set up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*84mdNUeou0dj-DmeFzSI1w.png" /><figcaption>Setting up the Tracked Image Prefab</figcaption></figure><p>Now, drag your <strong>Reference Image Library</strong> and your <strong>Tracked Image Prefab </strong>inside the AR Tracked Image Manager Script of the AR Session Origin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*rKYE-odTYUixPtT0Yq9muQ.png" /><figcaption>AR Session Origin</figcaption></figure><p>Great now, our AR app is ready to build and run. Head over to build settings and build and run your app.</p><p><strong>Note</strong>: Make sure you have connected your Android device with the USB cable and have USB debugging enabled. If you are facing any issues, you can follow the steps given<strong> </strong><a href="https://developer.android.com/studio/debug/dev-options#:~:text=To%20enable%20USB%20debugging%2C%20toggle,Android%208.0."><strong>here</strong></a>.</p><h3>Some of the issues you may come across</h3><p><strong>Issue 1</strong>: If you are getting this dialog box after build and run. Then you can simply visit this <a href="https://developers.google.com/ar/develop/unity/android-11-build"><strong>site</strong></a> for the fix. The Unity 2020 build may not face this issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*hOrmB5DPwUfCDr2w9bCGag.png" /><figcaption>Build Failure Dialog Box</figcaption></figure><p><strong>Issue 2</strong>: If your video player is inverting the video you may do the following changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*1DlYT_tkPsyQQNLqOlqPQw.png" /><figcaption>Sirius Black Video Settings</figcaption></figure><h3>Final Build</h3><p>Now is the time that we test our hard work that we spend the last couple of minutes. Let’s go <strong>Build Settings -&gt; Build and Run</strong>.</p><p>It must Build successfully and you may have a similar output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*oHZlya2SCsq7Wh_nXTg1JQ.gif" /><figcaption>The Output of our Image Tracking AR Project</figcaption></figure><p>You can explore other examples of this project <a href="https://giphy.com/channel/AnshGaikwad"><strong>here</strong></a>.</p><h3><strong>Conclusion</strong></h3><p><strong>Congratulations guys</strong>, you made it through. You can now implement Image Tracking in your AR application. But now the question arises is, <strong>what’s next</strong>?</p><p>AR Foundation provides a lot of other features such as <strong>Plane Detection</strong>, <strong>World Tracking</strong>, etc. You can find the complete documentation <a href="https://docs.unity3d.com/Packages/com.unity.xr.arfoundation@4.1/manual/index.html"><strong>here</strong></a> and explore various sections by yourself.</p><p>Hopefully, this tutorial was helpful to you guys. In case, if anyone’s stuck you may clone the project from <a href="https://github.com/AnshGaikwad/ImageTrackingAR"><strong>here</strong></a>. Also, you all are free to ask any of your doubts below or connect with me on <a href="https://www.linkedin.com/in/ansh-gaikwad-13814219a/"><strong>LinkedIn</strong></a>, I would be happy to help you out.</p><p><strong>Thank you for reading</strong>, see you guys next time. And don’t forget to leave a bunch of claps, if this blog helped you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dea7d2fbdfe9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dscvitpune/quick-introduction-to-image-tracking-using-ar-foundation-dea7d2fbdfe9">Quick Introduction to Image Tracking using AR Foundation</a> was originally published in <a href="https://medium.com/dscvitpune">Google Developer Students Club Vishwakarma Institute of Technology, Pune</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s create a Chess AI]]></title>
            <link>https://medium.com/dscvitpune/lets-create-a-chess-ai-8542a12afef?source=rss-32fa483c1cb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8542a12afef</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chess]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ansh Gaikwad]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 10:17:54 GMT</pubDate>
            <atom:updated>2020-10-14T10:17:54.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TJuR-eC8H_U6JmkjVDsnw.jpeg" /></figure><p><strong>Chess</strong> has been played by the world’s masterminds for ages and is the game where the <strong>brain needs a lot of processing</strong>. So, how can we teach a computer to play a mastermind game like chess? Let’s check it out.</p><p>To get started all you need is a <a href="https://www.python.org/"><strong>python3</strong></a> interpreter installed in your system and the basic level of python3. Cool right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*hxy_h4Uu-XD3RmwBLfYvIQ.gif" /></figure><h3><strong>Today’s Outline</strong></h3><ol><li>Board Representation</li><li>Board Evaluation</li><li>Move Selection</li><li>Testing our AI</li><li>Making an Interface</li></ol><h3><strong>Board Representation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gSajQ3p3FH2ieLxd" /></figure><p>Before writing any algorithm for our engine it’s important for us to code the logic behind chess pieces i.e. assign every possible legal move to each and every chess piece.</p><p>For that, our work has been made a lot simpler by the <a href="https://github.com/niklasf/python-chess"><strong>python-chess</strong></a> library which will provide us with all of the <strong>move generation</strong> and <strong>validation</strong>. So, let’s start by installing it.</p><pre>!pip install python-chess</pre><p>Now, as we have the library installed, we can start by importing and then initializing the board.</p><pre>import chess<br>board = chess.Board()<br>board</pre><p>This will be the output which you will be able to see in your notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWQzMpwihsMCrMTAzC6q9Q.png" /><figcaption>Output-1</figcaption></figure><p>This board object will be the complete board representation which will provide us with some important functions such as <strong>board.is_checkmate()</strong> to check if there’s a checkmate, <strong>board.push()</strong> to append a move, <strong>board.pop()</strong> to undo the last move, etc. You can read the complete documentation <a href="https://python-chess.readthedocs.io/en/latest/">here</a>.</p><h3><strong>Board Evaluation</strong></h3><p>For evaluating the board initially, we must think about how a Grandmaster would think in his respective match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*i-hzgWZTgu2maTq-v7-TJQ.gif" /></figure><ul><li><em>Some of the </em><strong><em>points</em></strong><em> which should come in our mind are:</em></li></ul><ol><li>Avoid exchanging one minor piece for three pawns.</li><li>Always have the bishop in pairs.</li><li>Avoid exchanging two minor pieces for a rook and a pawn.</li></ol><ul><li><em>So, the </em><strong><em>equations</em></strong><em> from the above insights will be:</em></li></ul><ol><li>Bishop &gt; 3 Pawns &amp; Knight &gt; 3 Pawns</li><li>Bishop &gt; Knight</li><li>Bishop + Knight &gt; Rook + Pawn</li></ol><p>By simplifying the above equations, we get Bishop &gt; Knight &gt; 3 Pawns. Also, we must convert the third equation as Bishop + Knight = Rook + 1.5 Pawn as two minor pieces are worth a rook and two pawns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*DFrBMVzVHRT7qoHJKK1qIQ.gif" /></figure><p>We will use<a href="https://www.chessprogramming.org/Piece-Square_Tables"> <strong>piece square tables</strong></a> to evaluate our board pieces and the values will be set in an 8x8 matrix such as in chess such that it must have a <strong>higher</strong> value at favorable positions and a<strong> lower</strong> value at a non-favorable place.</p><p>For example, the probability of the white’s king crossing the centerline will be less than 20% and therefore we will place negative values in that matrix.</p><p>Let’s take another example, suppose the Queen, she would like her to be placed at the center position as she can dominate more number of positions from the center and therefore we will set higher values at the center and the same for the other pieces as chess is all about defending the king and dominating the center.</p><p><em>Enough of the theory lets initialize the piece square tables:</em></p><pre>pawntable = [<br>    0, 0, 0, 0, 0, 0, 0, 0,<br>    5, 10, 10, -20, -20, 10, 10, 5,<br>    5, -5, -10, 0, 0, -10, -5, 5,<br>    0, 0, 0, 20, 20, 0, 0, 0,<br>    5, 5, 10, 25, 25, 10, 5, 5,<br>    10, 10, 20, 30, 30, 20, 10, 10,<br>    50, 50, 50, 50, 50, 50, 50, 50,<br>    0, 0, 0, 0, 0, 0, 0, 0]<br><br>knightstable = [<br>    -50, -40, -30, -30, -30, -30, -40, -50,<br>    -40, -20, 0, 5, 5, 0, -20, -40,<br>    -30, 5, 10, 15, 15, 10, 5, -30,<br>    -30, 0, 15, 20, 20, 15, 0, -30,<br>    -30, 5, 15, 20, 20, 15, 5, -30,<br>    -30, 0, 10, 15, 15, 10, 0, -30,<br>    -40, -20, 0, 0, 0, 0, -20, -40,<br>    -50, -40, -30, -30, -30, -30, -40, -50]</pre><pre>bishopstable = [<br>    -20, -10, -10, -10, -10, -10, -10, -20,<br>    -10, 5, 0, 0, 0, 0, 5, -10,<br>    -10, 10, 10, 10, 10, 10, 10, -10,<br>    -10, 0, 10, 10, 10, 10, 0, -10,<br>    -10, 5, 5, 10, 10, 5, 5, -10,<br>    -10, 0, 5, 10, 10, 5, 0, -10,<br>    -10, 0, 0, 0, 0, 0, 0, -10,<br>    -20, -10, -10, -10, -10, -10, -10, -20]</pre><pre>rookstable = [<br>    0, 0, 0, 5, 5, 0, 0, 0,<br>    -5, 0, 0, 0, 0, 0, 0, -5,<br>    -5, 0, 0, 0, 0, 0, 0, -5,<br>    -5, 0, 0, 0, 0, 0, 0, -5,<br>    -5, 0, 0, 0, 0, 0, 0, -5,<br>    -5, 0, 0, 0, 0, 0, 0, -5,<br>    5, 10, 10, 10, 10, 10, 10, 5,<br>    0, 0, 0, 0, 0, 0, 0, 0]</pre><pre>queenstable = [<br>    -20, -10, -10, -5, -5, -10, -10, -20,<br>    -10, 0, 0, 0, 0, 0, 0, -10,<br>    -10, 5, 5, 5, 5, 5, 0, -10,<br>    0, 0, 5, 5, 5, 5, 0, -5,<br>    -5, 0, 5, 5, 5, 5, 0, -5,<br>    -10, 0, 5, 5, 5, 5, 0, -10,<br>    -10, 0, 0, 0, 0, 0, 0, -10,<br>    -20, -10, -10, -5, -5, -10, -10, -20]</pre><pre>kingstable = [<br>    20, 30, 10, 0, 0, 10, 30, 20,<br>    20, 20, 0, 0, 0, 0, 20, 20,<br>    -10, -20, -20, -20, -20, -20, -20, -10,<br>    -20, -30, -30, -40, -40, -30, -30, -20,<br>    -30, -40, -40, -50, -50, -40, -40, -30,<br>    -30, -40, -40, -50, -50, -40, -40, -30,<br>    -30, -40, -40, -50, -50, -40, -40, -30,<br>    -30, -40, -40, -50, -50, -40, -40, -30]</pre><p><em>Now let’s get our evaluation function by following these four methods:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*AvNaGUWVZom1y8XSkWJxYg.gif" /></figure><p><strong>Firstly</strong>, let’s check if the game is still going on.</p><p>Now the logic behind coding this stage is that If it returns true at checkmate then it will check whose turn to make a move, if the current turn is of WHITE it must return -9999 i.e previous turn must be of BLACK, and BLACK wins or else it must return +9999 and then White wins. For stalemate or any insufficient material, let’s return 0 as its draw.</p><p>So, let’s code:</p><pre>if board.is_checkmate():<br>        if board.turn:<br>            return -9999<br>        else:<br>            return 9999<br>if board.is_stalemate():<br>        return 0<br>if board.is_insufficient_material():<br>        return 0</pre><p><strong>Secondly</strong>, we must calculate the total number of pieces so that we can pass it into our material function.</p><pre>wp = len(board.pieces(chess.PAWN, chess.WHITE))<br>bp = len(board.pieces(chess.PAWN, chess.BLACK))<br>wn = len(board.pieces(chess.KNIGHT, chess.WHITE))<br>bn = len(board.pieces(chess.KNIGHT, chess.BLACK))<br>wb = len(board.pieces(chess.BISHOP, chess.WHITE))<br>bb = len(board.pieces(chess.BISHOP, chess.BLACK))<br>wr = len(board.pieces(chess.ROOK, chess.WHITE))<br>br = len(board.pieces(chess.ROOK, chess.BLACK))<br>wq = len(board.pieces(chess.QUEEN, chess.WHITE))<br>bq = len(board.pieces(chess.QUEEN, chess.BLACK))</pre><p><strong>Third</strong>, let’s calculate the scores.</p><p>The <strong>material score</strong> is calculated by the summation of all respective piece’s weights multiplied by the difference between the number of that respective piece between white and black.</p><p>The <strong>individual pieces score</strong> is the sum of piece-square values of positions where the respective piece is present at that instance of the game.</p><pre>material = 100 * (wp - bp) + 320 * (wn - bn) + 330 * (wb - bb) + 500 * (wr - br) + 900 * (wq - bq)</pre><pre>pawnsq = sum([pawntable[i] for i in board.pieces(chess.PAWN, chess.WHITE)])<br>pawnsq = pawnsq + sum([-pawntable[chess.square_mirror(i)]<br>                       for i in board.pieces(chess.PAWN, chess.BLACK)])</pre><pre>knightsq = sum([knightstable[i] for i in board.pieces(chess.KNIGHT, chess.WHITE)])<br>knightsq = knightsq + sum([-knightstable[chess.square_mirror(i)]<br>                           for i in board.pieces(chess.KNIGHT, chess.BLACK)])</pre><pre>bishopsq = sum([bishopstable[i] for i in board.pieces(chess.BISHOP, chess.WHITE)])<br>bishopsq = bishopsq + sum([-bishopstable[chess.square_mirror(i)]<br>                           for i in board.pieces(chess.BISHOP, chess.BLACK)])</pre><pre>rooksq = sum([rookstable[i] for i in board.pieces(chess.ROOK, chess.WHITE)])<br>rooksq = rooksq + sum([-rookstable[chess.square_mirror(i)]<br>                       for i in board.pieces(chess.ROOK, chess.BLACK)])</pre><pre>queensq = sum([queenstable[i] for i in board.pieces(chess.QUEEN, chess.WHITE)])<br>queensq = queensq + sum([-queenstable[chess.square_mirror(i)]<br>                         for i in board.pieces(chess.QUEEN, chess.BLACK)])</pre><pre>kingsq = sum([kingstable[i] for i in board.pieces(chess.KING, chess.WHITE)])<br>kingsq = kingsq + sum([-kingstable[chess.square_mirror(i)]<br>                       for i in board.pieces(chess.KING, chess.BLACK)])</pre><p>At last, let’s calculate the<strong> evaluation function</strong> which will return the <strong>summation</strong> of the material scores and the individual scores for white and when it comes for black, let’s negate it.</p><p><strong>(As, favorable conditions for White = unfavorable conditions for Black)</strong></p><pre>eval = material + pawnsq + knightsq + bishopsq + rooksq + queensq + kingsq</pre><pre>if board.turn:<br>    return eval<br>else:<br>    return -eval</pre><p><em>Let&#39;s summarize our evaluation function right now, with the help of the flowchart given below:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*IEkkyvkDROHAFr7N" /><figcaption>Flowchart for the evaluation function</figcaption></figure><h3><strong>Move Selection</strong></h3><p>This will be the last step for our algorithm where we will use the <a href="https://www.chessprogramming.org/Negamax"><strong>Negamax</strong></a> Implementation of the <a href="https://www.chessprogramming.org/Minimax"><strong>Minimax Algorithm</strong></a> which is a mostly used algorithm for any two-player games such as checkers, snake, and ladders, etc. Then will later optimize it using <a href="https://www.chessprogramming.org/Alpha-Beta"><strong>Alpha-Beta pruning</strong></a> which will in turn reduce our execution time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*dLm14nzQvPa8NaQx06Eh-Q.gif" /></figure><p>For the smartness of our engine, we can use the initial moves from a book in which moves will be stored with a lot of opening moves by chess Grandmasters in a bin format. You can download some of them from <a href="https://github.com/AnshGaikwad/Chess-World/tree/master/books">here</a>.</p><pre>import chess.polygot<br>try:<br>    move = chess.polyglot.MemoryMappedReader(&quot;C:/Users/your_path/books/human.bin&quot;).weighted_choice(board).move<br>    return move</pre><p>Now, let’s dig into our minimax algorithm. It’s a decision rule used in <a href="https://www.chessprogramming.org/Artificial_Intelligence"><strong>artificial intelligence</strong></a>, decision theory, game theory, statistics, and philosophy for minimizing the possible loss for a worst-case scenario. In simple words, at each step, it assumes that player A is trying to <strong>maximize</strong> its chances of winning, and in the next turn player B is trying to <strong>minimize</strong> the chances of winning.</p><p><em>Check out the tree from below for a better understanding of the algorithm:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*qy-uImcaIA8XWOzN" /><figcaption>A minimax tree example from Wikipedia</figcaption></figure><p>But we will be using the negamax variant of minimax for better results as we will need only one function that is to maximize the utility of both the players. The difference is that here, <strong>one player loss is equal to another player’s gain </strong>and vice versa. In terms of the game, the value of the given position to the first player is the negation of the value to the second player.</p><p><em>You can differentiate the tree given below.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*N_i_7GevlxGu18p8" /><figcaption>A negamax tree example</figcaption></figure><p>Initially, we will set alpha as negative infinity and beta is positive infinity so that, <strong>both players start with the worst possible score</strong>. So, let&#39;s code.</p><pre>except:<br>    bestMove = chess.Move.null()<br>    bestValue = -99999<br>    alpha = -100000<br>    beta = 100000<br>    for move in board.legal_moves:<br>        board.push(move)<br>        boardValue = -alphabeta(-beta, -alpha, depth - 1)<br>        if boardValue &gt; bestValue:<br>            bestValue = boardValue<br>            bestMove = move<br>        if (boardValue &gt; alpha):<br>            alpha = boardValue<br>        board.pop()<br>    return bestMove</pre><p><em>Okay, so let&#39;s understand what we did here with this flowchart:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g8dDeZ-m0BMs6Z6p" /><figcaption>Flowchart for the search function</figcaption></figure><p>Now, the next step is the alpha-beta pruning for the <strong>optimization of our execution speed</strong>.</p><p>Let’s not go deep in the algorithm but just understand that we are applying this logic just to <strong>eliminate most of the unnecessary iterations</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*LXiIQkgWlkzKCaxj" /><figcaption>An illustration of alpha-beta pruning from Wikipedia</figcaption></figure><p><em>Let’s Code:</em></p><pre>def alphabeta(alpha, beta, depthleft):<br>    bestscore = -9999<br>    if (depthleft == 0):<br>        return quiesce(alpha, beta)<br>    for move in board.legal_moves:<br>        board.push(move)<br>        score = -alphabeta(-beta, -alpha, depthleft - 1)<br>        board.pop()<br>        if (score &gt;= beta):<br>            return score<br>        if (score &gt; bestscore):<br>            bestscore = score<br>        if (score &gt; alpha):<br>            alpha = score<br>    return bestscore</pre><p><em>Now, let’s revise the alphabeta function with this flowchart given below:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LRkPWu646aLI9CnP" /><figcaption>Flowchart for the alphabeta function</figcaption></figure><p>Now comes the <strong>Quiescence search</strong>, the purpose of this search is to only evaluate “quiet” positions, i.e the positions where there are no winning tactical moves to be made.</p><p>This search is needed to avoid the <a href="https://www.chessprogramming.org/Horizon_Effect"><strong>horizon effect</strong></a> which is caused by the <strong>depth limitation</strong> of the search algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*z93nv4DOf-1odSIqkR5upg.gif" /><figcaption>A Gif for illustrating the horizon effect</figcaption></figure><p>Let’s understand the horizon effect with the above-given gif like there’s a stage when our brain stops to respond when we are overthinking something and this same happens here and that’s why we apply the quiescence search.</p><p><em>Okay, let’s code:</em></p><pre>def quiesce(alpha, beta):<br>    stand_pat = evaluate_board()<br>    if (stand_pat &gt;= beta):<br>        return beta<br>    if (alpha &lt; stand_pat):<br>        alpha = stand_pat</pre><pre>for move in board.legal_moves:<br>        if board.is_capture(move):<br>            board.push(move)<br>            score = -quiesce(-beta, -alpha)<br>            board.pop()</pre><pre>if (score &gt;= beta):<br>                return beta<br>            if (score &gt; alpha):<br>                alpha = score<br>    return alpha</pre><p><em>So let’s summarise the function in a bit:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4_B2AjPwBlotD9bt" /><figcaption>Flowchart for the quiesce function</figcaption></figure><p>And now we are ready with our algorithm. Thanks for your patience guys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*caCxUuHCt8-GcwBoxyQHsg.gif" /></figure><h3><strong>Testing our AI</strong></h3><p>Before starting to code the testing part we will need to import some of the libraries so let’s get to it:</p><pre>import chess.svg<br>import chess.pgn<br>import chess.engine<br>from IPython.display import SVG</pre><p>Now, today we will be doing<strong> three tests</strong> today which will be</p><ol><li>AI Vs Human</li><li>Self Play (i.e AI vs AI)</li><li>AI Vs Stockfish (You can get info about stockfish12 <a href="https://stockfishchess.org/">here</a>)</li></ol><p>So, without wasting any further time let’s get started.</p><h4>AI Vs Human</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*oU8BeyQYErhEje6vkQrHXA.gif" /></figure><pre># use this for computer move<br>mov = selectmove(3)<br>board.push(mov)<br>board</pre><pre># use this for human move, where e5 is the example move<br>board.push_san(&quot;e5&quot;)<br>board</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*89qnTPlkdja5xQHy1WmJ5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*8bdOUniVmdXZooe6J94r6g.png" /><figcaption>Output-2</figcaption></figure><p>So, the <strong>AI chooses to go g1f3</strong>, which is a pretty smart move.</p><h4>Self-Play</h4><p><em>Let’s make our AI fight itself now:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*cCTvN9ZaEjlu5RA1uK3WEA.gif" /></figure><pre>count = 0<br>movehistory = []<br>game = chess.pgn.Game()<br>board = chess.Board()</pre><pre>while not board.is_game_over(claim_draw=True):<br>    if board.turn:<br>        count += 1<br>        print(f&#39;\n{count}]\n&#39;)<br>        move = selectmove(3)<br>        board.push(move)<br>        print(board)<br>        print()<br>    else:<br>        move = selectmove(3)<br>        board.push(move)<br>        print(board)</pre><pre>game.add_line(movehistory)<br>game.headers[&quot;Event&quot;] = &quot;Self Tournament 2020&quot;<br>game.headers[&quot;Site&quot;] = &quot;Pune&quot;<br>game.headers[&quot;Date&quot;] = str(datetime.datetime.now().date())<br>game.headers[&quot;Round&quot;] = 1<br>game.headers[&quot;White&quot;] = &quot;Ai&quot;<br>game.headers[&quot;Black&quot;] = &quot;Ai&quot;<br>game.headers[&quot;Result&quot;] = str(board.result(claim_draw=True))</pre><pre>print(game)<br>SVG(chess.svg.board(board=board,size=400))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_DrDNNhbqIVp-p02GQxEQ.png" /><figcaption>Output-3</figcaption></figure><h4>AI Vs Stockfish</h4><p>Now, let’s make our AI fight Stockfish. You can download the <strong>Stockfish engine </strong>from <a href="https://stockfishchess.org/download/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*6ZfkIO2E8AmuDhKaCowYfw.gif" /></figure><pre>count = 0<br>movehistory = []<br>game = chess.pgn.Game()<br>board = chess.Board()<br>engine = chess.engine.SimpleEngine.popen_uci(&quot;your_path/stockfish.exe&quot;)</pre><pre>while not board.is_game_over(claim_draw=True):<br>    if board.turn:<br>        count += 1<br>        print(f&#39;\n{count}]\n&#39;)<br>        move = engine.play(board, chess.engine.Limit(time=0.1))<br>        movehistory.append(move.move)<br>        board.push(move.move)<br>        print(board)<br>    else:<br>        move = selectmove(3)<br>        movehistory.append(move)<br>        board.push(move)<br>        print(board)</pre><pre>game.add_line(movehistory)<br>game.headers[&quot;Result&quot;] = str(board.result(claim_draw=True))</pre><pre>print(game)</pre><pre>SVG(chess.svg.board(board=board, size=400))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWKZu_LuXDLRDPw-0RS9Kg.png" /><figcaption>Output-4</figcaption></figure><p>So, yes our AI is not smart enough to beat the stockfish 12 but still, he managed to keep the fight for 20 moves.</p><p>There are a lot more <strong>open-source UCI compatible chess engines</strong> available for more of the testing purposes, you can find them <a href="https://github.com/AnshGaikwad/Chess-World/tree/master/engines">here</a>.</p><h3>Making an Interface</h3><p>The above testing seems to be a <strong>lot of code</strong>. That’s why let’s code an interface, clean up our code, and then test our AI again.</p><pre># Remaining imports<br>import traceback<br>from flask import Flask, Response, request<br>import webbrowser</pre><pre># Searching Ai&#39;s Move<br>def aimove():<br>    move = selectmove(3)<br>    board.push(move)</pre><pre># Searching Stockfish&#39;s Move<br>def stockfish():<br>    engine = chess.engine.SimpleEngine.popen_uci(<br>        &quot;your_path/stockfish.exe&quot;)<br>    move = engine.play(board, chess.engine.Limit(time=0.1))<br>    board.push(move.move)</pre><pre>app = Flask(__name__)</pre><pre># Front Page of the Flask Web Page<br>@app.route(&quot;/&quot;)<br>def main():<br>    global count, board<br>    ret = &#39;&lt;html&gt;&lt;head&gt;&#39;<br>    ret += &#39;&lt;style&gt;input {font-size: 20px; } button { font-size: 20px; }&lt;/style&gt;&#39;<br>    ret += &#39;&lt;/head&gt;&lt;body&gt;&#39;<br>    ret += &#39;&lt;img width=510 height=510 src=&quot;/board.svg?%f&quot;&gt;&lt;/img&gt;&lt;/br&gt;&lt;/br&gt;&#39; % time.time()<br>    ret += &#39;&lt;form action=&quot;/game/&quot; method=&quot;post&quot;&gt;&lt;button name=&quot;New Game&quot; type=&quot;submit&quot;&gt;New Game&lt;/button&gt;&lt;/form&gt;&#39;<br>    ret += &#39;&lt;form action=&quot;/undo/&quot; method=&quot;post&quot;&gt;&lt;button name=&quot;Undo&quot; type=&quot;submit&quot;&gt;Undo Last Move&lt;/button&gt;&lt;/form&gt;&#39;<br>    ret += &#39;&lt;form action=&quot;/move/&quot;&gt;&lt;input type=&quot;submit&quot; value=&quot;Make Human Move:&quot;&gt;&lt;input name=&quot;move&quot; type=&quot;text&quot;&gt;&lt;/input&gt;&lt;/form&gt;&#39;<br>    ret += &#39;&lt;form action=&quot;/dev/&quot; method=&quot;post&quot;&gt;&lt;button name=&quot;Comp Move&quot; type=&quot;submit&quot;&gt;Make Ai Move&lt;/button&gt;&lt;/form&gt;&#39;<br>    ret += &#39;&lt;form action=&quot;/engine/&quot; method=&quot;post&quot;&gt;&lt;button name=&quot;Stockfish Move&quot; type=&quot;submit&quot;&gt;Make Stockfish Move&lt;/button&gt;&lt;/form&gt;&#39;<br>    return ret</pre><pre># Display Board<br>@app.route(&quot;/board.svg/&quot;)<br>def board():<br>    return Response(chess.svg.board(board=board, size=700), mimetype=&#39;image/svg+xml&#39;)</pre><pre># Human Move<br>@app.route(&quot;/move/&quot;)<br>def move():<br>    try:<br>        move = request.args.get(&#39;move&#39;, default=&quot;&quot;)<br>        board.push_san(move)<br>    except Exception:<br>        traceback.print_exc()<br>    return main()</pre><pre># Make Ai’s Move<br>@app.route(&quot;/dev/&quot;, methods=[&#39;POST&#39;])<br>def dev():<br>    try:<br>        aimove()<br>    except Exception:<br>        traceback.print_exc()<br>    return main()</pre><pre># Make UCI Compatible engine&#39;s move<br>@app.route(&quot;/engine/&quot;, methods=[&#39;POST&#39;])<br>def engine():<br>    try:<br>        stockfish()<br>    except Exception:<br>        traceback.print_exc()<br>    return main()</pre><pre># New Game<br>@app.route(&quot;/game/&quot;, methods=[&#39;POST&#39;])<br>def game():<br>    board.reset()<br>    return main()</pre><pre># Undo<br>@app.route(&quot;/undo/&quot;, methods=[&#39;POST&#39;])<br>def undo():<br>    try:<br>        board.pop()<br>    except Exception:<br>        traceback.print_exc()<br>    return main()</pre><p><em>Now, let&#39;s execute it all in the next block.</em></p><pre>board = chess.Board()<br>webbrowser.open(&quot;<a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a>&quot;)<br>app.run()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*-pmfjw_55jwbpzWuvGm7jw.gif" /><figcaption>Final Output</figcaption></figure><p><strong>Thanks for reading out patiently guys</strong>. We have successfully completed our Chess AI in about 12 minutes. Now, we can have fun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*NGlXiYBw8cyqhWD5ZgAXRA.gif" /></figure><h3>Conclusion</h3><p>I hope you guys understood most of the things we coded. If not, don’t hesitate to ask your questions in the comment box. As this was a basic implementation of creating a chess engine, I would like to hear what you guys think can make this Chess AI more smarter? <em>Comment down below</em>.</p><p>Also, for more information, you can visit <a href="https://www.chessprogramming.org/Main_Page">here</a>.</p><p>And all of the code can be found <a href="https://github.com/AnshGaikwad/Chess-World">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8542a12afef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dscvitpune/lets-create-a-chess-ai-8542a12afef">Let’s create a Chess AI</a> was originally published in <a href="https://medium.com/dscvitpune">Google Developer Students Club Vishwakarma Institute of Technology, Pune</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>