PyGame Tutorial: Geometric Drawing. Therefore instead of re-iterating the documentation as part of this tutorial, I'll instead show you a few simple (and not-so-simple) examples of what can be doing with the draw module in PyGame and a few pitfalls to be aware of. At the end of this tutorial/demo you'll see a massive code dump. The first argument is the surface instance to draw the rectangle to. The second argument is the (red, green, blue) tuple that represents the color to draw with. The third argument is a pygame.Rect instance. The arguments for this constructor are the x and y coordintaes of the top left corner, the width, and the height. Amazing-er!but not by much.
- Pygame Draw Rect Example Free
- Pygame Draw Polygon
- How To Draw A Rectangle In Pygame
- Pygame Draw Rect Example For Word
- Pygame Draw Rect Example For Kids
Active6 months ago
Im making a game that requires knowing how to draw a rectangle in python 3.2.
I have checked lot of sources but none show exactly how to do it.
Thanks!
JaredJared
3 Answers
If you'd thoroughly checked the sources you purported to have checked, then you would've found how to draw a rectangle- the simplest of tasks in pygame. But since you asked, here's how:
This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the
pygame.draw.rect
to go about this, and you add the DISPLAY
constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.Look up pygame.org for more info
Mateusz Konieczny86511 gold badge1515 silver badges3737 bronze badges
user1800989
Have you tried this:
Taken from the site:
pygame.draw.rect(screen, color, (x,y,width,height), thickness) draws a rectangle (x,y,width,height) is a Python tuple x,y are the coordinates of the upper left hand corner width, height are the width and height of the rectangle thickness is the thickness of the line. If it is zero, the rectangle is filled
PhorcePhorce1,92766 gold badges3838 silver badges7575 bronze badges
l. zhangl. zhang
Not the answer you're looking for? Browse other questions tagged pythonpygamerectangles2d-games or ask your own question.
PyGame Tutorial
On this PyGame tutorial blog, let us learn in detail about PyGame and see how we can proceed building simple games with this.
We will be covering the following topics in the blog:
Prerequisites
For making a game of your choice there are 3 main questions that need answering. They are as follows:
- What sort of game do you want to build?
- What sort of language do you want to program in?
- What sort of platform do you want to deploy your game to?
Most of the time you can answer each of these questions and find a perfect framework that fits your requirements. Other times, it might not be possible. Consider for example, there aren’t many HTML5 frameworks that allow you to write a high-performance 3D game that you can build.
For PyGame, let’s assume you gave the following answers to the previous 3 questions:
- The game you want to create is graphical, but not 3D.
- You want to program in Python. Also, you already know a little bit of Python
- You want to create a client application that can potentially be wrapped in a standalone executable.
So, next up on this PyGame Tutorial blog let us look at how we can set up PyGame.
Installing PyGame
Installing PyGame is pretty straightforward and easy. But the first prerequisite is to install Python 2.7. Installing Python on both Windows and Linux is very easy and simple.
Next up would be download the official PyGame installer and run the corresponding files and follow the on-screen instructions.
Installation is simple. Just follow through and the defaults are considered fine.
I personally use PyCharm and install all of these addons there and work using that for my Python requirements. Just use whichever IDE you are comfortable with and start along with that.
Simple PyGame Application
The following is a very simple app that is built using PyGame pipeline. Check it out:
Here is where you can make more sense out of the syntax:
import pygame – This is of course needed to access the PyGame framework.
pygame.init() – This initializes all the modules required for PyGame.
pygame.display.set_mode((width, height)) – This will launch a window of the desired size. The return value is a Surface object which is the object you will perform graphical operations on.
pygame.event.get() – This empties the event queue. If you do not call this, the windows messages will start to pile up and your game will become unresponsive in the opinion of the operating system.
pygame.QUIT – This is the event type that is fired when you click on the close button in the corner of the window.
pygame.display.flip() – PyGame is double-buffered so this swaps the buffers. All you need to know is that this call is required in order for any updates that you make to the game screen to become visible.
So what is the output like, when we execute the above code? It looks something like this:
Looks rather plain, right? Let us start adding some content to our screen. We can begin by drawing a rectangle. It is simple and we use pygame.draw.rect for this purpose.
As you can imagine, this will draw a rectangle. It takes in a few arguments, including the surface to draw on , the color and the coordinates/dimensions of the rectangle.
As you can see there are 3 arguments:
- The first argument is the surface instance to draw the rectangle to.
- The second argument is the (red, green, blue) tuple that represents the color to draw with.
- The third argument is a pygame.Rect instance. The arguments for this constructor are the x and y coordinates of the top left corner, the width, and the height.
So what is it that we can see after adding that tiny piece of code?
Well, here is the output:
Seems to be nothing fancy just yet. But we can always start somewhere, right?
So next up on this PyGame Tutorial blog, let us look at how we can make the game more interactive.
Interactivity
The point of a game is to be interactive. Right now, the only thing you can interact with is the close button. Which isn’t a very fun game, right? All user input events come through the event queue. Simply add more if statements to that for loop to add more interactivity.
Add the following code before the loop:
Modify your rectangle code to pick a color conditionally:
Finally, the important bit. Add the following if statement to your for loop in the same sequence as the other if statement in there.
So pressing the space key will change the color of the box. Check out the following output:
Pretty easy, right?Next up on this PyGame tutorial blog, we need to check out how we can add some functionality to the game.
Adding Functionality
So, our entire code looks something like this for now. Check it out below:
Let us check the output when we try to move the rectangle to the right:
So that is not what we were expecting, right?
Two things are wrong.
- Each time you draw a rectangle, the rectangle from the previous frames remains on the screen.
- It moves really really really fast.
For the first, you simply need to reset the screen to black before you draw the rectangle. There is a simple method on Surface called fill that does this. It takes in an RGB tuple.
Secondly, the duration of each frame is as short as your super fancy computer can make it. The framerate needs to be throttled at a sane number such as 60 frames per second. Luckily, there is a simple class in pygame.time called Clock that does this for us. It has a method called tick which takes in a desired fps rate.
Put it all together and you get:
So what does the output look like now? Check it out:
Next up on this PyGame tutorial blog we will see how we can work with images and how we can integrate them into our game.
Adding Images
You can instantiate a blank surface by simply calling the Surface constructor with a width and height tuple.
This will create a blank 24-bit RGB image that’s 100 x 100 pixels. The default color will be black. Blitting such an image on a white background will result in this:
However, if you want a 32-bit RGBA image, you can also include an optional argument in the Surface constructor. Just add the following line in the code:
This will create a 100 x 100 image that’s initialized to transparent. Rendering such an image on a white background will result in this:
Solid color images and rectangles aren’t very interesting. Let’s use an image file:
Consider a PNG image of a ball. The fine name is ‘ball.png’. This is the image, check it out:
To load an image from file, there is a simple call to pygame.image.load()
Check out the following syntax:
Replacing the pygame.Surface((100, 100)) code with the code above will result in an output such as this. Check it out:
Do not use pygame.image.load repeatedly on the same image within your game loop. That is not an efficeint way to code. The best way to do it is to initialize it just once and use it any number of times later.
The best thing you could do is to create a string-to-surface dictionary in one centralized location. And then write a function called get_image that takes in a file path. If the image has been loaded already, then it returns the initialized image.
If not, it does the initialization. The beauty of this is that it is fast and it removes the clutter of initializing images at the beginning of key areas of the game logic. You can also use it to centralize the abstraction of directory separators for different operating systems. But a code snippet is worth a thousand words.
Here is the code snippet:
Note: Windows is not case sensitive when it comes to file names. All other major operating systems are. If your file is called ball.png and you use pygame.image.load(‘BALL.PNG’) it will work if you are on windows. However, when you give your game to someone running on a mac or Linux, it will not work and might end up with an erroneous output.
Next up on this PyGame tutorial blog, let us check out how we can implement music and sound effects into our game.
Sound and Music
The sound and music API’s are fairly simple. Let us go though the basics and we can work our way from there.
Playing a song once:
The number being passed in is the number of times to repeat the song. 0 will play it once.
Calling play without a number is like calling it with 0.
Queuing a song:
Stopping a song:
The stop function will also nullify any entries in the queue.
Shuffle and repeat:
If, for example, you wanted to play randomly from a list of 5 songs, one could create a list of the songs as a global:
Add a flag indicating which song is currently playing:
And write a function that chooses a different song randomly that gets called each time the SONG_END event is fired:
Or if you want them to play in the same sequence each time:
The music API is very centralized. However sounds require the creation of sound objects that you have to hold on to. Much like images. Sounds have a simple .play() method that will start playing the sound.
Because you can make the mistake of storing sound instances redundantly, I suggest creating a sound library much like the image library:
There are many more features but this is really all you need to do 95% of what most games will require of you.
Next up on this PyGame Tutorial blog, let us look at how we can implement geometric shapes into the game.
Geometric Drawings
Just like the mixer module, the drawing API is fairly straightforward with a few examples.
Drawing a rectangle:
Drawing a Circle:
Built-in outlines are bad, really bad!
This is the first caveat you should be aware of. PyGame’s method for creating “thicker” outlines for circles is to draw multiple 1-pixel outlines. In theory, it sounds okay, until you see the result:
The circle has noticeable pixel gaps in it. Even more embarrassing is the rectangle, which uses 4 line-draw calls at the desired thickness. This creates weird corners.
The way to do this for most drawing API calls is to pass in an optional last parameter which is the thickness.
Note: When you draw a polygon, rectangle, circle, etc, draw it filled in or with 1-pixel thickness. Everything else is not very well implemented.
Acceptable Outlines:
If you must draw a rectangle that has 10-pixel-thick borders, then it’s best that you re-implement the logic yourself with either 10 1-pixel-thick rectangle calls, or 4 10-pixel-thick rectangle calls for each side.
Drawing a Polygon:
This API is pretty straightforward. The point list is a list of tuples of x-y coordinates for the polygon.
Drawing a line:
Check out this amazing 3D spinning wireframe cube created using the line method and a lot of math:
Next up on this PyGame Tutorial blog, let us look at how we can work with Fonts and Text.
Fonts And Text
If you’re looking for the quick answer on how to render text, here it is:
But of course, there’s a few things not ideal about this.
Rule #1: You should never assume a certain font is installed on the user’s computer. Even in CSS, there is a way to define a hierarchy of fonts to use. If the best choice for a font isn’t available, an alternate is used. You should follow the same pattern. Luckily, PyGame has a way to enumerate all the fonts available on the machine:
Gamecube controller adapter dolphin. Additionally, there’s a way to instantiate the default system font:
And alternatively, you can pass in the name of a font file you include along with your code instead of None to guarantee the existence of the perfect font:
Using any combination of the above, you can write a better font creation function. For example, here’s a function that takes a list of font names, a font size and will create a font instance for the first available font in the list. If none are available, it’ll use the default system font.
You can even further improve it by caching the font instance by font name and size.
You can take it a step further and actually cache the rendered text itself. Storing an image is cheaper than rendering a new one, especially if you plan on having the same text show up for more than one consecutive frame. Yes. That is your plan if you want it to be readable.
Putting all of these together, here is the “Hello, World” code but with improved code:
Next up on this Pygame tutorial blog, we need to look at how we can consider inputs.
Input Models
There are two basic ways to get the state of any input device. Those are checking the event queue or polling. Every time a key or button is pressed or released, or the mouse is moved, an event is added to the event queue. You must empty this event queue out each frame by either calling pygame.event.get() or pygame.event.pump().
pygame.event.get() will return a list of all the events since the last time you emptied the queue. The way to handle those events depends on the type of event itself. The type of event can be checked by reading the event.type field. Examples of pretty much each type of common event can be seen in the extended code sample below. There are more types, but they are fairly uncommon.
The other way to check for events is to poll for the state of keys or buttons.
Free samsung phone unlock software. pygame.key.get_pressed() – This will get a list of booleans that describes the state of each keyboard key.
pygame.mouse.get_pos() – Returns the coordinates of the mouse cursor. Will return (0, 0) if the mouse hasn’t moved over the screen yet.
pygame.mouse.get_pressed() – Like pygame.key.get_pressed(), returns the state of each mouse button. The value returned is a tuple of size 3 that corresponds to the left, middle, and right buttons.
Here’s a little program that has a bit of everything:
- Moving the mouse causes a trail to be drawn after it.
- Pressing W while holding Ctrl will close the window. Same for Alt + F4.
- Pressing the close button will close the window
- Pressing r, g, or b keys will make the trail turn red, green, and blue respectively.
- Pressing the left mouse button will cause the trail to become thicker.
- Pressing the right mouse button will cause the trail to become thinner.
Lastly on this PyGame tutorial blog, we need to check out something called as the centralized scene logic.
Centralized Scene Logic
This isn’t a PyGame-specific tutorial per-se. It’s more of an application of good software design concepts. This model of doing things has served me well for many complicated games.
Pygame Draw Rect Example Free
If you are not familiar with Object-Oriented programming in Python, familiarize yourself now.
Done? Excellent.
Pygame Draw Polygon
Here is a class definition for a SceneBase:
How To Draw A Rectangle In Pygame
When you override this class, you have 3 method implementations to fill in.
- ProcessInput – This method will receive all the events that happened since the last frame.
- Update – Put your game logic in here for the scene.
- Render – Put your render code here. It will receive the main screen Surface as input.
Of course, this class needs the appropriate harness to work. Here is an example program that does something simple: It launches the PyGame pipeline with a scene that is a blank red background. When you press the ENTER key, it changes to blue.
This code may seem like overkill, but it does lots of other subtle things as well while at the same time keeps the complexity of your game logic contained into a snazzy OO model. Once you start adding more complexity to your game, this model will save you lots of time from debugging and changing code.
Pygame Draw Rect Example For Word
Conclusion
I hope this PyGame tutorial helps you to kickstart your learning on PyGame. After reading this blog on PyGame Tutorial using Python, I am pretty sure you want to know more about Python. To know more about Python you can refer the following blogs:
I think the following blogs on Python concepts will interest you as well. Check it out:
If you have any questions regarding this tutorial, please let me know in the comments.
Do develop some games using the tutorial and let me know in the comments section below, I’d be play some games!
PyGame Tutorial | PyGame Python Tutorial For Beginners | Python Certification Training | Edureka
Pygame Draw Rect Example For Kids
Master Python with the certification training now!