<?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 Max Knivets on Medium]]></title>
        <description><![CDATA[Stories by Max Knivets on Medium]]></description>
        <link>https://medium.com/@maxknivets?source=rss-9440dabc71af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iEeDVX3LkY3ytj-205uvYQ.jpeg</url>
            <title>Stories by Max Knivets on Medium</title>
            <link>https://medium.com/@maxknivets?source=rss-9440dabc71af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:14:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maxknivets/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[Pygame tutorial #5: bare and minimalistic event editor. Adding clickability to the game.]]></title>
            <link>https://medium.com/@maxknivets/pygame-tutorial-5-bare-and-minimalistic-event-editor-adding-clickability-to-the-game-eebec6af546d?source=rss-9440dabc71af------2</link>
            <guid isPermaLink="false">https://medium.com/p/eebec6af546d</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pygame]]></category>
            <dc:creator><![CDATA[Max Knivets]]></dc:creator>
            <pubDate>Tue, 08 May 2018 20:37:16 GMT</pubDate>
            <atom:updated>2019-04-12T12:13:56.910Z</atom:updated>
            <content:encoded><![CDATA[<p>In previous tutorial we separated values and functions from the game, now that we got that out of the way, we’ll create an event manager, that easily calls functions when the mouse is clicked.</p><p>So when I first created a function that displays a message when clicked on the screen, it looked like this:</p><pre>if event.type == pygame.MOUSEBUTTONDOWN:<br>    image_display(screen, &#39;mount.jpg&#39;, (0,0))<br>    large_text_display(*normal_message, text)</pre><p>Simple enough, right? But since we’re aiming to create a novel game, there needs to be clickability. Every time you click, a new frame appears. Which makes us think outside the box.</p><p>Since function calls (in our case) cannot be stored, we need to create another function that handles this.</p><pre>def perform(lst):<br>    lst[0](*lst[1:len(lst)])</pre><p>This code calls a function (like message_display) and passes it all arguments. So you can basically call any function we’ve defined earlier, and store the function call.</p><p>Alright, that’ll do. Try calling it, should work.</p><pre>perform([image_display, screen, (231,100), &#39;pandas.jpg&#39;])<br>perform([large_text_display, screen, white, pygame.Rect(1366,168,600,0),freemono,40,[1366,168,lightblue,120], &quot;Aww, so cute!&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypj8jhoKK1L0uERJ7NkF1Q.png" /><figcaption>So cool!</figcaption></figure><p>This is not how we’re going to create frames in this tutorial. We’ll be storing the values in a list which contains all the events. Here’s how I imagined this list structure:</p><pre>[ # start of the whole game<br>[ # start of the frame <br>[function_call_with_fixed_args, our_args],[another_function_call_with_fixed_args, our_args]<br>] # end of the frame<br>] # end of the whole game</pre><p>The first level, which is the base of the game, is where all the events will happen throughout the entire game. Then comes the second level, which are all the events that will happen in a specific frame. And finally, the third level is where the event is stored.</p><p>Let’s insert previously defined function in a for-loop:</p><pre>for action in events[curr_event]:<br>    perform(action)</pre><p>Add this after <strong>all</strong> of the Pygame’s checks are done, or it might lag.<br>Oh, I also forgot to mention the curr_event variable, which helps to jump through the frames. The for-loop iterates inside a specific frame, easily displaying everything there is to display in that frame. Create the variable at the start of the main function, and add this condition:</p><pre>if event.type == pygame.MOUSEBUTTONDOWN:<br>    curr_event += 1</pre><p>This is how your events list should look like:</p><pre>events = [<br> [[large_text_display, *normal_message,text],[image_display, screen,(0,0),&#39;pandas.jpg&#39;]],<br> [[large_text_display, *not_normal_message,text2],[image_display, screen,(0,0),&#39;pandas.jpg]]<br>]</pre><p>Now, create your own list using this one as an example, and run the code. (And don’t forget to add a screen.fill(white) before the <strong>for-loop</strong> to erase the previous screen when the new one is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjA5fx5wX32yW6jSglDgnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTdKDTAtGCOZsODLBNxwwQ.png" /></figure><p>Wow, now that looks awesome. Still, you wouldn’t like to write events manually. Now, let’s write a few functions that do that automatically.</p><pre>def create_event(func, args):<br>    return func + [args]</pre><pre>def new_frame(events,*acts):<br>    events.append([*acts])</pre><p>The first function creates an event, when passed a function name and its arguments. The second one creates a whole frame when passed all events.<br>Keep in mind that the first “events” argument is not a list of frames you pass. It’s simply the original events list. And you can pass that function events, without even inserting them into a list.</p><p>Alright, let’s try using these functions out.</p><pre>image = frame(image_display, screen, (0,0), &#39;pandas.jpg&#39;])<br>text = frame(text_display, *normal_message, &#39;Wow, that\&#39;s super short!&#39;)<br>newframe(events, image, text)</pre><pre>image = frame(image_display, screen, (0,0), &#39;pandas.jpg&#39;])<br>text = frame(text_display, *normal_message, &#39;Absolutely amazing!&#39;)<br>newframe(events, image, text)</pre><p>This is super short! As you may have noticed, we used the same image to create a scene, yet spent 6 lines of code. Let’s simplify the code once more.</p><pre>def scene(events, img_list, img_name, text_list, text):<br>    img_frame = frame(img_list, img_name)<br>    text_frame = frame(text_list, text)<br>    new_frame(events, img_frame, text_frame)</pre><p>This is how the list of arguments should look like:</p><pre>image_vars = [image_display, screen, (0,0)]<br>background1 = [events, image_vars, ‘pandas.jpg’]</pre><p>Why did we create background1 variable when we could create a large one instead? Well, you probably don’t want to have one fixed background the whole game. But when creating another background, you’d assign a large variable. This makes it easier to create new backgrounds.</p><p>At this point, you can create a new frame with just <strong>ONE </strong>line! That’s incredibly short! Just look for yourself!</p><pre>scene(*background1, normal_message, &quot;Wow, that&#39;s even shorter!&quot;)<br>scene(*background1, not_normal_message, &quot;Incredible!&quot;)</pre><p>Mind-blowing! At this point, we can create a novel with a linear plot! But there’s still a lot to be done, like buttons, choices, music and other stuff!</p><p><strong>Extra stuff:</strong></p><p>There’s a thing that I didn’t include in my tutorials, which is a shape() function.<br>shape() function sizes text properly inside the dialog window. Without this function, the text would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEC58qCOIQqQhNy-ZLoLug.png" /><figcaption>something like that.</figcaption></figure><p>It’s not vital, but still good to have:</p><pre>def shape(x, y, xspace=0, yspace=0):<br>    return [x+xspace, y+yspace, (size[0] — (x*2)), (size[1] — y)]</pre><p>The function returns a list of arguments to pass the pygame.Rect function.</p><p>This is pretty much it for this tutorial. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eebec6af546d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pygame tutorial #4: separating functions and values from the actual game.]]></title>
            <link>https://medium.com/@maxknivets/pygame-tutorial-4-separating-functions-and-values-from-the-actual-game-84a74660297b?source=rss-9440dabc71af------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a74660297b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[pygame]]></category>
            <dc:creator><![CDATA[Max Knivets]]></dc:creator>
            <pubDate>Thu, 03 May 2018 19:10:36 GMT</pubDate>
            <atom:updated>2019-04-12T11:47:24.636Z</atom:updated>
            <content:encoded><![CDATA[<p>In previous tutorial I wrote functions that render images and draw backgrounds for the text. I think it’s time to arrange the code properly.</p><p><em>(I do realize that this tutorial is very short, but this issue had to be addressed in a separate article.)</em></p><p>If you’ve been writing everything in one file during the tutorials, you might have noticed that the file is somewhat big now. Values and functions take up a lot of space, so let’s sort them with writing new files. Just create “values.py” and “code.py” files beside the main python file you used to write the code in. Then paste the functions into code.py and all values (like normal_message) into values.py.</p><p>Don’t forget to import and initialize the Pygame module in those files, or else it won’t work! Also, you’ll need to add the search_font() function to the values.py file in order for that file not to return an error (if you have any font variables there). Additionally, add the size = (1366,768) variable to code.py file, since there are functions that require this variable.</p><p>Now, importing the stuff.</p><p>It’s pretty simple, you just type:</p><pre>from values import *<br>from code import *</pre><p>This imports <strong>everything</strong> from the files. It also creates a __pycache__ folder, which helps python function better. If you try to delete it, it’ll reappear after executing the code again. So don’t bother trying to erase it, or adding any flags that might stop python from doing so, as it’ll hurt the code’s performance.</p><p>This is it for this tutorial. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a74660297b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pygame tutorial #3: rendering images, drawing background for the text.]]></title>
            <link>https://medium.com/@maxknivets/pygame-tutorial-3-rendering-images-drawing-background-for-the-text-573d028e9a7a?source=rss-9440dabc71af------2</link>
            <guid isPermaLink="false">https://medium.com/p/573d028e9a7a</guid>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Max Knivets]]></dc:creator>
            <pubDate>Wed, 02 May 2018 21:52:16 GMT</pubDate>
            <atom:updated>2019-04-12T11:22:36.378Z</atom:updated>
            <content:encoded><![CDATA[<p>In previous tutorial I explained how message display function works and how it’s written. Now, we’ll be writing a function that renders images, and draws a background for our text.</p><p>Rendering images is quite straightforward, and all it requires is to load the image and add it to the surface. Simple and easy enough.</p><pre>def image_display(surface, filename, xy):<br>    img = pygame.image.load(filename)  <br>    surface.blit(img, xy)</pre><p>Pygame supports a dozen of image extensions, like these:</p><p>JPG, PNG, GIF, BMP, PCX, TGA, TIF, LBM, PBM, XPM.</p><p>If you want to easily access the images in your game, put them in the same folder where your python script is executed. This allows us to display image using only the filename of the file instead of the full path to it:</p><pre>image_display(surface, &quot;mountains.jpg&quot;, [0,0])</pre><p>Now, let’s get to drawing the background.</p><p>In point&amp;click/novel games, the text is usually displayed in dialog boxes with a background. Let’s take “Doki Doki Literature Club!” for instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0kWODvqKTIEct_-W.png" /></figure><p>The function that draws rectangles is pygame.draw.rect()<em>. </em><br>Please note, that we’ll be using <a href="https://medium.com/@maxknivets/pygame-tutorial-2-1-precise-text-wrapping-method-68576b43ec92">this</a> function in order to render text. If you’re unfamiliar with it, I suggest you reading the previous part of the tutorial.</p><pre>def message_display(surface, color, rect, font_name, text_size, text, rect_draw=False, text_rect=False, aa=False):<br>    if rect_draw:<br>         pygame.draw.rect(surface, color, text_rect)<br>...</pre><p>text_rect argument requires 4 values: width&amp;height of the rectangle, and X&amp;Y position of the rectangle. Here’s a list of arguments for the background we are going to use throughout this tutorial: [1366,168,0,600]. Let’s fill the lower part of the screen with white color.</p><p>message_display(*normal_message, &quot;Ah mountains. The nature is truly beatiful.&quot;, True, [1366,168,0,600])</p><p>Here’s the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I90BHIA3_eyc60Z6Ln4HeQ.png" /><figcaption>Oh shoot. I forgot that the color is white for both the text and the rectangle!</figcaption></figure><p>Let’s fix it a little bit…</p><pre>...<br>    if rect_draw:<br>         pygame.draw.rect(surface, rect_draw, text_rect)</pre><p>Yes, we will pass a color instead of True/False via the rect_draw variable. This is a good solution, but probably renaming the rect_draw argument would make it prettier.<br>Time to give the function another try!</p><p>message_display(*normal_message, &quot;Ah mountains. The nature is truly beatiful.&quot;, (0,0,0), [1366,168,0,600])</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhRjJ_WA1BQVmGF3fVfJjQ.png" /><figcaption>Well, now it works!</figcaption></figure><p>Let’s add an image now. Just google “Mountain wallpapers 1366x768”, and render it at 0,0 XY.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmMWZrEbDqRyGDTPJ0RFBA.png" /><figcaption>Looks alright.</figcaption></figure><p>This looks a lot better, but as you can see, the background is not transparent. You might wonder what’s the problem with making the rectangle transparent, as it is easy enough to add an “alpha” value to the color we’re using. But the problem is that, we cannot draw transparent rectangles, even when adding another “alpha” value. <a href="https://stackoverflow.com/questions/6339057/draw-a-transparent-rectangle-in-pygame/6350227#6350227">Gustavo</a> clearly says that there’s no way to do so, but to create another surface, set its transparency to a specific value, and then add to our main surface. Here’s how I’ve done it:</p><pre>if bkglist:<br>    # bkglist[0] - width of the background, bkglist[1] - height of the background, bkglist[2] - color, bkglist[3] - transparency value</pre><pre>    surf = pygame.Surface((bkglist[0], bkglist[1]), pygame.SRCALPHA)<br>    surf.fill((*bkglist[2], bkglist[3]))<br>    surface.blit(surf, (round((bkglist[0] - bkglist[0])/2),(size[1] - bkglist[1])))</pre><p>Quick breakdown on this piece of code: you pass a list of values, where the first 2 are width and height of the surface, then the color, and finally, transparency value. The less the transparency value the more it’s transparent. The minimum value is 0, which is 100% transparent, and the maximum is 255, which is, as you may have guessed, not transparent at all.</p><p>The first line creates a surface. Then, it fills the surface with the specified color and sets its transparency. And finally, the surface is added to the main surface. <br>Also, the calculations at the end are made to render the rectangle at a proper X&amp;Y position.<br>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zPvaUE39De1xG9fuaqjZA.png" /><figcaption>Now that looks amazing!</figcaption></figure><p>At this point, the project begins to take great shape! The only thing it lacks is clickability and music, and we could proudly call it a game!</p><p>This is it for this tutorial. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=573d028e9a7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pygame tutorial #2.1: Precise text wrapping method.]]></title>
            <link>https://medium.com/@maxknivets/pygame-tutorial-2-1-precise-text-wrapping-method-68576b43ec92?source=rss-9440dabc71af------2</link>
            <guid isPermaLink="false">https://medium.com/p/68576b43ec92</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Max Knivets]]></dc:creator>
            <pubDate>Fri, 20 Apr 2018 20:17:25 GMT</pubDate>
            <atom:updated>2019-04-12T11:39:49.311Z</atom:updated>
            <content:encoded><![CDATA[<p>In previous tutorial I described how to wrap text, which wasn’t precise enough and had problems that couldn’t be solved. Now that I have finally comprehended the code I found, I can explain how it works.</p><p><em>Link to the code: </em><a href="https://www.pygame.org/wiki/TextWrap"><em>https://www.pygame.org/wiki/TextWrap</em></a><em>.</em></p><p>The first thing that had to be done is changing a few characters in the code, as it clearly says:</p><blockquote><strong>WARNING!</strong> When copy/pasting this code, you will need to change “&amp;lt;” to the “&lt;” symbol.</blockquote><p>(There’s also a “&amp;gt;” character which is basically a ”&gt;” symbol)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cda27434accf05ec4bd0423ac4a64d0/href">https://medium.com/media/9cda27434accf05ec4bd0423ac4a64d0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3n9JTeAk3Wlb2Yk97s8uw.png" /><figcaption>Perfect.</figcaption></figure><p>Now, let’s discuss the code.</p><p>Obviously, the function does the job better, and it doesn’t need a specific font to render text. Also, funnily enough, the function takes nearly the same number of arguments as the one we wrote.</p><p>Now, as you might have noticed, there’s a rect argument, which needs to be passed a list of values for a rectangle. To create a rectangle, we call pygame.Rect() function, and pass it 4 values: width, height and the XY position. <br>Keep in mind that it’s an object, and it won’t be displayed unless you add it to the surface!</p><p>The rectangle here is used to size the text inside its borders. So, all calculations are made by checking whether the text is outside the rectangle’s borders.</p><pre>i = 1<br>if y + fontHeight &gt; rect.bottom:<br>    break</pre><p>This stops the function when the Y position is outside the rectangle.<br>This is done to stop the function if the text is too long to fit.<br>i variable is a point at which the text is wrapped.</p><pre>while font.size(text[:i])[0] &lt; rect.width and i &lt; len(text): <br>    i += 1</pre><p>This one determines the maximum size of the line. It loops until the text position is outside the rectangle.</p><pre>if i &lt; len(text): <br>    i = text.rfind(&quot; &quot;, 0, i) + 1</pre><p>When we’ve reached the maximum size of the line, it finds the last white-space in the string and wraps the string.</p><pre>if bkg:<br>    image = font.render(text[:i], 1, color, bkg)<br>    image.set_colorkey(bkg)</pre><p>This renders text with an outline. Not really helpful, so you can feel free not to add it to your code.</p><pre>else:   <br>    image = font.render(text[:i], aa, color)</pre><p>Renders the text if chosen not to render it with the outline.</p><p>The normal_message variable now should look similar to this:</p><pre>normal_message = [screen,(255,255,255), pygame.Rect(30,400,1300,350),ubuntu,textsize[&#39;normal&#39;]] </pre><p>Oh, let’s not forget that this function is made specifically to display large texts. Let’s make an additional function that displays short messages.</p><pre>def display_message(surface, color, rect, font_name, size, text, xy, aa=False, bkg=None):<br> font = pygame.font.Font(font_name, size)<br> rendered_text = font.render(text, aa, (color))<br> screen.blit(rendered_text,(xy))<br> pygame.display.update()</pre><p>(I left the rect argument here so that the normal_message variable won’t have to be changed, though rect serves no purpose in this function.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zBZZIUzN9bsZdlRT6Dk9g.png" /><figcaption>Awesome!</figcaption></figure><p>This is pretty much it for this function. It’s quite simple, and handles the job a lot better than ours. At least we’ve learned how it works in the first place! <strong>First you learn the math, then you use the calculator.</strong></p><p>This is it for this tutorial. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68576b43ec92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pygame tutorial #2: wrapping text]]></title>
            <link>https://medium.com/@maxknivets/pygame-tutorial-2-wrapping-text-1abedcedf7bf?source=rss-9440dabc71af------2</link>
            <guid isPermaLink="false">https://medium.com/p/1abedcedf7bf</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[pygame]]></category>
            <dc:creator><![CDATA[Max Knivets]]></dc:creator>
            <pubDate>Sun, 15 Apr 2018 14:37:02 GMT</pubDate>
            <atom:updated>2019-04-12T09:57:13.889Z</atom:updated>
            <content:encoded><![CDATA[<p>In a previous tutorial I described how to render text with size, color, and etc. Now I’ll be wrapping the text.</p><p>The main problem with wrapping text in Pygame is that the whole string will only be printed out <strong>in one line</strong>, no matter what you do with the string. Due to this, it can stretch out of the window. I did manage to find a function that wraps the text properly: <a href="https://www.pygame.org/wiki/TextWrap">https://www.pygame.org/wiki/TextWrap</a>.</p><p>I also wrote the tutorial on how it’s used and how it works here:<br><a href="https://medium.com/@knivecmaksim/pygame-tutorial-2-1-precise-text-wrapping-method-68576b43ec92">https://medium.com/@knivecmaksim/pygame-tutorial-2-1-precise-text-wrapping-method-68576b43ec92</a>. <em>(I highly encourage you to check this tutorial if you’re looking for a precise wrapping method)</em></p><p><em>If you want to learn the process of making the wrapper function, keep on reading this article. However, I highly discourage you from using my function in this tutorial, as it’s poorly written.</em></p><p>Alright, let’s begin.</p><p>Since we cannot break the line even by using newline in the string, we have to split the message at correct intervals and then iterate the message_display() function with a for-loop. This is where the textwrap module comes in handy.</p><p>The textwrap module works similarly to list()<em> </em>function, except it splits the string at a specified interval.</p><p>Let’s import the module.</p><pre>import textwrap</pre><p>Now, let’s write the function:</p><pre>def wrap_text(message, wraplimit):<br>    return textwrap.fill(message, wraplimit)</pre><p>It still won’t do the job, since Pygame will render any text in one line. So, let’s write the for-loop.</p><p>But here’s a problem, when using textwrap with a random font, the values that are used to wrap the text could vary. That’s why we have to use monospace font for now. The name of the mono-type font that is available in Pygame is “freemono”.</p><p>Let’s establish a few fixed values . If your screen is 1366x766, these ones should do the trick:</p><pre>textvars = {&#39;large&#39;:[90,22,90], &#39;medium&#39;:[50,43,45], &#39;normal&#39;:[25,88,20], &#39;small&#39;:[15,148,10]}</pre><p>So basically the lists consist out of 3 elements : size of the text, the maximum amount of characters that can be fitted in one line, and vertical spacing width.</p><p>Now that we have the appropriate values, let’s display the text using a for-loop:</p><pre>def message_display(myfont, textvars, color, xy, wrap, message):<br>    xy = xy[:] # so we won&#39;t modify the original values<br>    font_object = pygame.font.Font(myfont,textvars[0])<br>    message = wrap_text(message,textvars[1])<br>    for part in message.split(&#39;\n&#39;):<br>         rendered_text = font_object.render(part, True, (color))<br>         screen.blit(rendered_text,(xy))<br>         xy[1] += textvars[2]<br>         pygame.display.update()</pre><p>Now, let’s try this function out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KcqvgwA6k5v8eihS3jx3EA.png" /><figcaption>Hey, it works!</figcaption></figure><p>Perfect. Now that it works, let’s make wrapping optional. Just insert these 2 lines of code before the for-loop:</p><pre>    if wrap:<br>        message = textwrap.fill(message, textvars[1])</pre><p>But that’s not all. What if we were to render text at a different position? Our current X position is 5, or 0 for convenience, but we might want to change it for whatever reason. Try to change the X position to 300 or 500.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEFoPLWsUaJKnMSAGW6B9A.png" /><figcaption>Not cool.</figcaption></figure><p>It won’t wrap the text since the values are fixed, so we need to do a few calculations:</p><pre>if wrap:<br>    char_size = size[0] / textvars[1] # size of one character<br>    new_wrap = (size[0] - xy[0]) / char_size # wrapping point<br>    message = textwrap.fill(message, round(new_wrap))</pre><p>Let’s move the text to the center to see whether it wraps accordingly now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqwI28TMfWmDoBy4wx6wXg.png" /><figcaption>It does!</figcaption></figure><p>This should apply to other sizes too. Let’s try the “medium” one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fiGysZ4dqtc3bRiAtL0ng.png" /><figcaption>It does work, but the text is too long to fit in the window.</figcaption></figure><p>As you can see, we’ll also need to make sure that text won’t be rendered outside the window. In case the text is too large to fit in the window, the loop will break when Y position is beyond the limit.</p><pre>for part in message.split(&#39;\n&#39;):<br>    rendered_text = font_object.render(part, True, (color))<br>    screen.blit(rendered_text, (xy))<br>    xy[1] += textvars[2]<br>    if xy[1] &gt;= size[1]:<br>        return None<br>    pygame.display.update()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBKO4F7wWCcre5wg-b6sTA.png" /><figcaption>Looks nice!</figcaption></figure><p>At this point the text is wrapped <strong>almost</strong> properly. The only disadvantage is that you’re stuck with only one font. Still, it works great.</p><p>This is it for this tutorial. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1abedcedf7bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pygame tutorial #1: displaying rendered text in a window.]]></title>
            <link>https://medium.com/@maxknivets/pygame-tutorial-1-displaying-rendered-text-in-a-window-d0894d838ab3?source=rss-9440dabc71af------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0894d838ab3</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Max Knivets]]></dc:creator>
            <pubDate>Tue, 27 Mar 2018 11:15:11 GMT</pubDate>
            <atom:updated>2019-04-12T09:27:57.209Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I had an idea to create a story-based game using python and pygame library. So I decided it’d be worth giving it a shot.</p><p>First things first, let’s import the stuff that we need for now.</p><pre>import pygame, sys<br>from pygame import font<br>pygame.init() # This is not an import, but it&#39;s necessary to initialize the modules we just imported</pre><p>Now, let’s configure all the necessary stuff.</p><pre>size = (800,600) # size of the window<br>screen = pygame.display.set_mode(size) # screen set-up<br>pygame.display.set_caption(&#39;Game&#39;) # naming our window &quot;Game&quot;</pre><p>The set.caption() function changes the window’s name. You could name the window anything you want.</p><p>Firstly, we need to create a font renderer that renders text with specific font and size. But creating a rendered font requires 2 things: the font that we need, and the size of the text.</p><p>The problem with passing the first thing to the font renderer is that you need to pass the string of<strong> the entire path to the font. </strong>It is time-consuming to manually search for the fonts you need, so Pygame offers a simple function: font.match_font(), which returns the path to the font, given the font’s name.</p><pre>def search_font(name):<br>    found_font = font.match_font(name)<br>    return found_font</pre><p>Pygame also offers a function that returns a list of available fonts: font.get_fonts()<em> .</em> Try running this in your shell to see all available fonts:</p><pre>&gt;&gt;&gt; import pygame<br>&gt;&gt;&gt; from pygame import font<br>&gt;&gt;&gt; font.get_fonts()<br>[&#39;waree&#39;, &#39;liberationsansnarrow&#39;, &#39;ubuntucondensed&#39;, &#39;stixintegralssm&#39;, &#39;garuda&#39;... </pre><p>Usually when running this function, it randomly shuffles the list, so I strongly discourage getting fonts from this list via index. <br>Now that we settled the question, let’s create the font renderer.</p><pre>def font_renderer(font,size): <br>    font_object = pygame.font.Font(font, size)<br>    return font_object</pre><p>Now let’s try to render the message with our rendered font, and color (with a XY position of 5, 500)<br>This is how it should look like:</p><pre>message = font_renderer(search_font(&#39;ubuntu&#39;), 30).render(<br>    &quot;Some Text&quot;,   # the text to render<br>    True,          # anti aliasing<br>    (255,255,255)) # color (RGB value)<br>screen.blit(message, (5, 500)) # adds the rendered text to screen<br>pygame.display.update() # updates the screen with new text</pre><p>This is not a really convenient way to render messages, but at least it renders it now! Let’s simplify this even more:</p><pre>def message_renderer(font_object, color, xy, message):    <br>    rendered_text = font_object.render(message, True, (color))<br>    screen.blit(rendered_text, (xy))<br>    pygame.display.update()</pre><pre># rendering the message</pre><pre>rendered_font = font_renderer(search_font(&#39;ubuntu&#39;),30)<br>message_renderer(rendered_font,(255,255,255),(5,500),&quot;Hello world&quot;)</pre><p>We can simplify it even more!<br>Let’s remove the font renderer function and write the message display as a one big function.</p><pre>def message_display(used_font, size, color,xy,message): <br>    font_object = pygame.font.Font(used_font, size)<br>    rendered_text = font_object.render(message, True, (color))<br>    screen.blit(rendered_text,(xy))<br>    pygame.display.update()</pre><pre>#rendering the message<br>ubuntu = search_font(&#39;ubuntu&#39;)<br>message_display(ubuntu,30,(255,255,255),(5,500),&quot;Hello, world!&quot;)</pre><p>At this point the function looks much simpler and requires only one line to be called. It’ll come in handy when writing story-based games.</p><p>It is also annoying to write long function calls with the same parameters all the time. So let’s write a list with desired parameters to run the message display function with two arguments instead of five.</p><pre>normal_message = [search_font(&#39;ubuntu&#39;),30,(255,255,255),(5,400)]</pre><p>Now, let’s use the variable.</p><pre>message_display(*normal_message ,&quot;That is a super short line!&quot;)</pre><p>We managed to simplify this task to calling the function with ease and <strong>1 short line of code</strong>!</p><p>Let’s not forget to make a while-loop so our window won’t close as soon as we launch the game.</p><pre>def main():<br>    while True:<br>        message_display(*normal_message ,&quot;Not much to see here.&quot;)<br>        for event in pygame.event.get():<br>            if event.type == pygame.QUIT:<br>            return False</pre><pre>main()</pre><p>Here’s the result of our hard work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7NYydNe5WtmhOQ0dtyyozQ.png" /><figcaption>Not so much to see here.</figcaption></figure><p>The progress might look insignificant, but later on we will use this function to write dialogue between characters, and much more!</p><p>This is it for this tutorial. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0894d838ab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>