<?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[Byte-Sized-Code - Medium]]></title>
        <description><![CDATA[A community of programming enthusiasts preaching code. - Medium]]></description>
        <link>https://medium.com/byte-sized-code?source=rss----3ba429f14279---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Byte-Sized-Code - Medium</title>
            <link>https://medium.com/byte-sized-code?source=rss----3ba429f14279---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:04:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/byte-sized-code" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a game of Tic-Tac-Toe in Python]]></title>
            <link>https://medium.com/byte-sized-code/building-a-game-of-tic-tac-toe-in-python-72dd59c5f240?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/72dd59c5f240</guid>
            <category><![CDATA[game-design]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 15:32:38 GMT</pubDate>
            <atom:updated>2021-02-22T15:32:36.596Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first post in a series of posts about building a Reinforcement Learning AI with Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E4yWzbcGG5BHYeRz.png" /><figcaption>A sample game of tic-tac-toe</figcaption></figure><p>The first thing that came to my mind when I started my journey with Reinforcement Learning was to train a bot that will play difficult games for me. I was in hope of building a chess bot that can beat players (I’m still on it! But <a href="https://aceking007.github.io/chess/">here’s</a> a simple bot for you to try out) that I couldn’t beat in my lifetime. But as with anything, my journey had its humble beginnings with some much easier games.</p><p>I figured that instead of writing a very long article that confusingly tries to explain both how to code the logic for the game and an RL algorithm, I would write some much shorter articles that break down the elements and make it easy to understand. So here goes …</p><h3>The Basics</h3><p>So for people who are unaware of the game, they can have a quick look <a href="https://en.wikipedia.org/wiki/Tic-tac-toe">here</a> or play some games <a href="https://www.google.com/search?q=tic+tac+toe">here</a>. We will be building a standard game that has 3 rows and 3 columns. So first we import packages that we need and define the constants:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*ko43tM4u7Ow7RDF6yPu0pA.png" /><figcaption>Basic imports</figcaption></figure><p>We will structure the program in an <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">Object-Oriented</a> way, so, let&#39;s first write the main loop that tells us what the program will do when executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*sXBJzx0WN2mB2nFNsSghxA.png" /><figcaption>The main loop</figcaption></figure><p>As you can see above, we need two classes — one for the game and another for the player. The game class takes in two players as input and has a play method that contains the game loop.</p><h3>The Player Class</h3><p>The player class will be short and easy to write. We have a name for the player and a method called make_move that asks the user for input, validates if the input is correct, and then passes on the move to the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9xpC1Phc7qhOPSDdadmjg.png" /><figcaption>Player class</figcaption></figure><h4>Init</h4><p>The __init__ function is pretty simple, it takes a name provided by the user earlier and sets the player name attribute to the given name.</p><h4>Make Move</h4><p>The make_move function takes as an input the list of available moves. The first line prints out whose turn it is, the next two lines take in inputs from the user as to which row and column they want to cross or circle. The try-except block makes sure that the while loop runs on till the user inputs a valid integer and not some random non-sense.</p><p>The method then parses the row and column values as a tuple and checks whether the tuple appears in the list of available moves — if it does, then the method returns the (row, value) pair; else it asks the user for input again.</p><h3>The Game Class</h3><p>The game class is the chunk of the program. It is a larger class so we will discuss it in parts and understand the logic for each part.</p><h4>Initialization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3emt4nnoicTvZCHrtJ0oGw.png" /><figcaption>The initialization of Game class</figcaption></figure><p>The Game class has a few variables that we need for it to function. The constructor takes in two objects of the player class as inputs and stores them in two variables. The board variable stores the board for the game. I have modeled it as a 2-D numpy array. The boardvariable is initiated to be an array full of 0’s. The boolean variable gameover stores whether the game is over or still continuing. Finally, the turn variable keeps track of which player’s turn it is (1 indicates player 1’s turn and -1 indicates player 2’s turn).</p><h4>The Game Loop</h4><p>Again let’s first tackle the game loop which will tell us more about the functionality of other methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoM9ngGXtEGi2P9CLk9Ppw.png" /><figcaption>The game loop</figcaption></figure><p>So the main game loop contains a while condition that depends on the value of gameovervariable. Basically, till the game is not over the code inside the while loop is executed.</p><p>self.show_board()is a function that prints the board to the screen. In the second line, we generate a list of moves using the available_moves function. We call the make_move function from the player class to let the player choose a move and store it in p1_action variable. In the next line, we update the state of the game by updating the board. Next, we check if the game is over and we have a winner. If we have a winner or it’s a draw — we print out the result, reset the game, and break the loop. Else, we continue and it’s player 2’s turn. In the else block we repeat a bunch of code but now for player 2’s gameplay. Finally, we ask the user if they want to play again. If the reply is a “yes” (y/Y) we call the game loop again.</p><p>Next, we implement the methods as they appear in the game loop.</p><h4>Print the Board</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*RhZ42ftB5vQOJdEs5jpZOg.png" /><figcaption>Showing the board</figcaption></figure><p>As with the turnvariable, a value of 0 in the board indicates an empty space, a value of 1 indicates that it is player 1’s square, and a value of -1 indicates that it is player 2’s square. We assign the default symbols — X for player 1 and O for player 2. The top and bottom print buttons print the top and bottom ends of the board. The other print statement prints the middle part (rows) of the board. If the value is 1 it prints an ‘X’, if it is -1it prints an ‘O’ and if it is 0 it prints an empty space.</p><h4>Legal Moves</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*mCkfEgGlN4Tu7VaRg_hq3Q.png" /><figcaption>Calculating available moves</figcaption></figure><p>The available_moves function iterates over the board and appends positions if they have the value 0 (are empty). It is a very basic and easy function (should’ve started with this to make things look easier! 😃).</p><h4>Update the Board</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*2nIyz78T8BZPY_W-UEVSTg.png" /><figcaption>Updating the board</figcaption></figure><p>Ah, I think this is the easiest now. The motto of the update_board function is simple, just add the symbol of the player to the board and change the symbol to that of the other player. As the symbols for the players are 1 and -1, we can easily do this by just multiplying -1 to the value of self.turn .</p><h4>Check for Win</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcfscbxGXouE2qKf9b1Gsw.png" /><figcaption>Check who won</figcaption></figure><p>The check_winfunction checks if any one of the players has won. Players can win when either a row, a column, or one of the diagonals has the same sign. As we are using 1, 0, and -1 for values in the board, we can simply check for the sum of rows, diagonals, or columns to check whether a player has won. If the sum is 3, player 1 won; if the sum is -3, player 2 won.</p><p>The first block of code checks whether one of the rows has a value of 3 or -3 and returns the sign of the winner (remember that the player in self.turn has changed, thus, we need to multiply it by -1 again). The second block is similar and does the same for the column values.</p><p>For calculating the values of the diagonals we make use of some functions from numpy to make things easier. The trace() function gives the sum of values on the main diagonal, so that gives us the value for the first diagonal. To calculate the value for the other diagonal, we have to flip the matrix horizontally and then take the trace. The flipping is done by fliplr() and then we again take the trace.</p><p>Finally, if no one has won, and we have no available moves, the game is a draw and the function returns 0.</p><h4>Reset the Game</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JuLqNqSsTDq7iMEFNVZKGw.png" /><figcaption>Resetting the values</figcaption></figure><p>Lastly, we reset the game when there is a win or tie. Resetting includes:</p><ol><li>setting the board to zeroes</li><li>setting the variable gameover to False</li><li>setting the turn to player 1 (1)</li></ol><h3>Hooray!</h3><p>We finally have a working code for the game. Let’s start playing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*GCUaI1qeXSHMEwhA4Y6kSA.jpeg" /><figcaption>The greatest game!</figcaption></figure><p>Want to know how it ends? Tune in for the next article next week!</p><h3>Before you go…</h3><p><strong>Connect with me on </strong><a href="https://www.instagram.com/om_arpit/"><strong>Instagram</strong></a><strong> and </strong><a href="https://www.facebook.com/ompuri55555"><strong>Facebook</strong></a><strong>.</strong><br><em>If you liked this story, hit the clap button (you can clap up to 50 times with just one button!) and follow me for more such articles!</em></p><blockquote><em>Share, recommend, and comment away! Engagement helps us communicate and be more human!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72dd59c5f240" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/building-a-game-of-tic-tac-toe-in-python-72dd59c5f240">Building a game of Tic-Tac-Toe in Python</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RegEx in Python]]></title>
            <link>https://medium.com/byte-sized-code/regex-in-python-a5e9ea52ec87?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/a5e9ea52ec87</guid>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[regular-expressions]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Sat, 18 Jul 2020 10:12:01 GMT</pubDate>
            <atom:updated>2020-07-18T10:12:01.663Z</atom:updated>
            <content:encoded><![CDATA[<p>You may be familiar with searching for text using ctrl + F and entering the words you are looking for. Regular Expressions (RegEx in short) go a step further and allow you to match patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*yzbe6idxiHOGtMxA.png" /><figcaption>Regular Expressions</figcaption></figure><h3>What is RegEx?</h3><p>A <strong>regular expression (or RE or RegEx)</strong> specifies a set of strings that matches it; <em>the functions in this [python] module let you check if a particular string matches a given regular expression</em>.</p><p>Patterns are present everywhere, email ids have a specific pattern — username@site.com, phone numbers (Indian numbers start with +91 in general), social media hashtags begin with #and_contain_no_more_spaces, and many more such examples can be cited from our everyday lives. <em>Regular expressions help us match these general patterns without knowing specifically what we are looking for</em>. For example, you can use RegEx to search for an email pattern on this page, and end up getting the above generic example.</p><blockquote>Knowing [RegEx] can mean the difference between solving a problem in three steps and solving it in 3,000 steps. When you’re a nerd, you forget that the problems you solve with a couple keystrokes can take other people days of tedious, error-prone work to slog through.</blockquote><blockquote>— Cory Doctorow</blockquote><p>Cory goes on to argue that one should first learn regular expressions before learning how to program. It is absolutely necessary for your day to day tasks.</p><h3>Matching Simple Patterns</h3><p>The simplest form of pattern matching is matching characters. Let’s start by looking at that.</p><h4>Matching Characters</h4><p>Most characters and numbers match themselves when used directly. For example, the string text will exactly match text in the given paragraph or page. We can also use a case-insensitive mode which will match text with text, Text, TEXT, tEXt, and so on (more on case-insensitivity later).</p><p>However, there are certain characters (called <strong>metacharacters</strong>) that do not match themselves and signal some out-of-the-ordinary pattern matching. Here is a list of metacharacters that are used in pattern matching in python: [ ] $ ^ . * + ? { } \ ( ) | .</p><h4>Group of Characters</h4><p>The first metacharacters that we’ll discuss are [ and ] . They are used for specifying a character class, which is a set of characters that will be matched. For example, [abc] will match a, b, or c. This is the same as [a-c], which uses a range to express the same characters.</p><p><strong><em>Metacharacters are not active inside classes</em></strong>. For example, [a-c$] will match a, b, c, and $. Although $ is a metacharacter, it acts as a simple character inside the square brackets.</p><p><em>The caret ( </em><em>^ ) is used to “complement” a character set</em>. This is indicated by using the caret as the first letter inside the character class. The string [^a-c] will match any character that is <strong>not </strong>a, b, or c.<strong> NOTE: </strong>^ outside the character class is a simple character and will match ^. Quite opposite to other metacharacters.</p><p>The all-powerful (and at times very difficult to use) metacharacter is .. It is used to match <strong>any character</strong> <strong><em>except the newline character</em></strong>.</p><h4>The Backslash</h4><p>Perhaps the most extensively used metacharacter is the backslash. The backslash ( \ ) can be followed by various characters to signal the various special sequences. It is frequently used to escape metacharacters (match metacharacters). For example, \[ is used to match [. Preceding characters with \ removes their special meaning. Also, \\ is used to match a\.</p><p>There are certain predefined character sets that can be matched by using the backslash. The following character sets can be matched by using backslash:</p><ul><li>\d — Matches any digit in the given text. It is the same as the character class [0-9].</li><li>\D — Matches any non-digit character. It is same as the character class [^0-9].</li><li>\s — Matches any whitespace character. It is the same as the character class [\t\v\n\r\f].</li><li>\S — Matches any non-whitespace character. It is the same as the character class [^\t\v\n\r\f].</li><li>\w —Matches any alphanumeric character. It is the same as the character class [a-zA-Z0-9_].</li><li>\W — Matches any non-alphanumeric character. It is the same as the character class [^a-zA-Z0-9_].</li></ul><p>These predefined classes can be used inside other character classes too. For example, [\s\w] matches alphanumeric characters and spaces.</p><h4>Repetition</h4><p>A very useful capability of RegEx is that it can be used to specify if some portions of the string we want to match are to be repeated a certain number of times.</p><p>The metacharacters { and } are used to specify repetitions. The curly brackets are used in the following way. {m,n} <em>means that there must be at least </em><em>m repetitions of the previous character and at most </em><em>n repetitions</em>. For example, the expression ab{2,3}c will match abbc and abbbc, but not abc (1 b) or abbbbc (4 repetitions of b). Three other metacharacters ( ?, +, *) are basically shortcuts that can be used in place of the long curly bracket syntax.</p><p>The <strong>question mark</strong> character matches either <strong>one or two repetitions</strong>. You can think of it as marking something as optional. For example, cat-?call will match both catcall and cat-call. It is the same as cat-{0,1}call.</p><p>The <strong>addition symbol</strong> matches <strong>one or more repetitions</strong>. For example, ab+c would match abc, abbc, abbbc, and so on (one or more repetitions of b). But it won’t match ac. The <strong>asterisk symbol</strong> is used to match <strong>zero or more</strong> <strong>occurrences</strong>, thus, ab*c will match all that ab+c matches and also ac.</p><p>That was all the raw material we needed to use RegEx in python. Now let’s learn how to actually use RE in python.</p><h3>Using Regular Expressions</h3><p>For using RE in python, we use the re module. Thus, we need to import re in all of our scripts where we want to use regular expressions.</p><h4>Compiling RE</h4><p>Regular expressions are compiled into pattern objects, which have methods for various tasks such as matching, searching, and replacing patterns. Here is a sample use case of re.</p><pre><strong>&gt;&gt;&gt;</strong> import re<br><strong>&gt;&gt;&gt; </strong>p = re.compile(&#39;ab*&#39;)<br><strong>&gt;&gt;&gt; </strong>p.pattern<br>&#39;ab*&#39;</pre><p>Earlier we stated that we can use <strong>case-insensitivity</strong> to match different cases of text. The case-insensitive behavior can be triggered by using the IGNORECASE flag in re.compile(). The same is illustrated below:</p><pre><strong>&gt;&gt;&gt; </strong>p = re.compile(&#39;ab*&#39;, re.IGNORECASE)</pre><h4>Escaping Backslash</h4><p>As mentioned earlier, one can use a backslash to escape metacharacters, but it leads to a problem of inflating backslashes. For example, if you want to match the text \text in your page, you need to escape the backslash before “text” using another backslash. Then you need to escape the second backslash by using another backslash. Thus, to match \text, you need to compile the string \\\\text. <strong><em>In short, to match one literal backslash ( </em></strong><em>\ </em><strong><em>), you need to type in four backslashes ( </em></strong><em>\\\\</em><strong><em> )</em></strong>. This makes the code pretty confusing to look at, especially if you want to match URLs.</p><p>The simple solution is using raw string notation. <em>By appending a </em><em>r in front of a given string, it instructs python to treat it as a raw string literal, </em><strong><em>where backslashes have no special meaning</em></strong>. The following code will illustrate the difference:</p><pre><strong>&gt;&gt;&gt;</strong> a = re.compile(r&#39;\\text&#39;)<br><strong>&gt;&gt;&gt;</strong> a.pattern<br>&#39;\\\\text&#39;<br><strong>&gt;&gt;&gt;</strong> a = re.compile(&#39;\\\\text&#39;)<br><strong>&gt;&gt;&gt;</strong> a.pattern<br>&#39;\\\\text&#39;</pre><p>The same pattern is achieved by using far fewer backslashes when dealing with a raw string literal.</p><h4>Pattern Matching</h4><p>Now that we have compiled and made a pattern object, what next? We can use the following methods on the pattern object:</p><ul><li>match() — Determines if the expression matches at the beginning of the string.</li><li>search() — Scans a string to check if the expression matches any substring of the given string.</li><li>findall() — Finds all substrings where the pattern matches and returns a list containing the matches.</li><li>finditer() — Finds all substrings where the pattern matches and returns them as an <em>iterable</em>.</li></ul><p>The following code block has examples of pattern matching using all the different methods of a pre-compiled match object.</p><p>Here’s an example of using match() for a RE.</p><pre><strong>&gt;&gt;&gt; </strong>import re<br><strong>&gt;&gt;&gt; </strong>p = re.compile(&#39;[a-z]+&#39;)</pre><pre><strong>&gt;&gt;&gt; </strong>p.match(&quot;&quot;)<br><strong>&gt;&gt;&gt; </strong>print(p.match(&quot;&quot;))<br>None</pre><pre><strong>&gt;&gt;&gt;</strong> m = p.match(&#39;tempo&#39;)<br><strong>&gt;&gt;&gt;</strong> m<br>&lt;_sre.SRE_Match object at 0x7fd35a818f10&gt;</pre><pre><strong>&gt;&gt;&gt;</strong> n = p.search(&#39;.*tempo&#39;)<br><strong>&gt;&gt;&gt;</strong> n<br>&lt;_sre.SRE_Match object at 0x7fd35a818f80&gt;</pre><pre><strong>&gt;&gt;&gt;</strong> r = p.findall(&#39;tempo.*tempo&#39;)<br><strong>&gt;&gt;&gt;</strong> r<br>[&#39;tempo&#39;, &#39;tempo&#39;]</pre><pre><strong>&gt;&gt;&gt;</strong> s = p.finditer(&#39;tempo.*tempo&#39;)<br><strong>&gt;&gt;&gt;</strong> s<br>&lt;callable-iterator object at 0x7fd35a7c8550&gt;</pre><p>As you can see, the findall method returns a simple list containing all the matches in the text. The finditer method returns an iterable object that can be iterated over by using a simple for loop:</p><pre><strong>&gt;&gt;&gt;</strong> for i in s:<br><strong>...</strong>   print(i)<br><strong>...</strong><br>&lt;_sre.SRE_Match object at 0x7fd35a7cc030&gt;<br>&lt;_sre.SRE_Match object at 0x7fd35a7cc0a0&gt;</pre><p>One can note that the individual entities in finditer and the results of search and match methods are <strong>match objects</strong>. The natural question here: <em>What is a match object and what can we do with them?</em></p><h4>Match Objects</h4><p>Match objects returned by re have four basic and important methods:</p><ul><li>group() — returns the string matched by the regular expression.</li><li>start() — returns the index of the starting position of the match.</li><li>end() — returns the ending position of the match.</li><li>span() — returns a tuple containing the (starting, ending) positions of the match.</li></ul><p>Here is what the methods return when called upon our match object ‘m’:</p><pre><strong>&gt;&gt;&gt;</strong> m.group()<br>&#39;tempo&#39;<br><strong>&gt;&gt;&gt;</strong> m.end()<br>5<br><strong>&gt;&gt;&gt;</strong> m.start()<br>0<br><strong>&gt;&gt;&gt;</strong> m.span()<br>(0, 5)</pre><h3>An Example</h3><p>Untill now we learnt the meaning of RE and basic methods that are present in the re library of python. Let’s use this feature to try extracting a given date from a given piece of text:</p><pre><strong>&gt;&gt;&gt; </strong>import re<strong><br>&gt;&gt;&gt;</strong> dateRegex = re.compile(&#39;\d\d-\d\d-\d\d\d\d&#39;)<br><strong>&gt;&gt;&gt;</strong> para = &quot;The date today is 18-07-2020. It&#39;s already July!&quot;<br><strong>&gt;&gt;&gt;</strong> date = dateRegex.search(para)<br><strong>&gt;&gt;&gt;</strong> date.group()<br>&#39;18-07-2020&#39;<br><strong>&gt;&gt;&gt;</strong> date.span()<br>(18, 28)<br><strong>&gt;&gt;&gt;</strong> para[18:28]<br>&#39;18-07-2020&#39;</pre><p>The above code first creates a compiled regex object that recognizes dates. Then it searches for a “date” in a given paragraph. As you can see, we can easily extract information about the location of the match via the <strong>span</strong> method and directly access the matching substring from the paragraph.</p><h3>Conclusion</h3><p>Although not a pre-requisite for learning basic programming, <strong><em>people are generally encouraged to learn about regular expressions sometime or later.</em></strong> It does help in shortening your code a lot if you work in the field of <strong>data science or specifically data mining</strong>. This articles serves as a basic introduction to regular expressions and a later article will enlighten you with the best practices of regular expressions and also fill in some gaps in knowledge (mostly about some left out metacharacters and flags).</p><h3>Before You Go…</h3><p>If you liked the article, <strong><em>give a clap</em></strong> (it’s free, and you can clap up to 50 times!), share, recommend, and respond to it. <strong><em>Your claps, shares, and responses encourage me to write more such articles.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5e9ea52ec87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/regex-in-python-a5e9ea52ec87">RegEx in Python</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asterisks in Python]]></title>
            <link>https://medium.com/byte-sized-code/asterisks-in-python-b46a3c7cfdf8?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/b46a3c7cfdf8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[pep]]></category>
            <category><![CDATA[asterisk]]></category>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 11:55:20 GMT</pubDate>
            <atom:updated>2020-06-20T11:56:08.990Z</atom:updated>
            <content:encoded><![CDATA[<p>What They Are and How to Use Them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*v1TY6tZvlr1j4B6z.jpeg" /></figure><p>Most of us have encountered code like this (and some of us will be seeing it for their first time):</p><pre><strong>&gt;&gt;&gt;</strong> numbers <strong>=</strong> [2, 1, 3, 4, 7] <br><strong>&gt;&gt;&gt;</strong> more_numbers <strong>=</strong> [<strong>*</strong>numbers, 11, 18] <br><strong>&gt;&gt;&gt;</strong> print(<strong>*</strong>more_numbers, sep<strong>=</strong>&#39;, &#39;) <br>2, 1, 3, 4, 7, 11, 18</pre><p>The first time I looked at it, I was quite puzzled. Isn’t asterisk (*) supposed to be the operator for multiplication? After some reading, I found out that * and **, when used before a variable, are known as <strong>prefix operators</strong>. They are also the representations of the <strong>infix operators</strong> for <em>multiplication (*) and exponentiation (**)</em>, but we won’t be looking into that today.</p><h3>So What Are We Looking into Today?</h3><p>We look exclusively into the prefix behavior of the operators, i.e., the * and ** operators that are used before a variable, as seen above. Two examples of usage of * are shown in the code above. <br>Asterisks can be used for the following purposes:</p><ul><li>Using * and ** to pass arguments to a function</li><li>Using * and ** to capture arguments passed into a function</li><li>Using * to accept keyword-only arguments</li><li>Using * to capture items during tuple unpacking</li><li>Using * to unpack iterables into a list/tuple</li><li>Using ** to unpack dictionaries into other dictionaries</li></ul><p>Even for the veterans (especially people who have recently migrated from Python 2 to 3), there are things to learn as <strong><em>Python has added new capabilities for these functions</em></strong>. Thus, I request everyone to go through the code blocks at least once to make sure you know the stuff.</p><h3>Unpacking into a Function Call</h3><p>When using a function call, we can use an asterisk (*) to unpack an iterable into the function call. For example:</p><pre>&gt;&gt;&gt; numbers = [1,2,3,12,4414,1,2]<br>&gt;&gt;&gt; print(*numbers)<br>1 2 3 12 4414 1 2</pre><p>The asterisk in the <em>print</em> function passes all the elements of the <em>numbers</em> list to the <em>print</em> function without us ever needing to know how many elements are present in the list. Quite useful when taking in user input as an iterable.</p><p>Here’s another useful (and a bit complicated) example:</p><pre>&gt;&gt;&gt; def transpose(matrix):<br>...   return [list(row) for row in zip(*matrix)]<br>...<br>&gt;&gt;&gt; transpose([[1,2,3],[4,5,6],[7,8,9]])<br>[[1, 4, 7], [2, 5, 8], [3, 6, 9]]</pre><p>The transpose function is first zipping all the rows (effectively turning them into column tuples) in the original matrix and then printing out their contents as a list of lists (matrix).</p><p>The ** operator does something similar, but with key-value pairs. It can be used to unpack a dictionary into a function call. Here’s an example:</p><pre>&gt;&gt;&gt; date_info <strong>=</strong> {&#39;year&#39;: &quot;2019&quot;, &#39;month&#39;: &quot;01&quot;, &#39;day&#39;: &quot;31&quot;} <br>&gt;&gt;&gt; filename <strong>=</strong> &quot;{year}-{month}-{day}.txt&quot;<strong>.</strong>format(<strong>**</strong>date_info) <br>&gt;&gt;&gt; filename <br>&#39;2019-01-31.txt&#39;</pre><p>As of Python 3.8, both * and ** can be used multiple times in a single function call:</p><pre>&gt;&gt;&gt; fruits <strong>=</strong> [&#39;lemon&#39;, &#39;pear&#39;, &#39;watermelon&#39;, &#39;tomato&#39;] <br>&gt;&gt;&gt; numbers <strong>=</strong> [2, 1, 3, 4, 7] <br>&gt;&gt;&gt; print(<strong>*</strong>numbers, <strong>*</strong>fruits) <br>2 1 3 4 7 lemon pear watermelon tomato</pre><pre>&gt;&gt;&gt; date_info <strong>=</strong> {&#39;year&#39;: &quot;2020&quot;, &#39;month&#39;: &quot;01&quot;, &#39;day&#39;: &quot;01&quot;}<br>&gt;&gt;&gt; track_info <strong>=</strong> {&#39;artist&#39;: &quot;Beethoven&quot;, &#39;title&#39;: &#39;Symphony No 5&#39;}<br>&gt;&gt;&gt; filename <strong>=</strong> &quot;{year}-{month}-{day}-{artist}-{title}.txt&quot;<strong>.</strong>format(<br>...     <strong>**</strong>date_info,<br>...     <strong>**</strong>track_info,)<br>...<br>&gt;&gt;&gt; filename<br>&#39;2020-01-01-Beethoven-Symphony No 5.txt&#39;</pre><blockquote>You need to be careful while using ** multiple times though, the different dictionaries should never have a matching key in them, as keywords for function calls are unique and repeats are not allowed.</blockquote><h3>Packing Arguments given to a Function</h3><p>The * operator can be used to capture an <strong>unlimited</strong> number of positional arguments given to a function. These arguments are captured into a tuple.</p><pre>&gt;&gt;&gt; def make_list(*items):<br>...   return [item for item in items]</pre><p>The function will take any number of positional arguments and convert them all into a single list:</p><pre>&gt;&gt;&gt; make_list(1,23,4,12,4,1,5,1)<br>[1, 23, 4, 12, 4, 1, 5, 1]</pre><p>Similarly, we can use the ** operator to capture any keyword arguments that are passed onto a given function.</p><pre>&gt;&gt;&gt; def tag(tag_name, **attributes):<br>...   attribute_list = [f&#39;{name}=&quot;{value}&quot;&#39; for name, value in attributes.items()]<br>...   return f&quot;&lt;{tag_name} {&#39; &#39;.join(attribute_list)}&gt;&quot;<br>...</pre><p>The function above will capture the tag name and any number of attributes that you throw at it and then convert it into a well-formatted HTML tag. Here’s an example usage:</p><pre>&gt;&gt;&gt; tag(&#39;a&#39;, href=&quot;<a href="https://aceking007.github.io/">https://aceking007.github.io</a>&quot;)<br>&#39;&lt;a href=&quot;<a href="https://aceking007.github.io/">https://aceking007.github.io</a>&quot;&gt;&#39;</pre><h3>Types of Function Arguments</h3><p>Arguments with names are called <strong>keyword</strong> arguments, and the other arguments are called <strong>positional</strong> arguments. Let’s first understand the difference between keyword and positional arguments. This part is a <strong>short detour</strong> before going into the primary use of asterisks. <em>Feel free to skip</em> <em>this if you are already familiar with this.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*Ee19NzTv_CeFQ1oW" /><figcaption>The other kinds of Arguments</figcaption></figure><h4>Positional Arguments</h4><p>Positional arguments are arguments passed onto a function that needs to be included in the<strong><em> proper position or order</em></strong>. I.e., the first positional argument must be provided first, followed by the second positional argument, and so on.</p><p>An example can be seen in Python’s <em>complex</em> function. The order in which you provide the numbers determines if they are real or imaginary parts. The real part needs to be provided as the first argument, followed by the imaginary part. For example,</p><pre>&gt;&gt;&gt; complex(1,2)<br>(1+2j)<br>&gt;&gt;&gt; complex(2,1)<br>(2+1j)</pre><p>Here, the relative positions of the arguments determine what the output will be, and thus, they are called positional arguments.</p><h4>Keyword Arguments</h4><p>A keyword argument is provided as a <strong>key-value</strong> pair separated by an <strong><em>equals (=)</em></strong> sign. The general form of such arguments is function(keyword=value) .</p><p>Python’s complex function can also accept two keyword arguments, called <em>real</em> and <em>imag. </em>Keyword arguments are provided to functions after any required positional arguments. But the order of keyword arguments is not taken does not matter. Note this in the example:</p><pre>&gt;&gt;&gt; complex(real=3, imag=5)<br>(3+5j)<br>&gt;&gt;&gt; complex(imag=5, real=3)<br>(3+5j)</pre><p>Both the orders produce the same number. Now that we are clear about keyword and positional arguments let’s move on to the main topic.</p><h3>Keyword-Only Arguments</h3><p>Keyword-Only arguments are arguments that can only be specified by using keywords (they can’t be positionally specified). As we saw above, we can define the arguments <em>real</em> and <em>imag</em> of the <em>complex</em> function both by using keywords and also positionally.</p><p>However, in 2006, via <a href="https://www.python.org/dev/peps/pep-3102/">PEP 3102</a>, Python introduced functions that can be defined to take Keyword-Only arguments. There is a special syntax for defining such functions as discussed below.</p><h4>Keyword-Only Arguments With Positional Arguments</h4><p>Arguments defined after the * in a function will behave as <strong>keyword-only arguments</strong>. We can often have a combination of positional and keyword-only arguments in functions that we create. For example:</p><pre>&gt;&gt;&gt; def pos_kw(name, *items, val, truth=False):<br>...   print(name)<br>...   print(items)<br>...   print(val)<br>...   print(truth)<br>...<br>&gt;&gt;&gt; pos_kw(&#39;good&#39;, 1,2,3,4,1,2, val=78, truth=True)<br>good<br>(1, 2, 3, 4, 1, 2)<br>78<br>True</pre><p>The last two arguments defined (<em>val</em> and <em>truth</em>) are keyword-only as they are defined after the asterisk (*) argument. They can not be assigned positionally. Trying to input the value 78 positionally for <em>val </em>will produce the following error:</p><pre>&gt;&gt;&gt; pos_kw(&#39;good&#39;, 1,2,3,4,1,2, 78)<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>TypeError: pos_kw() missing 1 required keyword-only argument: &#39;val&#39;</pre><p>Thus, we can use the above template to create functions that take in positional as well as keyword-only arguments.</p><h4>Keyword-Only Arguments Without Positional Arguments</h4><p>Similarly, we can use just the asterisk in the beginning to create functions that do not take any positional or keyword arguments but take only keyword-only arguments.</p><pre>&gt;&gt;&gt; def sample(*, name):<br>...   print(name)<br>...<br>&gt;&gt;&gt; sample(name=&#39;Arpit&#39;)<br>Arpit</pre><p>If we try to just pass on any argument without the keyword, it will result in an error.</p><pre>&gt;&gt;&gt; sample(&#39;Arpit&#39;)<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>TypeError: sample() takes 0 positional arguments but 1 was given</pre><p>An excellent example of this is Python’s built-in sorted function. If you use help on <em>sorted</em> you can see this:</p><pre>&gt;&gt;&gt; help(sorted)<br>Help on built-in function sorted in module builtins:</pre><pre>sorted(iterable, /, *, key=None, reverse=False)<br>    Return a new list containing all items from the iterable in ascending order.</pre><pre>A custom key function can be supplied to customize the sort order, and the<br>    reverse flag can be set to request the result in descending order.</pre><p>The arguments <em>key </em>and <em>reverse</em> are keyword-only arguments used in the function that can’t be passed on without a keyword.</p><h3>Unpacking Tuples using Asterisks</h3><p>Python 3 added this functionality, and it allows us to unpack the contents of a tuple into variables using the * operator.</p><pre>&gt;&gt;&gt; fruits <strong>=</strong> [&#39;lemon&#39;, &#39;pear&#39;, &#39;watermelon&#39;, &#39;tomato&#39;] <br>&gt;&gt;&gt; first, second, <strong>*</strong>remaining <strong>=</strong> fruits <br>&gt;&gt;&gt; remaining <br>[&#39;watermelon&#39;, &#39;tomato&#39;] <br>&gt;&gt;&gt; first, <strong>*</strong>remaining <strong>=</strong> fruits <br>&gt;&gt;&gt; remaining <br>[&#39;pear&#39;, &#39;watermelon&#39;, &#39;tomato&#39;] <br>&gt;&gt;&gt; first, <strong>*</strong>middle, last <strong>=</strong> fruits <br>&gt;&gt;&gt; middle <br>[&#39;pear&#39;, &#39;watermelon&#39;]</pre><p>It is also possible to use multiple asterisks by nested tuple unpacking, as shown below:</p><pre>&gt;&gt;&gt; fruits <strong>=</strong> [&#39;lemon&#39;, &#39;pear&#39;, &#39;watermelon&#39;, &#39;tomato&#39;]<br>&gt;&gt;&gt; ((first_letter, <strong>*</strong>remaining), <strong>*</strong>other_fruits) <strong>=</strong> fruits<br>&gt;&gt;&gt; remaining<br>[&#39;e&#39;, &#39;m&#39;, &#39;o&#39;, &#39;n&#39;]<br>&gt;&gt;&gt; other_fruits<br>[&#39;pear&#39;, &#39;watermelon&#39;, &#39;tomato&#39;]</pre><p>Check out this <a href="https://www.python.org/dev/peps/pep-3132/">PEP</a> for more information. It’s a short one and gives you an idea of where you can use it to better your code.</p><h3>Asterisks in List Literals</h3><p>Python 3.5 marks the addition of many features to the asterisk operators through the <a href="https://www.python.org/dev/peps/pep-0448/">PEP448</a>. Probably one of the most prominent new features is the ability to use * to dump an iterable into a new list.</p><p>Say you have the given function:</p><pre>&gt;&gt;&gt; def palindromify(text):<br>...   return list(text) + list(text[::-1])<br>...<br>&gt;&gt;&gt; palindromify(&#39;name&#39;)<br>[&#39;n&#39;, &#39;a&#39;, &#39;m&#39;, &#39;e&#39;, &#39;e&#39;, &#39;m&#39;, &#39;a&#39;, &#39;n&#39;]</pre><p>It can be quite easily modified to:</p><pre>&gt;&gt;&gt; def palindromify(text):<br>...   return [*text , *text[::-1]]<br>...<br>&gt;&gt;&gt; palindromify(&#39;name&#39;)<br>[&#39;n&#39;, &#39;a&#39;, &#39;m&#39;, &#39;e&#39;, &#39;e&#39;, &#39;m&#39;, &#39;a&#39;, &#39;n&#39;]</pre><p>which is more <strong>readable and efficient</strong> (compared to the two calls to <em>list</em>). The important thing is this method is not limited to creating lists. We can similarly use the * operator to create tuples and sets. Here is an example:</p><pre>&gt;&gt;&gt; fruits <strong>=</strong> [&#39;lemon&#39;, &#39;pear&#39;, &#39;watermelon&#39;, &#39;tomato&#39;] <br>&gt;&gt;&gt; (<strong>*</strong>fruits[1:], fruits[0]) <br>(&#39;pear&#39;, &#39;watermelon&#39;, &#39;tomato&#39;, &#39;lemon&#39;) <br>&gt;&gt;&gt; uppercase_fruits <strong>=</strong> (f<strong>.</strong>upper() for f <strong>in</strong> fruits) <br>&gt;&gt;&gt; {<strong>*</strong>fruits, <strong>*</strong>uppercase_fruits} <br>{&#39;lemon&#39;, &#39;watermelon&#39;, &#39;TOMATO&#39;, &#39;LEMON&#39;, &#39;PEAR&#39;, &#39;WATERMELON&#39;, &#39;tomato&#39;, &#39;pear&#39;}</pre><p>Note: It wasn’t that easy to accomplish the last thing we did in a single line. However, one had to depend on this obscure method that I found out some time ago:</p><pre>&gt;&gt;&gt; set()<strong>.</strong>union(fruits, uppercase_fruits)<br>{&#39;lemon&#39;, &#39;watermelon&#39;, &#39;TOMATO&#39;, &#39;LEMON&#39;, &#39;PEAR&#39;, &#39;WATERMELON&#39;, &#39;tomato&#39;, &#39;pear&#39;}</pre><h3>Asterisks in Dictionary Literals</h3><p>Similar to what * does for lists or tuples, ** does the same for dictionaries. The same PEP448 introduced a better and shorter way of dumping key-value pairs from dictionaries in Python using **.</p><pre>&gt;&gt;&gt; date_info <strong>=</strong> {&#39;year&#39;: &quot;2020&quot;, &#39;month&#39;: &quot;01&quot;, &#39;day&#39;: &quot;01&quot;} <br>&gt;&gt;&gt; track_info <strong>=</strong> {&#39;artist&#39;: &quot;Beethoven&quot;, &#39;title&#39;: &#39;Symphony No 5&#39;}<br>&gt;&gt;&gt; all_info <strong>=</strong> {<strong>**</strong>date_info, <strong>**</strong>track_info} <br>&gt;&gt;&gt; all_info <br>{&#39;year&#39;: &#39;2020&#39;, &#39;month&#39;: &#39;01&#39;, &#39;day&#39;: &#39;01&#39;, &#39;artist&#39;: &#39;Beethoven&#39;, &#39;title&#39;: &#39;Symphony No 5&#39;}</pre><p>Using ** also allows us to add/update values while we copy a dictionary. For example:</p><pre>&gt;&gt;&gt; date_info <strong>=</strong> {&#39;year&#39;: &#39;2020&#39;, &#39;month&#39;: &#39;01&#39;, &#39;day&#39;: &#39;7&#39;} <br>&gt;&gt;&gt; event_info <strong>=</strong> {<strong>**</strong>date_info, &#39;group&#39;: &quot;Python Meetup&quot;, &#39;day&#39;: 14} <br>&gt;&gt;&gt; event_info <br>{&#39;year&#39;: &#39;2020&#39;, &#39;month&#39;: &#39;01&#39;, &#39;day&#39;: &#39;14&#39;, &#39;group&#39;: &#39;Python Meetup&#39;}</pre><h3>Conclusion</h3><p>Python’s * and ** aren’t just <em>syntactic sugar</em> used by fancy people. Some things that they do can be achieved by other means, but the alternatives generally tend to be cumbersome and resource inefficient. Whereas, there are some things (Keyword-Only arguments, passing unlimited arguments to functions) that <strong>can not be achieved by other means</strong>.</p><p>If you are new to Python or are concerned about how to remember all these uses, don’t be! These operators have different applications and you aren’t required to memorize all of them. Getting a feel for when you might be using one of them is generally enough. You can always use this article as a <strong>cheat sheet</strong> and refer back as many times as you like.</p><h4>Before You Go…</h4><p>If you liked the article, <strong><em>give a clap</em></strong> (it’s free, and you can clap up to 50 times!), share, recommend, and respond to it. <strong><em>Your claps, shares, and responses encourage me to write more such articles.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46a3c7cfdf8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/asterisks-in-python-b46a3c7cfdf8">Asterisks in Python</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating windows apps using python]]></title>
            <link>https://medium.com/byte-sized-code/creating-windows-apps-using-python-f9db819e5f5?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/f9db819e5f5</guid>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 17:15:03 GMT</pubDate>
            <atom:updated>2020-02-04T12:45:05.091Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I made my very own version of the snake game using pygame. I was so excited about it and wanted to share it with the world. A few of my friends know how to code, and they generally use python, so they had python installed on their PCs, I just sent the code to them, and they executed it without any problems. It felt nice seeing how amazed and excited they were too. But sadly, some of my friends’ don’t code. Thus, I was unable to share the game with them. It made me feel a bit bad for them, but then I read up about how to convert python code to an executable file (.exe) that can be run straight from windows and voila!</p><p>I experimented a bit, so I tried pyinstaller, cx_freeze, and another program called auto-py-to-exe. I found the last one handy, it uses pyinstaller, but it has a friendly interface. As this post is aimed towards the general public, it is appropriate that I talk about auto-py-to-exe.</p><p>First, we need to install auto-py-to-exe. There are several ways to do that, but I prefer pip, so open up your command prompt (windows) or bash shell (Linux) and type pip install auto-py-to-exe. Then we wait till it is downloaded and installed. Next, type in auto-py-to-exe in the command prompt as shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*1J0kpWHN97XccO0vbI86Rg.jpeg" /><figcaption>Command to open auto-py-to-exe</figcaption></figure><p>The following window opens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*UYoacvJBMJCKCsEJV4gZRw.jpeg" /><figcaption>The auto-py-to-exe window</figcaption></figure><p>We select the path to the file where our python script is store. Next, we choose whether we want a directory as an output or a single file as an output. In my experience, it is easier to debug code from a folder, and it runs faster as compared to one file after conversion. The one file mode, however, produces just one file and thus is easily transferable or portable (generally, people have problems with one directory mode if they move some files out of the directory). If you want to deploy the app as a standard python script running in the command line, you select the ‘<em>Console based’</em> window option. Otherwise, you choose the<em> ‘Window-based’</em> window option, which displays the GUI. If you have a <em>.ico</em> file, you can use that to create an icon for your file.</p><p>In the advanced options, you can set the directory where the file is to be saved and any other relevant details (generally not required). In your python script, however, if you have some hidden imports, e.g., imports of the sort __import__ as opposed to import, then you have to include those package names under the hidden import option. Lastly, click on the blue button at the end of the application window and done!</p><p>Here is an example of all the options I used while making an executable of the snake game that I developed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*Qt6qXU--8jroBRHyUurA7g.jpeg" /></figure><p>So, I have provided the script location and the location of an icon file that I have. I have selected the <em>One Directory</em> and <em>Window Based</em> options and clicked on convert. After conversion, click on the <em>open output folder</em> option to see the output folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*GC3CsxfCYKhHImceBaJD7g.jpeg" /></figure><p>Here is the program in the directory along with all the dependencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*b8vQbUen2m0IqrrfKivspg.jpeg" /></figure><p>Now I can run the game and play:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*WibAQxAmD-HOr2iCb_c4Sw.jpeg" /><figcaption>Screenshot of the game</figcaption></figure><p>To read more about how auto-py-to-exe or pyinstaller works, have a look at the documentation <a href="https://pyinstaller.readthedocs.io/en/stable/operating-mode.html">here</a>. If you want to learn how to make your own snake game in python using pygame, go <a href="https://medium.com/@omarpit26/making-a-simple-snake-game-in-python-part-1-42eb2890f0eb?source=friends_link&amp;sk=9d01ab768c69f29485f36970d189564f">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9db819e5f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/creating-windows-apps-using-python-f9db819e5f5">Creating windows apps using python</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Game Development in Python (part 3)]]></title>
            <link>https://medium.com/byte-sized-code/introduction-to-game-development-in-python-part-3-1ea915e31e25?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/1ea915e31e25</guid>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Mon, 01 Jun 2020 15:55:10 GMT</pubDate>
            <atom:updated>2020-06-01T15:52:06.220Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/byte-sized-code/introduction-to-game-development-in-python-part-2-78c2fa2b9315">previous article</a>, we delved deeper into the objects and Surfaces in Pygame. We also learned how to draw some primitive graphics on the screen. In today’s post, we will make all of the drawings come alive!</p><h3><strong>Animation</strong></h3><p>Now that we know how to get the Pygame framework to draw on the screen, let’s learn how to make animated pictures. First, we need to know how the brain perceives animation. <em>When our brain “sees” an image, it lasts on our brain for some time.</em> This is called the <strong>persistence of vision</strong>. If our eyes are shown a number of images in succession, the brain perceives the images to be continuous. In short, if we show the eyes images that differ minorly in quick succession, it produces an <strong><em>illusion</em></strong> of motion. Here’s an example:</p><p>Suppose the window that we are showing currently is 6 pixels wide and 1 pixel tall. All the pixels are white except for a black pixel at (4,0). It would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/0*G2WKz-cS1i2_7vHp.jpg" /></figure><p>If you changed the window, so that the black spot is now present on (3,0) instead of (4,0), it would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/0*zBdg12FwE7WCdXoG.jpg" /></figure><p>To the user, it looks like the black pixel has “moved” to the left. We again redraw the window to have the black pixel at (2,0), it would continue to look like the black pixel is moving left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/0*goRoYLFS0TGkm1RD.jpg" /></figure><p>It may look like the black pixel is moving, but it is just an illusion. The computer is just showing three different images that each just happens to have one black pixel.</p><blockquote>The trick to making believable animations is to have your program draw a picture to the window, wait a fraction of a second, and then draw a slightly different picture.</blockquote><p>Here is an example program demonstration simple animation using a rectangle object is Pygame:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7ae8ab6be3d35b4f9e3dd06f2d7845f/href">https://medium.com/media/e7ae8ab6be3d35b4f9e3dd06f2d7845f/href</a></iframe><p>Some screenshots from the program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*P0xQ9c83oEY1x26iOVL48w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*UPK3zbpDCLmMJJjt_qVWDg.jpeg" /></figure><h3>Working with Images</h3><p>The last article was quite long. Thus, I decided to purposefully not include images in the tutorial. Images in Pygame are often called “<strong>sprites</strong>”. Pygame is able to load images onto Surface objects from <strong><em>PNG, JPG, GIF, and BMP</em></strong> image files.</p><p>Here is a code for a simple animation, using an image:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/493e22b2c5d274cbe348fac80cd43966/href">https://medium.com/media/493e22b2c5d274cbe348fac80cd43966/href</a></iframe><p>The image of the ball was stored in a file named <em>ball.jpg</em>. To load this file’s image, the string ‘<strong><em>ball.png</em></strong>’ is passed to the pygame.image.load() function. The pygame.image.load() function call will return a Surface object that has the image drawn on it. This Surface object will be a separate Surface object from the display Surface object, so we must <strong>blit </strong>(i.e., copy) the image’s Surface object to the display Surface object. <strong><em>Blitting</em></strong> is drawing the contents of one Surface onto another. It is done with the blit() Surface object method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*UgUvGWTyps6uuM4gXD_F4g.jpeg" /></figure><p>If you get an error message like pygame.error:Couldn&#39;t open ball.jpg when calling pygame.image.load(), then make sure the ‘<em>ball.png</em>’ file is in the same folder as the <em>image_animation.py</em> file before you run the program.</p><pre>DISPLAYSURF.blit(ballImg, (ballx, bally))</pre><p>The above line in the <em>image_animation.py</em> file uses the blit() method to copy <em>ballImg</em> to DISPLAYSURF. There are two parameters for blit(). The first is the source Surface object, which is what will be copied onto the <strong><em>DISPLAYSURF</em></strong> Surface object. The second parameter is a two-integer tuple for the X and Y values of the top-left corner where the image should be blitted to.</p><p>If <em>ballx</em> and <em>bally</em> were set to 100 and 200 and the width of <em>ballImg</em> was 125 and the height was 79, this blit() call would copy this image onto the <strong><em>DISPLAYSURF</em></strong> so that the top left corner of the <em>ballImg</em> was at the XY coordinate (100,200) and the bottom right corner’s XY coordinate was at (225, 279).</p><p><strong><em>Note: blitting is not allowed for Surfaces that are locked (e.g., when working with PixelArray objects).</em></strong></p><h3>Frames Per Second and ‘Clock’ objects</h3><p>The <strong>frame rate</strong> or <strong>refresh rate</strong> is the number of pictures that the program draws per second and is measured in FPS or frames per second. (Many monitors have a frame rate of <em>60 hertz or 60 frames per second</em>).</p><blockquote><strong><em>A low frame rate in video games can make the game look choppy or jumpy</em></strong>. If the program has too much code to run to draw to the screen frequently enough, then the FPS goes down.</blockquote><p>A pygame.time.Clock object can help us make sure our program runs at a certain maximum FPS. This Clock object will ensure that our game programs don’t run too fast by putting in small pauses on each iteration of the game loop. If we didn’t have these pauses, our game programs would run as fast as the computer can run it. This is often too fast for the player (typically for any human). A call to the tick() method of a Clock object in the game loop sets the FPS to a maximum value that is provided. In our program, we create the Clock object on the following line:</p><pre>fpsClock = pygame.time.Clock()</pre><p>The Clock object’s tick() method should be called at the very end of the game loop, after the call to pygame.display.update(). The length of the pause is calculated based on how long it has been since the previous call to the tick(), which would have taken place at the end of a previous iteration of the game loop. The first time the tick() method is called, it doesn’t pause at all. In the animation program, the tick() command is the last instruction on the game loop.</p><pre>fpsClock.tick(FPS)</pre><p><em>Try changing the FPS constant to different values to see the effect it has on the speed of the animation</em>. In the end, comment the above line and see how it affects the program.</p><h3>Text and Fonts</h3><p>How does the user know how well they are doing in the game? We require a display where we can write the <strong>score</strong> of the user. We also require to display text for certain other stuff like any names or menu options on the game. We can write several calls to the pygame.draw.line() to draw out the lines of each letter. This would be a headache to type out all those pygame.draw.line() calls and figure out all the XY coordinates, and probably wouldn’t look very good.</p><p>Pygame provides some much simpler functions for fonts and creating text. Here is a small Hello World program using Pygame’s font functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/811c0316956dc50ddcc19d3c05c0b075/href">https://medium.com/media/811c0316956dc50ddcc19d3c05c0b075/href</a></iframe><p>The screen looks something like this when you execute the program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*gxVsQupQePmPEo4LschQgQ.jpeg" /></figure><p>There are <strong><em>six steps</em></strong> to making text appear on the screen:</p><ul><li>Create a pygame.font.Font object (<em>Line 12</em>)</li><li>Create a Surface object with the text drawn on it by calling the Font object’s render() method (<em>Line 13</em>)</li><li>Create a Rect object from the Surface object by calling the Surface object’s get_rect() method. This Rect object will have the width and height correctly set for the text that was rendered, but the top and left attributes will be zero (<em>Line 14</em>).</li><li>Set the position of the Rect object by changing one of its attributes. On line <em>15</em>, we set the center of the Rect object to be at 200,150.</li><li>Blit the Surface object with the text onto the Surface object returned by pygame.display.set_mode() (<em>Line19</em>).</li><li>Call pygame.display.update() to make the display Surface appear on the screen (<em>Line 24</em>).</li></ul><p>The parameters to the pygame.font.Font() constructor is a string of the font file to use, and an integer of the size of the font (in points, like how word processors measure font size). On line 12, we pass ‘<em>freesansbold.ttf</em>’ (this is a font that comes with Pygame) and the integer 32 (<strong><em>for a 32-point sized font</em></strong>).</p><p>The parameters to the render() method call are a string of the text to render, a Boolean value to specify if we want <strong>anti-aliasing</strong> (see below), the color of the text, and the color of the background. If you want a transparent background, then simply leave off the background color parameter in the method call.</p><h3>Anti-Aliasing</h3><p>Anti-Aliasing is a graphics technique for making text and shapes look less blocky by adding a little bit of blur to the edges. <em>It takes a little more computation time to draw with anti-aliasing</em>, so although the graphics may look better, your program may run slower (but only just a little).</p><p>Here is the difference between an aliased and anti-aliased line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/0*AF0DL0Nov1EewP-J.png" /></figure><p>To make Pygame’s text use anti-aliasing, just pass True for the second parameter of the render() method. The pygame.draw.aaline() and pygame.draw.aalines() functions have the same parameters as pygame.draw.line() and pygame.draw.lines(), except they will draw anti-aliased (smooth) lines instead of aliased (blocky) lines.</p><h3>Playing Sounds</h3><p>Another quite well-known component of any game is sound. In Pygame, playing sounds is much simpler than displaying images from image files. First, we need to create a pygame.mixer.Sound object (we’ll call them as Sound objects for short). The pygame.mixer.Sound() constructor takes one string parameter, which is the filename of the sound file. Pygame can load <strong><em>WAV, MP3, or OGG</em></strong> files.</p><p>To play this sound, call the Sound object’s play() method. If you want to immediately top the Sound object from playing, call the stop() method. The stop() method has no arguments. Here is a sample code:</p><pre>import time</pre><pre>soundObj = pygame.mixer.Sound(&#39;beeps.wav&#39;)<br>soundObj.play()<br>time.sleep(1) # wait and let the sound play for 1 secondsoundObj.stop()</pre><p>The program execution continues immediately after play() is called; it does not wait for the sound to finish playing before moving on to the next line of code.</p><p>The Sound objects are good for sound effects to play when the player takes damage, slashes a sword, or collects a coin. But your games might also be better if they had background music regardless of what was going on in the game. Pygame can only load one music file to play in the background at a time. To load a background music file, call the pygame.mixer.load() function and pass it a string argument of the sound file to load. This file can be <strong><em>WAV, MP3, or MIDI</em></strong> format.</p><p>To begin playing the loaded sound file as the background music, call the pygame.mixer.music.play(-1, 0.0) function. The -1 argument makes the background music forever loop when it reaches the end of the sound file. If you set it to an integer 0 or larger, then the music will only loop that number of times. The 0.0 means to start playing the sound file from the beginning. Changing this value will lead the sound file to be played from a different point of time.</p><p>To stop playing the background music immediately, call the pygame.mixer.music.stop() function. This function has no arguments.</p><p>Here is a code sample:</p><pre># Loading and playing a sound effect:<br>soundObj = pygame.mixer.Sound(&#39;beepingsound.wav&#39;)<br>soundObj.play()</pre><pre># Loading and playing background music:<br>pygame.mixer.music.load(&#39;backgroundmusic.mp3&#39;)<br>pygame.mixer.music.play(-1, 0.0)<br># ...some more of your code goes here...<br>pygame.mixer.music.stop()</pre><h3>Conclusion</h3><p>This concludes the short tutorial on Pygame. Now you are ready to:</p><ul><li>Write a game loop in Pygame from scratch</li><li>Add images, drawings and other graphical representations to the game window</li><li>Animate objects in the windows</li><li>Add music and sound effects to the game</li></ul><p>Only reading the posts and replicating the snippets of code present here <strong>won’t </strong>help you master Pygame or begin developing games. However, <strong><em>practicing what you learned and trying out different and new stuff on your own will help</em></strong>. A good idea would be to replicate the alien demo game included in the Pygame package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yt7SULmF6YTCvqr1.png" /><figcaption>Pygame Aliens</figcaption></figure><p>I will post tutorials for some basic games that one can build using Pygame, meanwhile, you can check out the tutorial for creating a <a href="https://medium.com/byte-sized-code/making-a-simple-snake-game-in-python-part-1-42eb2890f0eb">Snake game in Pygame</a>. I hope this helps you and motivates you to try out Pygame and develop games for fun and recreation. <strong><em>Share, clap, and recommend if you liked the article and would want to read more articles like this.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ea915e31e25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/introduction-to-game-development-in-python-part-3-1ea915e31e25">Introduction to Game Development in Python (part 3)</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Game Development in Python (part 2)]]></title>
            <link>https://medium.com/byte-sized-code/introduction-to-game-development-in-python-part-2-78c2fa2b9315?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/78c2fa2b9315</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Mon, 25 May 2020 11:27:47 GMT</pubDate>
            <atom:updated>2020-05-25T11:27:47.186Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/byte-sized-code/the-worlds-most-boring-game-using-pygame-348c6a8f040a">previous article</a>, we took a look at a simple Pygame program that displays <em>“Hello World”</em>. We got to know some of the basic terms in game development like <em>Game Loops, Events, and Event Handling</em>. Today’s read covers the <strong><em>Objects and Drawing</em></strong> part of Pygame. Without further ado, here is the simplest guide to Pygame Graphics and Objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J1BvGZ2i70QAnZNl.png" /></figure><h3>Pixel Coordinates</h3><p>The window of the “Hello World” program is just composed of little square dots on your screen called <strong>pixels</strong>. Each pixel starts off as black but can be set to a different color. The screen looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*sQ7yS02_Os8iZjBGS_LP1g.jpeg" /><figcaption>A simple Pygame window</figcaption></figure><p>If you remember, the Surface object was about <em>400 pixels wide and 300 pixels tall</em>. Instead, if we had a Surface object that was 8 pixels by 8 pixels, an enlarged picture of this tiny surface would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/0*53AUL6vQSWpOf4rM.png" /></figure><p>The <strong><em>Surface (or window)</em></strong> has 64 pixels arranged in a grid with 8 rows and 8 columns. The image above adds two axes and a zero-indexed numbering to make the representation look better. <br>A specific pixel can be located using the Cartesian Coordinate system. Each column of the X-axis and each row of the Y-axis will have an <strong><em>“address”</em></strong> that is an integer from 0 to 7 so that we can locate any pixel by specifying the X and Y axis integers.</p><p>For example, in the above image, we can see that the pixels at XY coordinates (4,0), (2,2), (0,5), and (5,6) have been painted black, the pixel at (2,4) has been painted gray, while all the other pixels are white. XY coordinates are also called points. Someone who knows the Cartesian Coordinates can easily notice that the Y-axis starts at 0 at the top and <strong><em>increases going down</em></strong>, rather than how it normally decreases going down. This is just how Coordinates work in Pygame (and almost every programming language).</p><p>The Pygame framework often represents Cartesian Coordinates as a tuple of two integers, such as (3,0). <strong><em>The first integer represents the X coordinate and the second is the Y coordinate</em></strong>.</p><h3>Surface Objects and The Window</h3><p>Surface objects are objects that represent a rectangular 2D image. The pixels of the Surface object can be changed by the Pygame drawing functions (described later) and then displayed on the screen. <em>The window border, title bar, and buttons are not part of the display Surface object.</em></p><p>In particular, the Surface object returned by pygame.display.set_mode() is called the <strong>display Surface</strong>. <em>Anything that is drawn on the display Surface object will be displayed on the window when the </em><em>pygame.diaplay.update() function is called</em>.</p><p>Your program will draw several different things to a Surface object. Once you’re done drawing everything on the display Surface object for this iteration of the game loop (called a frame, just like a still image in a paused video) on a Surface object, it can be drawn to the screen. The computer can draw frames very quickly, and our programs will often run around 30 frames per second (that is, 30 FPS). This is called the <strong>“frame rate”</strong> and is explained in the next post.</p><h3>Colors</h3><p>There are three primary colors of light: <em>red, green, and blue</em>. By combining different amounts of these three colors you can form any other color. <em>In Pygame, we represent colors with tuples of three integers</em>. The first value indicates how much red is in the color. An integer of 0 means there is no red in the color, and a value of 255 means there is the maximum amount of red in the color. The second and third values denote the amount of green and blue respectively. These tuples of three integers used to represent a color are often called RGB values.</p><blockquote>As the values can vary from 0 to 255 for each primary color, this means Pygame supports 16,777,216 different colors (256 x 256 x 256). However, any value greater than 255 or less than 0 results in an error that looks like this: ValueError: invalid color argument .</blockquote><p>Some playing around with the numbers yields different colors. For example, (0, 0, 0) indicates the absence of any color. The result is the color black. (255, 255, 255) means all the primary colors are present in their maximum amount. This results in white. Similarly, (255, 0, 0), (0, 255, 0), and (0, 0, 255) represent red, green, and blue respectively.</p><p>Here is a table for the values of a few common colors:</p><pre>╔═══════════╦═════════════════╗<br>║   Color   ║   RGB Values    ║<br>╠═══════════╬═════════════════╣<br>║ Aqua      ║ (0, 255, 255)   ║<br>║ Black     ║ (0, 0, 0)       ║<br>║ Blue      ║ (0, 0, 255)     ║<br>║ Fuchsia   ║ (255, 0, 255)   ║<br>║ Gray      ║ (128, 128, 128) ║<br>║ Green     ║ (0, 128, 0)     ║<br>║ Lime      ║ (0, 255, 0)     ║<br>║ Maroon    ║ (128, 0, 0)     ║<br>║ Navy Blue ║ (0, 0, 128)     ║<br>║ Olive     ║ (128, 128, 0)   ║<br>║ Purple    ║ (128, 0, 128)   ║<br>║ Red       ║ (255, 0, 0)     ║<br>║ Silver    ║ (192, 192, 192) ║<br>║ Teal      ║ (0, 128, 128)   ║<br>║ White     ║ (255, 255, 255) ║<br>║ Yellow    ║ (255, 255, 0)   ║<br>╚═══════════╩═════════════════╝</pre><p>Note: <em>(0, 255, 0) is actually Lime green, and (0, 128, 0) is the lighter version we see as green.</em></p><h4>Transparent Colors</h4><p>Not only can you control the color of a pixel, but you can also control the <strong>opacity</strong> of the color. This can be done by adding a fourth value to the tuple of color. <br>This value is known as the <strong>alpha value</strong>. It is a measure of how opaque (that is, not transparent) a color is. Normally when you draw a color on a pixel, it is completely opaque and thus, the color replaces any other color that was present below it. But with colors that have an alpha value, the upper color (the color you add last) will just add a <em>colored tint</em> over the previous color.</p><p>For example, the tuple of three integers for red is: (255, 0, 0). But if we add a fourth integer for the alpha value, we can make this a half-transparent red color: (255, 0, 0, 128). <strong><em>An alpha value of 255 denotes an opaque color and alpha value of 0 means the color is completely transparent (and thus, invisible), i.e., (255, 0, 0) is the same as (255, 0, 0, 255), and (0, 0, 0) is same as (255, 0, 0, 0).</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*UuFCjTgQBQYt16gl.png" /><figcaption>Tints and Colours</figcaption></figure><p>In order to draw using transparent colors, you must create a Surface object with the convert_alpha() method. For example, the following code creates a Surface object that transparent colors can be drawn on:</p><pre>surfaceObject  = DISPLAYSURF.convert_alpha()</pre><p>It’s important to note that you cannot use transparent colors on Surface objects not returned from a convert_alpha() call, including the display Surface that was returned from pygame.display.set_mode() .</p><h3>pygame.Color Objects</h3><p>Pygame provides objects to denote colors. You can create color objects by calling the pygame.Color() constructor function and passing a tuple for the desired color. You can store this object in tuples just like you can store tuples in variables. Try typing the following in the interactive shell:</p><pre>&gt;&gt;&gt; import pygame<br>&gt;&gt;&gt; pygame.Color(255, 0, 0)<br>(255, 0, 0, 255)<br>&gt;&gt;&gt; myColor = pygame.Color(255, 0, 0, 128)<br>&gt;&gt;&gt; myColor == (255, 0, 0, 255)<br>True<br>&gt;&gt;&gt;</pre><p>It is just a matter of choice and personal preference as any drawing function in Pygame that has a parameter for color can have either the tuple form or Color object form of color passed for it. Now that you know all about colors and coordinates, let’s learn about pygame.Rect objects so we can start using Pygame’s drawing functions.</p><h3>Rect Objects</h3><p>Pygame has <strong><em>two ways</em></strong> to represent rectangular areas. The first is a tuple of four integers:</p><ul><li>The X coordinate of the top left corner</li><li>The Y coordinate of the top left corner</li><li>The width (in pixels) of the rectangle</li><li>The height (in pixels) of the rectangle</li></ul><p>The second way is as a pygame.Rect object, which we will call Rect objects for short. For example, the code below creates a Rect object with a top left corner at (10, 20) that is 200 pixels wide and 300 pixels tall:</p><pre>&gt;&gt;&gt; import pygame<br>&gt;&gt;&gt; spamRect = pygame.Rect(10, 20, 200, 300)<br>&gt;&gt;&gt; spamRect == (10, 20, 200, 300)<br>True</pre><blockquote>The benefit of using Rect object is that it automatically calculates and manipulates stuff for you. For example, the Rect.right property can be used to know the X coordinate of the right edge of the Rect object we just created. Also, we can reassign the location of the right edge, and the other object attributes are recalculated automatically.</blockquote><pre>&gt;&gt;&gt; spamRect.right<br>210<br>&gt;&gt;&gt; spamRect.right = 350<br>&gt;&gt;&gt; spamRect.left<br>150</pre><p>Here is a list of all the attributes that pygame.Rect objects provide:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b773a4e5a0a8e9a0b5a401fb5de988c4/href">https://medium.com/media/b773a4e5a0a8e9a0b5a401fb5de988c4/href</a></iframe><h3>Primitive Drawing Functions</h3><p>Pygame provides several different functions for drawing different shapes onto a Surface object. These shapes such as <strong><em>rectangles, circles, ellipses, lines, or individual pixels</em></strong> are often called drawing primitives. Save the following code in a file and execute it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/234b127377c503594301b13af0ec7280/href">https://medium.com/media/234b127377c503594301b13af0ec7280/href</a></iframe><p>When the program is run, the following window appears:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*Xn_bY_9_A9kS8MHuh5tRHA.jpeg" /><figcaption>The drawn image</figcaption></figure><p>Notice how we make constant variables for the colors that we use. This improves code readability and also makes sure that we don’t have to deal with the nefarious RGB values again and again while changing color for a given part of the code.</p><p><em>The drawing functions are named after the shapes they draw. The parameters you pass these functions tell them which surface to draw on, where to draw the shape (and what size), in what color, and how wide to make the lines</em>. You can see how these functions are called in the pygame_drawing.py program. Here is a short description of each function:</p><ul><li>fill(color) — The fill() method is not a function but a method of pygame.Surface objects. It will completely fill the entire Surface object with whatever color value you pass as for the color parameter.</li><li>pygame.draw.polygon(surface, color, pointlist, width) — This function draws a polygon. The surface and color parameters tell the functions on what surface to draw and in which color. <br>The pointlist parameter is a tuple or list of points. The polygon is drawn by drawing lines between each point and the point that comes after it in the tuple. Then a line is drawn from the last point to the first point. You can also pass a list of points instead of a tuple of points.<br>The width parameter is optional. If you leave it out, the polygon drawn will be filled with color (as is the case with our pentagon). If you do pass the parameter, an outline of the shape with the given width is drawn. A width of “0” fills the polygon. <br>All of the pygame.draw drawing functions have the optional width parameter at the end.</li><li>pygame.draw.line(surface, color, start_point, end_point, width) — This function draws a line between the start_point and end_point parameters.</li><li>pygame.draw.lines(surface, color closed, pointlist, width) — This function draws a series of lines from one point to the next, much like the polygon function above. The only difference is that if you pass False for the closed parameter, there will not be a line form the last point to the first point.</li><li>pygame.draw.circle(surface, color, center_point, radius, width) — This function draws a circle. The center of the circle is at the center_point parameter. The integer passed for the radius parameter sets the size of the circle.</li><li>pygame.draw.ellipse(surface, color, bounding_rectangle, width) — This function draws an ellipse (oval shape). This function has all the usual parameter, but in order to tell the function of how large and where to draw the ellipse, you must specify the bounding rectangle of the ellipse. A <strong>bounding rectangle</strong> is the smallest rectangle that can be drawn around the shape. Here’s an example of a bounding rectangle:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/0*DDI9mlr9zxqK__P7.png" /><figcaption>Bounding rectangle of an ellipse</figcaption></figure><ul><li>pygame.draw.rect(surface, color, rectangel_tuple, width) — This function draws a rectangle. The rectangle_tuple is either a tuple of four integers or a pygame.Rect object can be passed instead.</li></ul><h3>pygame.PixelArray Objects</h3><p>Unfortunately, <strong><em>there isn’t a single function you can call that will set a single pixel to a color</em></strong> (unless you call a line drawing function with the same start and endpoint). The Pygame framework needs to run some code behind the scenes before and after drawing to a Surface object. If it had to do this for every single pixel you wanted to set, your program would run much slower.</p><p>Instead, you should create a pygame.PixelArray object (we’ll call them PixelArray objects from now on). Creating a PixelArray object of a Surface object will <strong>“lock”</strong> the Surface object. While a Surface object is locked, the drawing functions can still be called on it, but it cannot have images like PNG or JPG images drawn on it with the blit() method (I’ll discuss this and animations in a later article).</p><p>If you want to see if a Surface object is locked, the get_locked() Surface method will return True if it is locked and False if it is not.</p><p>The PixelArray object that is returned from pygame.PixelArray() can have individual pixels set by accessing them with two indexes. For example, line 28’s pixObj[480][380] = BLACK will set the pixel at X coordinate 480 and Y coordinate 380 to black.</p><p><em>To tell Pygame that you are finished drawing individual pixels, delete the PixelArray object with a del statement</em>. This is what line 33 does. Deleting the PixelArray object will “unlock” the Surface object. I<strong>f you forget to delete the PixelArray object, the </strong>blit()<strong> command will raise an error that looks like this: </strong>pygame.error: Surfces must not be locked during blit .</p><h3>pygame.display.update() Function</h3><p>After you are done calling the drawing functions to make the display Surface object look the way you want, you must call pygame.diaplay.update() to make the display Surface actually appear on the user’s monitor.</p><p><strong><em>The one thing that you must remember is that this function will only make the display Surface (that is, the Surface object that was returned from the call to </em></strong>pygame.display.set_mode()<strong><em> ) appear on the screen.</em></strong></p><h3>Epilogue</h3><p>We learned about the following in this article:</p><ul><li>The coordinate system of Pygame</li><li>Colors and Color objects</li><li>Surfaces and Windows in Pygame</li><li>Rectangle objects in Pygame</li><li>Drawing in Pygame</li></ul><p>Now you are ready to draw your own shapes and images on the canvas of Pygame. Here are a few images for you to try out using pygame:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*2FoKlb1f3H0jsCOr.png" /><figcaption>A simple building</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/0*1IaNFH2JRbnIbi3z" /><figcaption>A chessboard in Pygame</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*vk1lX-B6fp3OJJ2z.png" /><figcaption>Santa Claus in Pygame</figcaption></figure><p>This article served as a continuation of the previous one to enrich your knowledge about the Pygame framework. Soon, I’ll post another article that dives deeper into the parts of the animation of the Pygame library. <strong>Follow</strong> to get notified of the <em>next article on Pygame</em>. <em>If you found this article interesting or helpful, do clap, share, and recommend it!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78c2fa2b9315" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/introduction-to-game-development-in-python-part-2-78c2fa2b9315">Introduction to Game Development in Python (part 2)</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Game Development in Python (part 1)]]></title>
            <link>https://medium.com/byte-sized-code/the-worlds-most-boring-game-using-pygame-348c6a8f040a?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/348c6a8f040a</guid>
            <category><![CDATA[games]]></category>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Fri, 15 May 2020 04:24:15 GMT</pubDate>
            <atom:updated>2020-05-25T11:28:32.144Z</atom:updated>
            <content:encoded><![CDATA[<p>Game development is a rewarding experience and also an exciting teaching tool. <strong><em>But what can you learn by coding the most boring game?</em></strong> This post serves as an introduction to Pygame by helping you write a simple program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z09M9I-VtzQjpKE2.jpg" /><figcaption>A game of Chess between the Holmes brothers</figcaption></figure><p>Pygame is an excellent tool for developers. It isn’t set up to be compatible with mobile devices. Also, due to Python’s nature, it isn’t great for commercial products in general; yet, its strengths include its ease of use and accessibility. <em>The flow of the Pygame workflow is a fantastic way for beginners to learn game programming at a deeper level</em>. <em>It is straightforward, while also having a fair amount of depth.</em></p><p>Before jumping right into coding, we first need to know some basic stuff. Thus, we take this short diversion to help you better understand the purpose and basics of installing and using Pygame. <em>You can skip this part if you are already familiar with Pygame.</em></p><h3>GUI vs. CLI</h3><p>The “normal” python programs that you write with pythons built-in functions interact with the user by print and input statements. You can output text onto the screen, and the user inputs values <strong><em>using the keyboard</em></strong>. These kinds of programs are said to have a CLI (Command Line Interface, pronounced as See-El-Eye). <strong><em>CLI are interfaces that heavily depend on the keyboard and are generally devoid of graphics</em></strong>.</p><p>On the other hand, GUI (Graphical User Interface, pronounced as Gooey) displays graphical stuff, as the name indicates. All of us are most familiar with this interface. In fact, the screen you are using to read this post is a GUI, and the machine you are running it on (Windows, Android, Ubuntu, or iOS) is also a GUI.</p><p>A CLI program is somewhat limited in terms of functionality. As some of you may have noticed, a CLI program <strong>waits for the user to input</strong> an answer using the keyboard and <strong>press enter before the application can process the information</strong>. This means <strong><em>a program (or game) cannot process input in real-time (as the user presses a button)</em></strong>. CLI programs also lack the visual appeal of color and graphics. Thus, it is essential to learn to program in GUI to develop advanced games using graphics (like this game of snake).</p><p>Pygame provides functions for creating programs with GUI. Pygame functions easily take care of things like drawing graphics, playing sounds, handling mouse input, and other items necessary to develop GUI applications.</p><h3>Installing Pygame</h3><p>I believe it is better to learn by coding rather than just reading random articles or books. Here is the source code for a simple “Hello World” program in Pygame that we will use as a reference to learn more about Pygame. <strong><em>I highly encourage people to write this simple snippet of code and play around with it as we discuss different features of Pygame</em></strong>.</p><p>Since you are here, I assume you know at least a bit of python and what <em>pip </em>is. If not google it! It’s never too late to learn. If you haven’t installed Pygame yet, you can do so by running the following commands:</p><pre>python -m pip install pygame</pre><p>To check if it is properly installed, you can run an example file included in the package:</p><pre>python3 -m pygame.examples.aliens</pre><p>If it works, you are ready to go! Else have a look <a href="https://www.pygame.org/wiki/GettingStarted">here</a>.</p><h3>The World’s Most Boring Game</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd3a0a7aba12c4184c5c14cec019a497/href">https://medium.com/media/cd3a0a7aba12c4184c5c14cec019a497/href</a></iframe><p>Type the above code in an empty file and save it with the extension “.py”. Then go on and run the program. A window like this should appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*sQ7yS02_Os8iZjBGS_LP1g.jpeg" /><figcaption>The most boring game in pygame!</figcaption></figure><p><strong>Yay! You just made the world’s most boring video game!</strong> It’s just a blank screen with a “Hello World!” on the top of the window (title bar). Like a standard window, clicking on the X button on the corner of the window will end the game and make the window disappear.</p><p>Lets’s take a closer look at the program.</p><h3>Setting up a Pygame Program</h3><p>The first few lines of the code will be found in almost any program that uses Pygame.</p><pre>import pygame, sys<br>from pygame.locals import *</pre><p>The first line is a simple import statement that imports the pygame and sys modules. <strong><em>It enables us to use the functions present in the respective modules to develop our game</em></strong>. All of the Pygame functions dealing with graphics, sound, and other features that Pygame provides are in the pygame module.<br>The second line imports several constant variables stored in the <em>pygame.locals </em>module that we can use in our program.</p><pre>pygame.init()</pre><p>The fourth line is the <em>pygame init</em> function call, which always needs to be called after importing the pygame module and before calling any other Pygame function. <strong><em>The init function initializes all the imported modules of Pygame before they can be used</em></strong>. Failure to include this in any program will always lead to errors.</p><pre>DISPLAYSURF = pygame.display.set_mode((400, 300))</pre><p>The fifth line calls the set_mode function that returns a <em>pygame.Surface</em> object for the window (Surfaces coming up in the next post). <strong><em>The supplied tuple (400, 300) will return a window with a width of 400 pixels and a height of 300 pixels</em></strong>. Note: The set_mode function takes in a tuple as an argument. <em>A TypeError is thrown when you try to supply two ints instead of a tuple.</em></p><pre>pygame.display.set_caption(&#39;Hello World!&#39;)</pre><p>Line 6 <strong><em>sets the caption text that will appear on the title bar of the game</em></strong>. It takes a string as an argument and makes the text appear as the caption:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*00j0TLv8gruK_eCt1SiYdA.jpeg" /><figcaption>Title bar caption</figcaption></figure><h3>Game Loops and Game States</h3><pre>while True: # main game loop<br>    for event in pygame.event.get():</pre><p>The while loop in line number 7 is special. It always evaluates to True and, thus, is an infinite while loop. The loop never exits unless it encounters a break, return, or in our case, the sys.exit() call.</p><p>Most of the games developed in pygame or in general have a while loop along with a comment (good programmers always comment!) calling it the <strong>“main loop”</strong> or <strong>“game loop”</strong>, even the <strong>“main game loop”</strong>. A game loop is a loop where the code does three things:</p><ul><li>Handles events</li><li>Updates the game state</li><li>Draws the game state to the screen</li></ul><p>The<strong> game state</strong> simply refers to a <strong><em>set of values for all the variables in a game program</em></strong>. In many games, the game state includes the set of variables that track a players health and position, the health and position of any enemies, any marks/trails made by the player or enemy, the score, whose turn it is and other things that describe a precise moment in the game.</p><p>A game state can be thought of as a picture of an instance of the game. Whenever you <strong><em>pause a game, the game state doesn’t change</em></strong>, and saving a game basically saves the game state.</p><p>Since players interact with the game using events (such as a mouse click or keyboard presses), the game state is usually updated in response to such events. <strong><em>The game loop constantly checks and re-checks many times a second for any new events that have happened and updates the game state accordingly.</em></strong> In Pygame, this is done by calling the pygame.event.get() function. <br>The main loop also contains code that updates the game state based on which events have been created. This is termed as <strong>event handling.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6xUPDh7r60KhIZD_A8r9Q.png" /><figcaption>The game loop</figcaption></figure><h4>pygame.event.Event Objects</h4><p>Any time the user does one of the several actions such as pressing a keyboard, or moving/clicking the mouse on the program’s window, a pygame.event.Event object is created to record this <strong>“event”</strong>. We can get a list of events that have happened by calling the pygame.event.get() function. <br>This is precisely what we are doing in the first line inside the while loop. The pygame.event.get() function returns a list of events that have happened since the last time the function was called.</p><pre>while True: # main game loop<br>    for event in pygame.event.get():</pre><p>The for loop will iterate over the list of events that have happened since the last time the get function was evoked. On each iteration, a variable named event is assigned the value of the next event object in the list. <strong><em>The list is sequential</em></strong>, i.e., the order of events in the list is the order in which they happen. If no events have happened, an empty list is returned.</p><h4>The QUIT Event</h4><p>Event objects have an <strong>attribute (or property)</strong> called<strong> type</strong>, which tells what kind of event the object represents. Pygame has a constant variable for each of the possible types in the pygame.locals module.</p><pre>if event.type == QUIT:<br>    pygame.quit()<br>    sys.exit()</pre><p>The first line of this code block checks if the event type is equal to the constant QUIT. If the event object is a quit event, then the pygame.quit() and sys.exit() lines are run, closing the pygame module and closing the window. The pygame.quit() function is like the opposite of the pygame.init() function and <strong><em>deactivates the pygame library</em></strong>. The sys.exit() <strong><em>closes the window and terminates the program</em></strong>.</p><p>One should always call pygame.quit() before calling sys.exit() . In most cases, it works just fine either way, but in some cases, some bugs will crash the native python IDLE (if you are using IDLE). Also, many times I have noticed that one has to manually turn off the instance of pygame from the task manager if you don&#39;t call the pygame.quit() function at the end of your program.</p><p>Since there are no other ‘if’ statements, the code doesn’t do much of event handling, and our keyboard presses and mouse movements go unnoticed. The program then continues to the final line:</p><pre>pygame.display.update()</pre><p>The function in the last line <strong><em>draws the Surface object</em></strong> returned by pygame.display.set_mode to the screen. Since the Surface object hasn’t changed, the same black image is redrawn to the screen each time pygame.display.update() is called. That’s the whole program. The program then returns to executing the while loop from the beginning and repeating the process described again and again till we close the window.</p><h3>Conclusion</h3><p>Wait! It’s just this? Probably that’s what all of you are wondering right now. The post serves as a simple and easy to grasp introduction to Pygame. Here is a <a href="https://medium.com/byte-sized-code/making-a-simple-snake-game-in-python-part-1-42eb2890f0eb"><strong><em>link to making a game of snake in Pygame</em></strong> </a>for the interested readers.</p><p>Things that you learned:</p><ul><li><strong><em>The basic structure of a Pygame program</em></strong></li><li><strong><em>Game Loops and game states</em></strong></li><li><strong><em>Events and event handling in Pygame</em></strong></li></ul><p>Soon, I’ll post <a href="https://medium.com/byte-sized-code/introduction-to-game-development-in-python-part-2-78c2fa2b9315">another article</a> that dives deeper into the objects and graphics parts of the Pygame library. <strong>Follow</strong> to get notified of the <em>next article on Pygame</em>. <em>If you found this article interesting or helpful, do clap, share, and recommend it!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=348c6a8f040a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/the-worlds-most-boring-game-using-pygame-348c6a8f040a">Introduction to Game Development in Python (part 1)</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Guessing Game in Python]]></title>
            <link>https://medium.com/byte-sized-code/a-simple-guessing-game-in-python-3d825dc9223b?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/3d825dc9223b</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Fri, 08 May 2020 15:18:16 GMT</pubDate>
            <atom:updated>2020-05-08T15:18:16.740Z</atom:updated>
            <content:encoded><![CDATA[<p>Many people start with learning to code and give up mid-way as they don’t know what to do further or <em>get frustrated while doing the numerous painful but straightforward exercises online that gives them no joy upon finishing</em>. <strong>It is just another easy assignment completed.</strong></p><blockquote>People are encouraged to develop programs that are enjoyable and challenging to keep them motivated to learn more.</blockquote><p>Here is the outline for one such exercise, a simple game designed to be coded and enjoyed in python.</p><p>Keeping in mind the<strong><em> need for originality and the importance of developing logical thinking</em></strong> in programmers, <strong><em>everyone is encouraged to use the outline below to write their versions for the game</em></strong>. However, a refined implementation is given to compare your code to and (hopefully) inspire you to revise and improve your code.</p><h3>The Game</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oFd4Z0zYmrLLtDfi.png" /></figure><p>The game is pretty simple. The computer randomly chooses a number, and the user has to guess the number that the computer has selected in a specified number of tries. The user is informed whether the number guessed by the user is greater or smaller than the required number to be guessed.</p><h3>An outline</h3><p>There are many ways to accomplish this simple task, and one such way is outlined in the flowchart below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWs1tY0Pkih6MrlKfdWf1w.png" /><figcaption>Flowchart for the game</figcaption></figure><p>As seen above, the game passes through some significant<em> checkpoints</em> that are stressed below:</p><ul><li><strong>Initialization</strong>: The part where the computer chooses a number</li><li><strong>Check the number of tries</strong>: checks if the number of attempts has exceeded. If the user exceeds the number of maximum tries, the program should terminate.</li><li><strong>User input</strong>: The user inputs a guess. Note — The program must check if the number of tries has exceeded before this</li><li><strong>Check guess</strong>: If guess matches the answer, the program exits. Otherwise, the program should compare the guess with the answer and let the user know how the guess compares to the answer.</li></ul><h3>Points to Ponder</h3><p>Here are a few points that I came across while implementing the game:</p><ul><li><strong><em>What should be the number of tries? </em></strong><br>As the game is random (i.e., the computer chooses a number randomly), what should be the number of tries that a user should get to guess the number?</li><li><strong><em>Optimal strategy</em></strong><br>Can you devise an optimal strategy that helps you guess the number correctly almost every time? I have one which I think is optimal, comment yours so we can discuss more!</li><li><strong><em>The difficulty of the game</em></strong><br>Almost all popular games provide different levels that define how easy/hard it is to win a game. What can be a similar measure for this game? Increasing or decreasing the number of tries seems a bit trivial. Other suggestions are welcome!</li></ul><h3>Conclusion</h3><p>Here is my take on the game. Let me know what you think of it, and if you enjoyed reading this article and implementing the game for yourself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1924fda9a7c224de07ed352058d4bbb5/href">https://medium.com/media/1924fda9a7c224de07ed352058d4bbb5/href</a></iframe><h3>Before you go…</h3><p><strong>Connect with me on </strong><a href="https://www.instagram.com/om_arpit/"><strong>Instagram</strong></a><strong> and </strong><a href="https://www.facebook.com/ompuri55555"><strong>Facebook</strong></a><strong>.</strong><br><em>If you liked this story, hit the clap button (you can clap up to 50 times with just one button!) and follow me for more such articles!</em></p><blockquote>Share, recommend, and comment away! Engagement helps us communicate and be more human!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d825dc9223b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/a-simple-guessing-game-in-python-3d825dc9223b">A Simple Guessing Game in Python</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first hands-on project with Rhyme!]]></title>
            <link>https://medium.com/byte-sized-code/my-first-hands-on-project-with-rhyme-1120a645171f?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/1120a645171f</guid>
            <category><![CDATA[mooc]]></category>
            <category><![CDATA[hands-on-learning]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[coursera]]></category>
            <category><![CDATA[review]]></category>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Sat, 02 May 2020 11:38:38 GMT</pubDate>
            <atom:updated>2020-05-02T11:38:38.315Z</atom:updated>
            <content:encoded><![CDATA[<p>In this lockdown, after getting bored for a long time, I decided to try out different <a href="https://en.wikipedia.org/wiki/Massive_open_online_course">MOOCs</a>. As I am bored most of the time when I’m not coding, I have accounts in many different online learning platforms that I generally don’t use much (e.g., Udemy, Coursera, edX). After browsing the catalog for over a day, I decided I should do a guided project instead of a full-fledged course.</p><h3>Why a “Guided Project”?</h3><p>On August 28, 2019, Coursera announced the acquisition of <a href="https://rhyme.com/">Rhyme Softworks</a>, which provides custom cloud computing frameworks that can be used to complete projects online. It provides the platform with a special kind of short course called “Guided Projects” that are follow-along projects you complete online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*p372PcbnBMs9uj7gYh-GTA.jpeg" /><figcaption>Coursera acquired Rhyme Softworks</figcaption></figure><p>There were many different reasons why I thought a guided project is better:</p><ul><li>It’s different and seemed interesting</li><li>I love hands-on projects and sites like Freecodecamp and Codeacademy</li><li>It is probably the best way to learn to code</li><li>Lastly, it is small and completed in a few hours</li></ul><h3>The Guided Project</h3><p>Finally, I decided I should do this course named “<a href="https://www.coursera.org/learn/multilayer-perceptron-model-keras/home/welcome">Build Multi-Layered Perceptron Models with Keras</a>”. I always wanted to know more about machine learning and Keras, and this seemed like an opportunity for the same.</p><h4>Rhyme interface</h4><p>Initially, I had a few hiccups when I tried to log on to the platform and get things going.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*yLH2zSuF9WlWIP5bKjAFqA.jpeg" /><figcaption>Initially, I faced the token authentication problem.</figcaption></figure><p>The Jupyter notebook would just not open and asked for some sort of token for authentication. I realized that as it is a cloud desktop, I can restart Jupyter from the terminal, and voila! It worked. I just had to change the port of the notebook a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YMKlRwPqTY7T-hEU6vV9w.jpeg" /><figcaption>The Rhyme interface</figcaption></figure><p>As one can see, the whole webpage is divide into two parts; one contains the cloud computing unit where one can write and execute code, and the other part includes the video lesson for the project. Various other helpful features allow the user to interact with the instructor or teaching assistant directly (if they are online) annotated in the image. The best part of the project is that they mail you the finished product (whatever code you wrote on the machine) along with the datasets and other functions used in the notebook.</p><h4>The Instructor</h4><p>The instructor, <a href="https://www.linkedin.com/in/snehankekre/">Snehan Kekre</a>, was friendly and explained the motive behind the guided project. It was easy to follow along and write the lines of code. The instructor explained the code as he wrote (also I was coding along with him), which made it much easier to follow than other traditional lectures.</p><h3>My Experience</h3><p>The guided project consisted of three parts/phases:</p><ul><li>An introduction page — This part details the problem addressed in the project and the approach to deal with it.</li><li>The cloud computing framework and the project — This is the main part of the project. Here you follow the instructor and code.</li><li>A short quiz to test your understanding — The questionnaire asks about the different aspects of the project; it may be about some specific code or, in general, about the problem statement in general.</li></ul><p>It took me about 1.5 hours to complete the whole project (including the quiz). The quiz was quite easy. Then I had to fill a survey and got my certificate. The project was easy to follow through and quite informative. It was like the hands-on lab sessions we have in our college from time to time (for some courses). I feel like it has made me a bit confident about MLPs in general and also implementing an MLP using Keras. After the project, I installed Keras and tried to code the whole problem from scratch on my PC, and it was awesome!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*hu1fD9KdLPvEN5_f" /><figcaption>Online Learning</figcaption></figure><h4>Pros</h4><ul><li>Informative — Although the project was quite short, it did boost my knowledge and confidence.</li><li>Pretty Hands-on — Reading a theoretical model and implementing it to solve a real-life problem are two very different things. The hands-on approach shines a light on the subtle nuances and best practices that should be kept in mind while coding a theoretical project.</li><li>No downloads/software required — As the code you write is implemented on a cloud computing unit, you can run different programs, including high-end libraries like TensorFlow and Keras, that might not work on your native desktop or computer.</li><li>Side by side lectures — As the lecture and coding go in together, it is quite easy to navigate and understand even the most complicated code as opposed to listening to a lecture and then later implementing the same code separately.</li><li>Online — Lastly, as the project is online, it doesn’t require you to go to someplace specifically to learn and the lessons can be accessed from the comfort of your own home.</li></ul><h4>Cons</h4><ul><li>Too Easy — The major problem I have with the project is it was too easy, including the quiz at the end. The quiz consisted of just five questions that were quite easy to answer.</li><li>Pre-requisite Knowledge — The project assumes a specific pre-requisite knowledge about the topic, which may be a setback for people interested in a guided project but who don’t have the background knowledge to take on one.</li></ul><h3>Takeaway</h3><p>As mentioned earlier, one needs some background knowledge before jumping into a guided project. Apart from that, it is was a rather enriching experience for me, and I hope it will be the same for others who undertake such projects. I liked the experience so much that I have completed another project, “<a href="https://www.coursera.org/learn/deep-learning-fundamentals-logistic-regression/home/welcome">Logistic Regression with Python and Numpy</a>” and have enrolled in some more. The guided projects provide insight into the practical side of things, which is a necessity in today’s world.</p><h3>Before you go…</h3><p><strong>Connect with me on </strong><a href="https://www.instagram.com/om_arpit/"><strong>Instagram</strong></a><strong> and </strong><a href="https://www.facebook.com/ompuri55555"><strong>Facebook</strong></a><strong>.</strong><br><em>If you liked this story, hit the clap button (you can clap up to 50 times with just one button!) and follow me for more such articles!</em></p><blockquote><em>Share, recommend, and comment away! Engagement helps us communicate and be more human!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1120a645171f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/my-first-hands-on-project-with-rhyme-1120a645171f">My first hands-on project with Rhyme!</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a simple Snake game in python (part 2)]]></title>
            <link>https://medium.com/byte-sized-code/making-a-simple-snake-game-in-python-part-2-2c41756d4574?source=rss----3ba429f14279---4</link>
            <guid isPermaLink="false">https://medium.com/p/2c41756d4574</guid>
            <dc:creator><![CDATA[Arpit Omprakash]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 11:56:26 GMT</pubDate>
            <atom:updated>2020-02-03T18:01:27.394Z</atom:updated>
            <content:encoded><![CDATA[<p>In part 1, we have covered the basics of pygame and written classes for the objects in our game (food and the snake). So the plan for part 2 is to write some essential functions related to the scoring, and then we will put everything together into a final program and play the game!</p><p>Without further ado, here is the final piece of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a3720fd44e5cbe97ee4dced26b5e959/href">https://medium.com/media/4a3720fd44e5cbe97ee4dced26b5e959/href</a></iframe><p>Let’s go through it step by step. The first function here</p><pre># Draw the score on the screen<br>def draw_score(surface):<br>    global high_score<br>    font_name = pg.font.match_font(&#39;arial&#39;)<br>    if score &gt; high_score:<br>        high_score = score<br>    # writing the score<br>    font = pg.font.Font(font_name, 18)<br>    text_surface = font.render(&#39;Score: {} High Score: {}&#39;.format(score, high_score), True, white)<br>    text_rect = text_surface.get_rect()<br>    text_rect.midtop = (200 , 10)<br>    surface.blit(text_surface, text_rect)</pre><p>is used to write scores on the screen. First, we declare global to access and modify the high_score variable. We set the high score as the current score if it is higher than the current high score. Next, we choose a font (the first line, font_name = pg.font.match_font(&#39;arial&#39;) ensures that we find a font that is either ‘arial’ or whose name has an ‘arial’ in it. The next three lines create a rectangle to display the score, font.render(‘Score: {} High Score: {}&#39;.format(score, high_score), True, white) tells the program to write ‘Score: score High Score: high_score’ in white. The other parameter which is set as True is anti-aliasing. It smoothens the text. Next, we get the rectangle on which the text is drawn via get_rect() and place its mid-top position at (200,10) in the next line. The final line writes the score in the text_rect object.</p><p>Next up, we have the game over function:</p><pre># What to do when the game is over<br>def game_over():<br>    global score<br>    # writing game over<br>    gameOverFont = pg.font.Font(&#39;freesansbold.ttf&#39;, 24)<br>    gameOverSurf = gameOverFont.render(&#39;Game Over&#39;, True, white)<br>    gameOverRect = gameOverSurf.get_rect()<br>    gameOverRect.midtop = (200, 50)<br>    wn.blit(gameOverSurf, gameOverRect)<br>    # reset score<br>    score = 0<br>    pg.display.flip()<br>    time.sleep(2)<br>    # re-initialize game<br>    run = True<br>    fd = Food()<br>    p = Player()<br>    play_game(fd, p)</pre><p>The function first writes the word “Game Over” on the screen (the first 6–7 lines). Then it resets the score to 0. pg.display.flip() is used to update the screen so that the changes made above are visible. Next, we call the time.sleep() function from the time module, which makes the screen unresponsive for 2 seconds. Finally, we re-initialize the whole game by creating new food and player objects and initializing the game environment using the play_game function.</p><p>Next, we have a look at the play_game function:</p><pre># The game<br>def play_game(fd, p):<br>    global score<br>    run = True<br>    while run:<br>        # FPS<br>        clock.tick(30)<br>        for event in pg.event.get():<br>            if event.type == pg.QUIT:<br>                run = False<br>        # draw food, snake, score<br>        wn.fill(black)<br>        fd.draw_food(wn)<br>        p.draw_player(wn)<br>        draw_score(wn)<br>        # user input<br>        pressed = pg.key.get_pressed()<br>        if pressed[pg.K_UP]:<br>            p.change_direction(&#39;up&#39;)<br>        if pressed[pg.K_LEFT]:<br>            p.change_direction(&#39;left&#39;)<br>        if pressed[pg.K_DOWN]:<br>            p.change_direction(&#39;down&#39;)<br>        if pressed[pg.K_RIGHT]:<br>            p.change_direction(&#39;right&#39;)<br>        # move snake<br>        p.move()<br>        # eating<br>        if fd.is_eaten(p.head):<br>            fd.new_pos()<br>            p.add_unit()<br>            score += 10<br>        # collision<br>        if p.is_collision():<br>            run = False<br>            game_over()</pre><pre>pg.display.update()</pre><p>The play_game function takes the two objects (food and player) as the input and makes them play the game. In part 1, we had seen pretty much half of the code written here, so I am not explaining that part in detail. I’ll be talking about the changes from the code we encountered in the first post. After we fill the screen with a black color, in the next three lines, we draw the food, the player, and the score. pressed = pg.key.get_pressed() Makes a note of all the keys that are pressed on the keyboard by the user. The next segment of code checks if the user pressed a key and then calls an appropriate function in response, e.g., the line if pressed[pg.K_UP] checks if the user pressed the Up arrow, then it changes the direction of snake to upwards in the next line, p.change_direction(&#39;up&#39;). The very next line moves the snake in the direction of its head. The last two blocks of code check if the snake has eaten the food or if the snake has collided with itself or the game boundaries. When the snake eats the food, the block if fd.is_eaten(p.head): is executed and (a.) the food moves to a new position (b.) the snake body length is increased by one unit (c.) the score is increased by 10. Similarly, when a collision occurs, the if p.is_collision(): block is executed, the game loop is stopped, and the game_over function is called. The last line pg.display.update() Updates the screen from time to time so that we can see the snake, the food, and the scores. The very first line of the function is clock.tick(30) this may seem puzzling, and we haven’t talked about it yet, but we are going to now. Comment out that line and run the whole code.</p><p>When you run the whole code without the clock.tick() line, everything happens fast. The game moves at the fastest rate that your computer can run the program, and nothing is visible to us, and the snake dies by colliding with the wall. So, to make time for the user to interact with the game, we need to slow down the speed at which everything progresses. The slowdown is achieved by the clock.tick() function. clock = pg.time.Clock() is an object of pygame that is used to regulate the FPS or Frames Per Second of the game. A value of 30 (as in the code above) implies that the calculations and the images of the final product (snake, the score, and the food) are drawn about 30 times in a second, which is an incredibly fast rate. Changing the values will slow down or speed up the whole game and can thus be used to regulate the difficulty of the game.</p><p>This is the final piece of code:</p><pre>pg.init()</pre><pre>wn = pg.display.set_mode((screen_width, screen_height))<br>pg.display.set_caption(&#39;A simple game of Snake&#39;)<br>fd = Food()<br>p = Player()<br>play_game(fd,p)</pre><pre>pg.quit()</pre><p>This makes a screen object and calls the required functions to initialize the game. The whole code compiled is present <a href="https://github.com/aceking007/CodeProjects/blob/master/Games/pygame_tut/SnakeAI/snake.py">here</a> for reference. I hope you enjoyed the tutorial, and it made you learn some new things. Here are a few screenshots of the game:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*T7_KT-cv4oXxh2mHfBGGCg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*84tiT6A2U1GZ0mCDaWLyVQ.jpeg" /><figcaption>Screenshots from the game</figcaption></figure><p>Comment below if you enjoyed making your own game of snake and how did others (friends and family) feel when you showed it to them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c41756d4574" width="1" height="1" alt=""><hr><p><a href="https://medium.com/byte-sized-code/making-a-simple-snake-game-in-python-part-2-2c41756d4574">Making a simple Snake game in python (part 2)</a> was originally published in <a href="https://medium.com/byte-sized-code">Byte-Sized-Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>