<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sabahat Usman on Medium]]></title>
        <description><![CDATA[Stories by Sabahat Usman on Medium]]></description>
        <link>https://medium.com/@sabahat.usman.su?source=rss-48c6a8ff055------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DnWBcaNgXHBKnMAG</url>
            <title>Stories by Sabahat Usman on Medium</title>
            <link>https://medium.com/@sabahat.usman.su?source=rss-48c6a8ff055------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:42:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sabahat.usman.su/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Small Paint Program]]></title>
            <link>https://medium.com/@sabahat.usman.su/a-small-paint-program-1d6cb64f8da7?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6cb64f8da7</guid>
            <category><![CDATA[coding-project-for-kids]]></category>
            <category><![CDATA[replit]]></category>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[pygame-repl-it]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Wed, 27 May 2020 17:37:45 GMT</pubDate>
            <atom:updated>2020-05-27T17:37:45.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/47/0*CVpRNKF69lcgm8v1" /></figure><p>A Pygame project tutorial</p><p>Level: Beginner</p><h3>Overview</h3><p>Pygame is a set of Python modules for creating games. This tutorial will introduce you to Pygame in<strong> repl.it.</strong> The modules that you will be working with are:</p><ol><li><strong>pygame.display</strong>: a module to control the screen.</li><li><strong>pygame.draw</strong>: a module to draw shapes on the screen.</li><li><strong>pyame.event</strong>: a module to interact with events.</li><li><strong>pygame.mouse</strong>: a module to work with the mouse.</li></ol><p>You will also come across a few computer science concepts which include:</p><ol><li>Variable declaration</li><li>If conditional</li><li>While statement</li><li>For-loop</li><li>Function declaration</li></ol><h3>Prerequisites</h3><ol><li>You should have signed up for a free account at repl.it. Try to get familiar with the interface if you are new to it.</li><li>You should be familiar with the Python language syntax.</li></ol><h3>Let’s begin!</h3><ol><li>Sign in to repl.it</li></ol><p>Sign in to your repl.it account and start a new repl. Make sure you choose Pygame as the language and create a name for your repl.</p><ol><li>Import the Pygame module.</li></ol><p>Before you can start using any module, you need to import it into your program. You do this by typing in the keyword <em>import</em> followed by the name of the module.</p><pre>import pygame</pre><p>2. Create a variable for storing the RGB code for a color.</p><p>An RGB code for a color is a set of three integers with a value between 0 to 255 inclusive representing the amount of red, green, and blue respectively.</p><p>The RGB code for blue is 0, 0, 255.</p><p>Let’s create a variable called BLUE. This data type of this variable will be a tuple. A tuple is a data type in Python that holds a collection of objects and is unchangeable. This tuple BLUE will be holding a collection of three integers representing the RGB code for the color blue.</p><pre>BLUE = (0 , 0 , 255)</pre><p>3. Initialize the screen.</p><p>Declare a variable called screen and assign it to the function set_mode() in the pygame.display module. The set_mode() function takes in a tuple containing two integers that represent the width and height of your screen and returns a pygame.surface object. A pygame.surface object is used to represent images, in this case a screen display.</p><pre>screen = pygame.display.set_mode( (500, 500) )</pre><p>4. Create a function to draw a circle on the screen.</p><p>To create a function, type in the keyword <strong>def</strong> followed by the name of your function and a pair of parentheses. We will name our function <em>drawCircle</em>. Our function will take in three parameters: <em>screen</em>, <em>x,</em> and <em>y </em>where x and y will be placeholders for the coordinates of a mouse click or the position on screen where you want the circle to be drawn. Our function will return no value. Inside of the function block or body, we will call the circle() function in the pygame.draw module. The circle() function takes in a few arguments:</p><ul><li>surface: the screen to draw on</li><li>RGB code for a color</li><li>coordinates for the center</li><li>radius</li></ul><pre>def drawCircle( screen, x, y ):<br>  pygame.draw.circle( screen, BLUE, ( x, y ), 5 )</pre><p>5. Draw a circle on the screen.</p><p>We will create an infinite while loop in which we will call our drawCircle() function. We will also call the flip() function in the pygame.display module. The flip() function refreshes the contents of the screen each time it is called.</p><pre>while True:<br>  drawCircle( screen, 50, 50 )<br>  pygame.display.flip()</pre><p>6. Draw a circle on the screen wherever the mouse is clicked.</p><p>To handle mouse click events, we will make use of the pygame.event module. Inside the while loop, we will call the get() function in pygame.event module. This function returns a list of events that have occurred. We will iterate through the event list using a for-loop. Inside the loop, we will check if the type of event is a pygame.MOUSEBUTTONDOWN, we will call the drawCircle() function and pass it the screen to draw on and the position of the mouse cursor. We can get the position of the cursor by calling the get_pos() function in the pygame.mouse module.</p><pre>while True:<br>  for event in pygame.event.get():<br>  if event.type == pygame.MOUSEBUTTONDOWN:<br>    ( x, y ) = pygame.mouse.get_pos() <em># returns the position of mouse cursor</em><br>    drawCircle( screen, x, y )</pre><pre>  pygame.display.flip()</pre><p>7. Use your mouse to imitate a paintbrush.</p><p>To imitate a paintbrush, we need to make sure that we draw a circle while we hold down the mouse button and move it. As soon as we release the mouse button, nothing should be drawn.</p><p>To do this, we will have to do the following steps:</p><ul><li>We will create a global variable called isPressed and initialize it to False.</li><li>We will set the isPressed to True whenever the mouse button is down.</li><li>We will set the isPressed to False whenever the mouse button is up.</li><li>We will draw a circle when the mouse button is down ( isPressed = True) and the mouse is moving ( event.type == pygame.MOUSEMOTION).</li></ul><pre>while True: <br>  for event in pygame.event.get():<br>    if event.type == pygame.MOUSEBUTTONDOWN:<br>      isPressed = True<br>    elif event.type == pygame.MOUSEBUTTONUP:<br>      isPressed = False<br>    elif event.type == pygame.MOUSEMOTION and isPressed == True:         </pre><pre>      ( x, y ) = pygame.mouse.get_pos()       <em># returns the position of mouse cursor</em><br>      drawCircle( screen, x, y )</pre><pre>   pygame.display.flip()</pre><p>You have just created a small paint program using Pygame in repl.it. Congratulations! For a working solution, visit <a href="https://repl.it/@SabahatUsman0/PygameDrawCircle#main.py">here</a>. If you have any questions, leave it in the response section and I’d be glad to help.</p><h3>References</h3><p><a href="https://www.pygame.org/docs/">https://www.pygame.org/docs/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6cb64f8da7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to handle keyboard events in a Python turtle environment?]]></title>
            <link>https://medium.com/@sabahat.usman.su/how-to-handle-keyboard-events-in-a-python-turtle-environment-4c0cca74afbd?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c0cca74afbd</guid>
            <category><![CDATA[turtle-screen]]></category>
            <category><![CDATA[project-for-kids]]></category>
            <category><![CDATA[turtle-screen-onkey]]></category>
            <category><![CDATA[handling-events]]></category>
            <category><![CDATA[python-turtle-graphics]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Tue, 26 May 2020 22:02:43 GMT</pubDate>
            <atom:updated>2020-05-26T22:02:43.722Z</atom:updated>
            <content:encoded><![CDATA[<p>A Python Turtle graphics project</p><p>Following is a Python program that uses <em>Turtle graphics</em> to draw infinite lines on the screen. This program has been taken from <em>“Coding Projects in Python”</em> by DK called <em>Mutant Rainbow. It is written in the trinket platform.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BdzrHhBRZ9LwBJFe" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B_KeJ4iIWRJ4LBCy" /></figure><p>In this program, we control the default unnamed turtle instance that is made available to us after we import the turtle module. We used the identifier <em>t</em> for it. The turtle draws colorful lines filling up the screen. There is no way of clearing the screen. How can we clear the screen if we wanted to? Since we are using the default turtle, we will use the Screen() methods: <em>listen(),update() </em>and <em>onkey(fn, key)</em> to achieve the purpose. (The default screen instance is not available on trinket)</p><p>Steps:</p><ol><li>Define a function and name it <em>clear().</em> It will take no parameters.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*HJf_R-dkcRErzSJb" /></figure><ol><li>Inside the function block, type in <em>t.clear()</em><strong> </strong>where <em>t </em>is the identifier for the turtle module. The t.clear() function deletes the turtle drawings from the screen.</li><li>Inside the infinite <strong>while</strong> loop, add the following function calls before <strong>move_turtle(line_length)</strong>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*wReCDBl7Sxs2hlLr" /></figure><p>→ t.Screen().update() : updates the screen.</p><p>→ t.Screen().listen() : starts listening for any keyboard event.</p><p>→ t.Screen().onkey(clear, “space”): calls the clear function whenever the spacebar key is pressed.</p><p>For a working solution, visit <a href="https://trinket.io/python/f9d175d220.">here</a>.</p><p>Note:</p><p>There are two ways of using the turtle library:</p><ol><li>Procedure-oriented interface: provides functions that are derived from the methods of the classes Screen and Turtle. It uses a pen and a canvas which are automatically created when any of the functions are called.</li><li>Object-oriented interface: provides classes such as Turtle and Screen that can be used to create unique instances of each.</li></ol><p>For more details, visit this<a href="https://docs.python.org/3.3/library/turtle.html?highlight=turtle"> online documentation.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c0cca74afbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PIANO SIMULATION -2]]></title>
            <link>https://medium.com/@sabahat.usman.su/piano-simulation-2-5b696ff3a53e?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b696ff3a53e</guid>
            <category><![CDATA[sketch]]></category>
            <category><![CDATA[piano-simulation]]></category>
            <category><![CDATA[project-for-kids]]></category>
            <category><![CDATA[p5js]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Mon, 18 May 2020 22:48:31 GMT</pubDate>
            <atom:updated>2020-05-20T03:56:52.780Z</atom:updated>
            <content:encoded><![CDATA[<p>A p5.js Project Tutorial</p><blockquote>This tutorial is an extension to the Piano Simulation project. In this tutorial, we will learn how to add a tint effect to the piano keys whenever they are pressed.</blockquote><h3>PREREQUISITES</h3><ol><li>You should know some Javascript.</li><li>You should have access to the p5.js web editor or it should be locally installed on your system. <strong>Note: This tutorial uses the web editor. You can find it at : </strong><a href="https://editor.p5js.org/"><strong>https://editor.p5js.org</strong></a><strong> . Make sure you log in or sign up for a free account to be able to use most of the editor’s features.</strong></li><li>You should have completed the Piano Simulation<a href="https://medium.com/@sabahat.usman.su/piano-simulation-58c0d9f6834e"> project.</a></li></ol><h3>LET’S DO THIS!</h3><h4><strong>1. Create a variable</strong></h4><p>Let’s create an empty variable called key_pressed. This variable will keep track of the current key that is pressed.</p><pre>var key_pressed;</pre><p>Initialise key_pressed to -1 inside of the setup() function.</p><pre>function setup()<br>{<br>   ...</pre><pre>   key_pressed = -1;</pre><pre>   ...<br>}</pre><h4>2. Update the value of the variable whenever a key is pressed</h4><p>Inside of the mousePressed() function, we will update the value of the variable key_pressed to the value of the key that has been pressed. Our first key has the value of 1 and the second has 2 and so on.</p><pre>function <strong>mousePressed</strong>()<br>{<br> <em>//first key</em><br> if (mouseX &gt; 55 &amp;&amp; mouseX &lt; 75 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> { <br>   key_pressed = 1;<br>   a1.play();<br> }<br> <em>//second key </em><br> if (mouseX &gt; 75 &amp;&amp; mouseX &lt; 95 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br>   key_pressed = 2;<br>   b1.play();<br> }<br> <em>//third key</em><br> if (mouseX &gt; 95 &amp;&amp; mouseX &lt; 115 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br>   key_pressed = 3;   <br>   c2.play();<br> }<br> <em>//fourth key</em><br> if (mouseX &gt; 115 &amp;&amp; mouseX &lt; 135 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br>   key_pressed = 4;   <br>   d2.play();<br> }<br> <em>//fifth key</em><br> if (mouseX &gt; 135 &amp;&amp; mouseX &lt; 155 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br>   key_pressed = 5;<br>   e2.play();<br> }<br> <em>//sixth key</em><br> if (mouseX &gt; 155 &amp;&amp; mouseX &lt; 175 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br>   key_pressed = 6;<br>   f2.play();<br> }<br> <em>//seventh key</em><br> if (mouseX &gt; 175 &amp;&amp; mouseX &lt; 195 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br>   key_pressed = 7;<br>   g2.play();<br> }<br>}</pre><h4>3. Set key_pressed back to -1 when mouse button is released</h4><p>We will override a built in function called mouseReleased(). In here, we will simply reset the value of key_pressed to -1.</p><pre>function <strong>mouseReleased()</strong><br>{<br>   key_pressed = -1;<br>}</pre><h4>4. Tint the pressed key</h4><p>Inside our draw() function, we have a for-loop that draws the rectangles representing the piano keys. Before we want any of our keys to be drawn, we want to check the value of the variable key_pressed. If key_pressed is equal to a key, we will set the pen color to grey so that the particular key is drawn in grey. As soon as the mouse is released, key_pressed is set to -1 and the key is drawn in white.</p><pre>function <strong>draw()</strong><br>{ <br>  ...</pre><pre>  for (let i = 1; i &lt;= 14; i++)<br>  {<br>    if(key_pressed === i)<br>       fill(201)<br>    else<br>      fill(255)<br>   <br>    rect(x,y,w,h);<br>    x = x + 20;<br>  }</pre><pre>}</pre><p>This is how we can add a tint effect to the piano keys. To see a working solution, visit <a href="https://editor.p5js.org/Sabahat70/sketches/p3kKK8BKM">here</a>.</p><p>Note: If you have any questions, please leave them in the response section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b696ff3a53e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PIANO SIMULATION]]></title>
            <link>https://medium.com/@sabahat.usman.su/piano-simulation-58c0d9f6834e?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/58c0d9f6834e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[piano-simualtion]]></category>
            <category><![CDATA[music-simualation]]></category>
            <category><![CDATA[p5js]]></category>
            <category><![CDATA[project-for-kids]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Mon, 18 May 2020 19:11:23 GMT</pubDate>
            <atom:updated>2020-05-20T03:56:21.631Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A </em><strong><em>p5.js</em></strong><em> Project Tutorial</em></p><blockquote>OVERVIEW</blockquote><blockquote><strong>p5.js</strong> is a creative coding javascript library based on the idea of sketching. In this tutorial, I will use this library to create a piano simulation.</blockquote><h3>PREREQUISITES</h3><ol><li>You should know some Javascript.</li><li>You should have access to the p5.js web editor or it should be locally installed on your system. <strong>Note: This tutorial uses the web editor. You can find it at : </strong><a href="https://editor.p5js.org/"><strong>https://editor.p5js.org</strong></a><strong> . Make sure you log in or sign up for a free account to be able to use most of the editor’s features.</strong></li></ol><h3>LET’S GET STARTED!</h3><h3><strong>Login</strong></h3><p>Login to your p5.js web editor account. And open up a new <strong>sketch</strong>.</p><h3><strong>Designing the piano keyboard</strong></h3><p>A piano keyboard is typically black in color and has a rectangle shape. It has a small digital screen on the top front and many other controls such as volume, rhythm and sounds. The front lower part consists of keys that are white in color. Let’s try to draw it on our p5.js canvas.</p><ol><li>Set the pen color to black.</li></ol><pre>fill( 51 );</pre><p>2. Draw a rectangle. Pass the top left coordinate: x as 45 and y as 155. Pass width as 300 and height as 150.</p><pre>rect( 45 , 155 , 300 , 150);</pre><p>3. Set the pen color to green.</p><pre>fill( 0 , 128 , 0);</pre><p>4. Draw a small rectangle inside of the black rectangle at a little margin from the top and left. This rectangle will represent a digital screen that piano keyboards have. Pass the top left coordinate: x as 55 and y as 160. Pass width as 200 and height as 50.</p><pre>rect( 55 , 160 , 200 , 50 );</pre><p>5. Set the pen color to yellow.</p><pre>fill( 255 , 255 , 0 );</pre><p>6. Draw two circles next to the digital screen vertically aligned to each other. These two circles will represent some of the controls that you may find on a piano keyboard.</p><pre>circle( 280 , 170 , 20 , 20 );<br>circle( 280, 200 , 20 , 20 );</pre><p>7. Set the pen color to white.</p><pre>fill( 255 );</pre><p>8. Draw rectangles vertically aligned to each other. These rectangles will represent the keys of the piano keyboard. For this keyboard that we have drawn, we can draw at most 14 keys inside of it. Let’s first create a few variables called x , y, w and h where x and y will hold the top-left coordinates of the first rectangle and w and h will hold the width and height respectively.</p><pre>var x , y , w , h;</pre><p>9. Inside the setup() function, initialize the variables with the values as shown.</p><pre>function <strong>setup</strong>(){<br> createCanvas( 400 , 400 );<br> x = 55;<br> y = 230;<br> w = 20;<br> h = 70;<br>}</pre><p>10. To draw the rectangles, we will use a for-loop that will iterate from 1 to 14 each time drawing a rectangle and incrementing the value of x by value of w. The rest of the three values will remain the same as we want the rectangles to align horizontally with each other. We will do this inside of the draw() function.</p><pre>for (let i = 1; i &lt;= 14; i++)<br>{<br> rect(x , y , w , h);<br> x = x + w;<br>}</pre><p><strong>HOORAY! We are done drawing our piano! Now let’s make some sound!</strong></p><h3><strong>Download sound files.</strong></h3><p>You can search the internet for free piano key notes or you can download a few from my drive which I have used in this tutorial:</p><p><a href="https://drive.google.com/drive/folders/18GAKJLquQQco6g8JeFz_cIuswyC9wYNB?usp=sharing">https://drive.google.com/drive/folders/18GAKJLquQQco6g8JeFz_cIuswyC9wYNB?usp=sharing</a></p><h3><strong>Upload sound files.</strong></h3><p>On the code editor, you should see a file navigation pane on your left. Click on the drop down menu called Sketch Files. You should see an option to upload files. Click on it and an Upload File dialog box should pop up. Drop files into it. You can drop a certain number of files at a time. Repeat the process to upload the rest of the sounds. In this tutorial, we will be uploading 7 files.</p><h3><strong>Load the uploaded sounds into your code.</strong></h3><p>Once all the sounds are uploaded, you should see them in your file navigation pane. But you still can’t play them in our code. To be able to do that, we first need to load them into our project.</p><ol><li>Create empty variables to hold the sounds.</li></ol><pre>var a1 , b1 , c2 , d2 , e2 , f2 , g2;</pre><p>2. In the setup() function, we will call the loadSound() function a couple of times. The loadSound() function takes in a string that should be a path for a sound file.</p><p>Load each sound one by one and store them in their respective variables as shown.</p><pre>function <strong>setup</strong>() {<br> createCanvas(400, 400);<br> w = 20;<br> h = 70;<br> y = 230;<br> x = 55;<br> <br> a1 = loadSound(‘A1.mp3’);<br> b1 = loadSound(‘B1.mp3’);<br> c2 = loadSound(‘C2.mp3’);<br> d2 = loadSound(‘D2.mp3’);<br> e2 = loadSound(‘E2.mp3’);<br> f2 = loadSound(‘F2.mp3’);<br> g2 = loadSound(‘G2.mp3’);<br>}</pre><h3><strong>Play the sounds when the piano keys are pressed.</strong></h3><p>To do this, we will override the built in function called mousePressed(). Whenever the mouse is pressed, this function is called. Also the mouseX and mouseY variables are made available to us. These variables hold the coordinates of the point where the mouse has been clicked.</p><p>We will use the values of mouseX and mouseY to find out if their values lie inside of any of the keys and play the respective sound.</p><pre>function <strong>mousePressed</strong>()<br>{<br> <em>//first key</em><br> if (mouseX &gt; 55 &amp;&amp; mouseX &lt; 75 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> { <br> a1.play();<br> }<br><em>//second key </em><br> if (mouseX &gt; 75 &amp;&amp; mouseX &lt; 95 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br> b1.play();<br> }<br><em>//third key</em><br> if (mouseX &gt; 95 &amp;&amp; mouseX &lt; 115 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br> c2.play();<br> }<br><em>//fourth key</em><br> if (mouseX &gt; 115 &amp;&amp; mouseX &lt; 135 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br> d2.play();<br> }<br><em>//fifth key</em><br> if (mouseX &gt; 135 &amp;&amp; mouseX &lt; 155 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br> e2.play();<br> }<br><em>//sixth key</em><br> if (mouseX &gt; 155 &amp;&amp; mouseX &lt; 175 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br> f2.play();<br> }<br><em>//seventh key</em><br> if (mouseX &gt; 175 &amp;&amp; mouseX &lt; 195 &amp;&amp; mouseY &gt; y &amp;&amp; mouseY &lt; 300)<br> {<br> g2.play();<br> }<br>}</pre><p>This completes the piano simulation tutorial. You can add extensions to this project such as:</p><ol><li>Add sounds for the rest of the remaining keys.</li><li>Add a tint effect to the piano key that is pressed. To learn how to click <a href="https://medium.com/@sabahat.usman.su/piano-simulation-2-5b696ff3a53e">here</a>.</li></ol><p>If you have any questions, please leave them in the response section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58c0d9f6834e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterative Postorder Traversal of a Binary Tree]]></title>
            <link>https://medium.com/@sabahat.usman.su/iterative-postorder-traversal-of-a-binary-tree-9f7f397de767?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f7f397de767</guid>
            <category><![CDATA[example-traversal]]></category>
            <category><![CDATA[postorder-traversal]]></category>
            <category><![CDATA[morris-algo]]></category>
            <category><![CDATA[iterative]]></category>
            <category><![CDATA[binary-tree]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Wed, 13 May 2020 21:02:34 GMT</pubDate>
            <atom:updated>2020-05-18T20:41:20.047Z</atom:updated>
            <content:encoded><![CDATA[<h3>Explanation: Iterative Postorder Traversal of a Binary Tree</h3><p>Morris Algorithm in Javascript</p><blockquote>Understanding someone else’s code or algorithm is usually challenging. When I first read the Morris Postorder Traversal algorithm, it just went through my head. So I decided to take an example binary tree and walk myself through the algorithm step by step in order to understand what exactly was happening.</blockquote><blockquote>We already know that postorder traversal means traversing the tree and visiting the nodes in the order left node, right node and then the root node. Let’s traverse through an example binary tree using the algorithm.</blockquote><p>Example binary tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*QnZ-hwL9vv3G79-r" /></figure><h3>[ 5, 3, 6, 2, 4]</h3><p>Let’s start!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*_WnqoscQCinluVG5" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*2LNxub-XDz2oBZTO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*wdKC7hr3UvH_1sn5" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*bIg_cLGAcX0amG2k" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*4Hyt1NpBqR-DPdj1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*MaUuNnQPoSA9yPF_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*A-1Xo_WJ0kxL4PMl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*Elcn4NzFVoKhxoD_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*kgS65JBt5UJGie-K" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*kemahFLxCqT_wRMq" /></figure><p>The postorder sequence of this binary tree is stored in an array called <em>arr</em> and returned when the stack is empty in this case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f7f397de767" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flood Fill — LeetCode]]></title>
            <link>https://medium.com/@sabahat.usman.su/flood-fill-leetcode-63507413c472?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/63507413c472</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flood-fill]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Tue, 12 May 2020 05:04:23 GMT</pubDate>
            <atom:updated>2020-05-12T05:04:23.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flood Fill — LeetCode</h3><p>Solution in Javascript</p><pre>var floodFill = function(image, sr, sc, newColor) <br>{<br>   let originalColor = image[sr][sc];</pre><pre>   if (originalColor === newColor ) return image;</pre><pre>   dps(image,sr,sc,originalColor,newColor);</pre><pre>   return image;<br>};</pre><pre>var dps = function(image,i,j,originalColor, newColor)<br>{<br>   if (i &lt; 0 || i &gt;= image.length || j &lt; 0 || j&gt;=image[i].length ||      image[i][j] !== originalColor)<br>   return;</pre><pre>   if (image[i][j] === originalColor)<br>     image[i][j] = newColor;<br> <br>   dps(image,i-1, j,originalColor,newColor);<br>   dps(image,i+1, j,originalColor,newColor);<br>   dps(image,i, j-1,originalColor,newColor);<br>   dps(image,i, j+1,originalColor,newColor);<br> <br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63507413c472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Valid Perfect Square — LeetCode]]></title>
            <link>https://medium.com/@sabahat.usman.su/valid-perfect-square-leetcode-6a6bf47adb4b?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a6bf47adb4b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nologs]]></category>
            <category><![CDATA[valid-perfect-square]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[binary-search]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Sun, 10 May 2020 03:17:39 GMT</pubDate>
            <atom:updated>2020-05-10T03:17:39.605Z</atom:updated>
            <content:encoded><![CDATA[<h3>Valid Perfect Square — LeetCode</h3><p>Solved using binary search in Javascript</p><pre>var isPerfectSquare = function(num) {<br> <br> let start = 1;<br> let end = num;<br> <br> while(true)<br> {<br>   let midpoint = parseInt((start+end)/2);<br>   let product = midpoint * midpoint;<br> <br>   if (product === num) return true;<br> <br>   else if( product &gt; num )<br>   {<br>     end = midpoint — 1;<br>   }<br>   else start = midpoint + 1;<br> <br>   if (start &gt; end) return false;<br> }<br> <br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a6bf47adb4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterative Postorder Traversal of a Binary Tree]]></title>
            <link>https://medium.com/@sabahat.usman.su/iterative-postorder-traversal-of-a-binary-tree-e69ac30e7cf6?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/e69ac30e7cf6</guid>
            <category><![CDATA[morris-algorithm]]></category>
            <category><![CDATA[iterative]]></category>
            <category><![CDATA[postorder-traversal]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[binary-tree-traversal]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Wed, 06 May 2020 17:52:06 GMT</pubDate>
            <atom:updated>2020-05-13T21:04:05.659Z</atom:updated>
            <content:encoded><![CDATA[<p>Code for Morris’s Algorithm in Javascript</p><pre>const postorderTraversal = function(root)<br>{<br>   let arr = [];<br>   let stack = [];<br>   let p = root;<br>   let q = root;</pre><pre>   while( p )<br>   {<br>      while( p.left )<br>      {<br>         stack.unshift(p);<br>         p = p.left;<br>      }</pre><pre>      while ( !p.right || p.right === q )<br>      {<br>         arr.push(p.val);<br>         q = p;<br>         if ( stack.length === 0 ) return arr;<br>         p = stack.shift();<br>      }<br>      <br>      stack.unshift(p);<br>      p = p.right;<br>   }</pre><pre>   return arr;<br>}</pre><pre>/* Definition of a Binary Tree Node */<br>    /* Borrowed From LeetCode */</pre><pre>/* <br>   const TreeNode = function(val,left,right)<br>   {<br>     this.val = (val===undefined ? 0 : val)<br>     this.left = (left===undefined ? null : left)<br>     this.right = (right===undefined ? null : right)<br>   } <br>*/ </pre><p>For further understanding visit: <a href="https://medium.com/@sabahat.usman.su/iterative-postorder-traversal-of-a-binary-tree-9f7f397de767?sk=af9a0a2972c89fc5fe70569ecb949e73">https://medium.com/@sabahat.usman.su/iterative-postorder-traversal-of-a-binary-tree-9f7f397de767?sk=af9a0a2972c89fc5fe70569ecb949e73</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e69ac30e7cf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ways to Write Functions in Javascript]]></title>
            <link>https://medium.com/@sabahat.usman.su/ways-to-write-functions-in-javascript-311bc352b686?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/311bc352b686</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[function-javascript]]></category>
            <category><![CDATA[expression-vs-declaration]]></category>
            <category><![CDATA[function-declaration]]></category>
            <category><![CDATA[function-expression]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Tue, 05 May 2020 05:27:46 GMT</pubDate>
            <atom:updated>2020-05-05T06:52:48.973Z</atom:updated>
            <content:encoded><![CDATA[<p>A Quick Look Up</p><p>There are two main ways of writing functions in javascript:</p><ol><li>As a declaration</li></ol><pre><strong>function</strong> <em>identifier</em>() {...}</pre><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*gpEyiAopjv4NZ8vukgO_cg.png" /></figure><p>A function declaration has a signature that starts with the keyword<strong><em> function</em></strong> followed by an identifier and a pair of parenthesis. The body of the function comes inside of the curly brackets.</p><p>2. As an expression (called anonymous functions)</p><pre><strong>const|var|let</strong> <em>identifier</em> = <strong>function</strong>() {…}</pre><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*70muDn7-ZtX11jv9JJyWjA.png" /></figure><p>Since we know that a function evaluates to a value, it can be assigned to a variable in this manner. These functions are also called anonymous functions as they do not need a name. To call an anonymous function, we use the name of the variable it has been assigned to.</p><p>Anonymous functions can also have a name; however, you may not be able to call it by that name from outside of the function and if you try to call it, it will give you an error. You can however use the name of your function within the function itself (called <strong>recursion</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFFXa2kNFdzBg_WOiavQNA.png" /></figure><p>Thus, function declarations and function expressions are syntactically identical to each other just that functions written as expressions need not have a name.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=311bc352b686" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coin Collector]]></title>
            <link>https://medium.com/@sabahat.usman.su/coin-collector-2bb27c0a84e2?source=rss-48c6a8ff055------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bb27c0a84e2</guid>
            <category><![CDATA[python-turtle]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[games-using-python-turtle]]></category>
            <category><![CDATA[trinket]]></category>
            <category><![CDATA[project-for-kids]]></category>
            <dc:creator><![CDATA[Sabahat Usman]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 03:39:22 GMT</pubDate>
            <atom:updated>2020-04-30T03:39:22.902Z</atom:updated>
            <content:encoded><![CDATA[<p>A Python Game with <strong>Turtle graphics</strong></p><blockquote>I teach kids how to code. And I try my best to make it fun and easy for them. I recently discovered that the turtle module can be used to create animations. So I rewrote a game called Coin Collector taken from the book, <strong>Coding Games in Python by DK</strong>, using the turtle. The book, however, teaches how to create games using <strong>Pygame Zero</strong>. Pygame Zero is not yet available in any of the existing online platforms and its installation process is a little tricky for the kids.</blockquote><h4>Prerequisites</h4><ul><li>Should have some knowledge of the Python programming language and Turtle graphics.</li></ul><h4>Platforms</h4><ul><li>(Recommended) Any online platform such as: <strong>trinket </strong><a href="https://trinket.io/">https://trinket.io</a> or <strong>repl.it </strong><a href="https://repl.it/">https://repl.it</a> , that supports Python and the turtle module.</li><li>Python IDLE that comes with Python installation or any other preferred IDE or Editor installed on your local machine. Make sure you have the turtle module installed as well.</li></ul><h4>Notes</h4><ul><li>Steps for Python installation are not covered in this tutorial.</li><li>The tutorial uses the <strong>trinket</strong> platform for writing code.</li></ul><h4><strong>Game Overview</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*ITZr7FtUYPWGj8LV" /></figure><p><em>In this game, a fox (player) has to collect coins within a given time. A coin appears at a random position on screen. The fox can be controlled using the arrow keys. Whenever the fox touches the coin, the score is incremented by 10 and the coin moves to another position. When the timer reaches zero, the game ends.</em></p><p>Let’s start building!</p><ol><li>Create a new <strong>trinket </strong>Python project.</li><li>Import three modules: turtle, random and time.</li></ol><pre>#imports<br>import turtle<br>import random<br>import time</pre><p>3. Instantiate a Screen object from the turtle Screen class and store it into a variable named screen.</p><pre>#screen<br>screen = turtle.Screen()</pre><p>4. Turn off the tracer by passing 0 as an argument to the screen.tracer() method.. This will stop the screen from automatically refreshing or updating.</p><pre>screen.tracer(0)</pre><p>5. Download images of a fox(fox.png) and a coin(coin.png) from this link: <a href="https://www.dk.com/uk/information/computer-coding/">https://www.dk.com/uk/information/computer-coding/</a> or you can use any other images you would like.</p><p>6. Upload these images into your trinket’s image library by clicking on the <strong>View and Add Images</strong> button at the right most corner of your code editor’s navigation bar. After uploading the images, make sure you select them so that they can be accessed by your code.</p><p>7. To use these images for our turtles, we will need to add them to the screen’s shapelist as shown below:</p><pre>screen.addshape(“fox.png”)<br>screen.addshape(“coin.png”)</pre><p>8. Create a global variable named <em>score</em> and initialize it to 0. Place it after the import statements.</p><pre>#global variables<br>score = 0</pre><p>9. Create a turtle dedicated for displaying and updating the score.</p><pre>#score turtle<br>scoreTurtle = turtle.Turtle() #instantiates a Turtle object from the Turtle class into scoreTurtle<br>scoreTurtle.hideturtle() #hides the turtle.<br>scoreTurtle.penup() #stops the turtle from drawing a line whenever moving.<br>scoreTurtle.goto(-130,180) # moves the turtle to the top left corner of the screen.<br>scoreTurtle.write(“Score:{}”.format(score) ,align=”center”, font=(“Courier”,15,”normal”)) #writes the score.</pre><p>Note: The <strong>write()</strong> method takes in three arguments. The first argument is a string that contains a text, “Score: {}”, and the <strong>format()</strong> method called on it . The score variable is passed as an argument to the format() method and the curly brackets act as a placeholder for the score variable. This means that the curly brackets will be replaced by the value of score which is 0 at this moment. The second and third arguments set the align and font properties.</p><p>10. Create another global variable called timelimit and set it to 30.</p><pre>#global variables<br>score = 0<br>timelimit = 30</pre><p>11. Create a turtle dedicated for displaying and updating the timer.</p><pre>#timer turtle<br>timer = turtle.Turtle() #instantiates a Turtle object from the Turtle class.<br>timer.hideturtle() #hides the turtle<br>timer.penup() #stops the turtle from drawing a line whenever moving<br>timer.goto(130,180) #moves the turtle to the top right corner of the screen<br>timer.write(“Timer: {}”.format(timelimit), align =”center”, font=(“Courier”,15,”normal”)) #displays the time limit</pre><p>12. Run your code to see if everything is working as expected.</p><p>13. Create a turtle to be the player fox.</p><pre>#player fox turtle<br>fox = turtle.Turtle() # instantiates a Turtle object from the Turtle class into fox<br>fox.addshape(‘fox.png’) # sets the shape of the turtle to fox.png<br>fox.penup() # stops the turtle from drawing a line whenever moving<br>fox.speed(0) # sets the turtle’s speed to ‘fastest’<br>fox.setheading(90) # set initial direction facing to the right</pre><p>14. Add functions to control fox movements: up, down, right and left.</p><pre>def moveUp():<br> fox.forward(5) </pre><pre>def moveDown():<br> fox.backward(5)</pre><pre>def moveRight():<br> x = fox.xcor() # gets the x coordinate of fox’s position<br> fox.setx(x + 5)# increments the x coordinate of fox’s position by 5</pre><pre>def moveLeft():<br> x = fox.xcor() # gets the x coordinate of fox’s position<br> fox.setx(x — 5) # decrements the x coordinate of fox’s position by 5</pre><p>15. Bind the fox’s movement functions with keyboard arrow keys.</p><pre>#keyboard bindings<br>screen.listen() #starts listening for keyboard events<br>screen.onkey(moveUp,”up”) #calls the moveUp() function whenever the up arrow key is pressed.<br>screen.onkey(moveDown, “down”) #calls the moveDown() function whenever the down arrow key is pressed.<br>screen.onkey(moveRight, “right”) #calls the moveRight() function whenever the right arrow key is pressed.<br>screen.onkey(moveLeft, “left”) #calls the moveLeft function whenever the left arrow key is pressed.</pre><p>16. Create a turtle to be the coin object.</p><pre>#object coin turtle<br>coin = turtle.Turtle() #instantiates a Turtle object from the Turtle class into the variable, coin.<br>coin.shape(“coin.png”) # sets the shape of the coin turtle to coin.png<br>coin.penup() # stops the turtle from drawing a line whenever moving<br>coin.speed(0) # sets the turtle’s speed to ‘fastest’<br>x = random.randint(-180,180) # get a random number between -180 and 180<br>y = random.randint(-180,160) # get a random number between -180 and 160<br>coin.goto(x,y) # place the coin at (x, y)</pre><p>Note: We use the <strong>randint() </strong>function of the random module to generate random values and we pass it a range. We chose the above ranges because we want our coin to be placed within the screen boundaries. The screen’s (0,0) coordinates lie in the center and the screen size is (400,400).</p><p>17. If you run the program at this point, you might not see the fox moving when you press the arrow keys. This is because we have not yet called the screen.update() function anywhere in the code to actually update the screen and show the fox’s updated positions. We need some kind of logic that can refresh the screen for an infinite amount of time until the game ends. Let’s add the screen.update() function inside of an infinite while loop to achieve our purpose. This is also going to be the loop where we will add rest of the game logic.</p><pre>#main game loop<br>while True:<br> screen.update() #refreshes the screen</pre><p>Now when you run the program, you should be able to see the fox move whenever you press the arrow keys.</p><p>18. Add collision detection between fox and coin by taking the help of the <strong>distance() </strong>method. Call the distance() method on the fox turtle and pass the coin turtle as an argument to it. Whenever the distance between the two is less than 30, that suggests a collision. When collision happens, place the coin in a new randomly generated position on screen and also increment the score by 10. Also update the score display.</p><pre>#main game loop<br>while True:<br> screen.update() # refresh the screen<br> if fox.distance(coin) &lt; 30: # checks if fox and coin are less than 30 steps away<br> x = random.randint(-180,180) # gets a random number between -180 and 180<br> y = random.randint(-180,160)# gets a random number between -180 and 160<br> coin.goto(x,y) # places the coin at (x, y)<br> score = score + 10 # increments the score by 10<br> scoreTurtle.clear() # deletes turtle’s previous writing<br> scoreTurtle.write(“Score:{}”.format(score) ,align=”center”,<br> font =(“Courier”,15,”normal”) # sets the current score</pre><p>19. Add the countdown timer logic. First create a global variable named startTime and assign it the value of <strong>time.time()</strong>. This way we will be storing the time our game begins.</p><pre>#global variables<br>score = 0<br>timelimit = 30<br>startTime = time.time()</pre><p>20. Second, inside of your main game loop, calculate the time elapsed by subtracting the startTime from the current time which we can get by calling <strong>time.time()</strong> again. Store the result in a variable called timeElapsed. We also need to convert the result into an integer as the time.time() function returns a floating point value.</p><pre>#countdown<br>timeElapsed = int(time.time() — startTime)</pre><p>21. Third, update the timer display. Since we are counting down, we will have to subtract the timeElapsed values from the timelimit.</p><pre>timer.clear() # deletes turtle’s previous writing<br>timer.write(“Timer: {}”.format(timelimit — timeElapsed), align =”center”, font =(“Courier”,15 “normal”)</pre><p>22. Third, check if the value of timeElapsed is greater than or equal to the timelimit. If yes, then break the while loop.</p><pre>#end game<br>if timeElapsed &gt;= timelimit:<br> break;</pre><p>23. Here is a working solution of the game in trinket: <a href="https://trinket.io/python/60ee536d64">https://trinket.io/python/60ee536d64</a></p><p><strong>Challenges:</strong></p><ol><li>Display a game over message before breaking the loop. Make sure you add a call to screen.update() where required.</li><li>The fox can go out of screen boundaries. Can you make sure the fox stays within the screen?</li></ol><h4>References:</h4><ol><li>2018.Coding Games IN PYTHON.DK.</li><li><a href="https://docs.python.org/3/library/turtle.html">https://docs.python.org/3/library/turtle.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bb27c0a84e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>