Just like how Python comes with several modules like random, math , or time that provide
additional functions for your programs, the Pygame framework includes several modules with
functions for drawing graphics, playing sounds, handling mouse input, and other things.
This chapter will
The "Invent with Python" book also has a few chapters covering Pygame. You can read them online at http://invpy.com/chap17.
Once you learn more about Pygame, you can view the other modules that Pygame provides from
the
The Python programs that you can write with Python's print() and input() functions. Your program can display text on the screen and
let the user type in text from the keyboard. This type of program has a command line interface,
or CLI (which is pronounced like the first part of "climb" and rhymes with "sky"). These
programs are somewhat limited because they can't display graphics, have colors, or use the
mouse. These CLI programs only get input from the keyboard with the input() function and
even then user must press Enter before the program can
Pygame provides functions for creating programs with a graphical user interface, or GUI (pronounced, "gooey"). Instead of a text-based CLI, programs with a graphics-based GUI can show a window with images and colors.
Our first program made with Pygame is a small program that makes a window that says "Hello World!" appear on the screen. Open a new file editor window by clicking on IDLE's File menu, then New Window. Type in the following code into IDLE’s file editor and save it as blankpygame.py. Then run the program by pressing F5 or selecting Run > Run Module from the menu at the top of the file editor.
Remember, do not type the numbers or the periods at the beginning of each line (that’s just for reference in this book).
1. import pygame, sys
2. from pygame.locals import *
3.
4. pygame.init()
5. DISPLAYSURF = pygame.display.set_mode((400, 300))
6. pygame.display.set_caption('Hello World!')
7. while True: # main game loop
8. for event in pygame.event.get():
9. if event.type == QUIT:
10. pygame.quit()
11. sys.exit()
12. pygame.display.update()
When you run this program, a black window like this will appear:
(рис 2.1) Black window
Yay! You've just made the world’s most boring
Calling the print() function to make text appear in the window won't work because
print() is a function for CLI programs. The same goes for input() to get
The first few lines of code in the Hello World program are lines that will begin almost every program you write that uses Pygame.
1. import pygame, sys
Line 1 is a simple import statement that imports the pygame and sys modules so that our
program can use the functions in them. All of the Pygame functions dealing with graphics, sound,
and other features that Pygame provides are in the pygame module.
Note that when you import the pygame module you automatically import all the modules that
are in the pygame module as well, such as pygame.images and pygame..
There's no need to import these modules-inside-modules with additional import statements.
2. from pygame.locals import *
Line 2 is also an import statement. However, instead of the import modulename format, it
uses the from modulename import * format. Normally if you want to call a function that
is in a module, you must use the modulename.functionname() format after importing the
module. However, with from modulename import *, you can skip the modulename.
functionname() (just like Python's
The import statement for pygame.locals is because
pygame.locals contains several pygame.locals module without pygame.locals in front of them. For all other modules,
you generally want to use the regular import modulename format. (There is more
information about why you want to do this at http://invpy.com/namespaces).
4. pygame.init()
Line 4 is the pygame.init() pygame module and before calling any other Pygame function. You don't need to know what
this function does, you just need to know that it needs to be called first in order for many Pygame
functions to work. If you ever see an pygame.error: font not
initialized, check to see if you forgot to call pygame.init() at the start of your
program.
5. DISPLAYSURF = pygame.display.set_mode((400, 300))
Line 5 is a call to the pygame.display.set_mode() function, which returns the
pygame. object for the window. (set_mode() function how wide and how high to make the window in pixels. (400,
300) will make a window with a width of 400 pixels and height of 300 pixels.
Remember to pass a set_mode(), not just two integers themselves. The
correct way to call the function is like this: pygame.display.set_mode((400, 300)).
A pygame.display.set_mode(400, 300) will cause an error that
looks like this: TypeError: argument 1 must be 2-itcode sequence, not int
The pygame. object (we will just call them DISPLAYSURF.
6. pygame.display.set_caption('Hello World!')
Line 6 sets the caption text that will appear at the top of the window by calling the
pygame.display.set_caption() function. The string value 'Hello World!' is
passed in this
(рис 2.2) Caption
7. while True: # main game loop 8. for event in pygame.event.get():
Line 7 is a while loop that has a condition of simply the value True This means that it never
exits due to its condition evaluating to False The only way the program execution will ever
exit the loop is if a break statement is executed (which moves execution to the first line after the
loop) or sys.exit() (which terminates the program). If a loop like this was inside a function,
a return statement will also move execution out of the loop (as well as the function too).
The games in this book all have these while True loops in them along with a comment calling
it the "main game loop". A game loop (also called a main loop) is a loop where the code does
three things:
The game state is simply a way of referring to a set of values for all the variables in a game program. In many games, the game state includes the values in the variables that tracks the player's health and position, the health and position of any enemies, which marks have been made on a board, the score, or whose turn it is. Whenever something happens like the player taking damage (which lowers their health value), or an enemy moves somewhere, or something happens in the game world we say that the game state has changed.
If you've ever played a game that let you saved, the "save state" is the game state at the point that you've saved it. In most games, pausing the game will prevent the game state from changing.
Since the game state is usually updated in response to events (such as pygame.event.get()
function). The main loop also has code that updates the game state based on which events have
been created. This is usually called event handling.
(рис 2.3) pygame.event.EventObjects
Any time the user does one of several actions (they are listed later in this chapter) such as
pressing a keyboard key or moving the mouse on the program's window, a
pygame.event.Event object is created by the Pygame library to record this "event". (This is
a type of object called Event that exists in the event module, which itself is in the pygame
module.) We can find out which events have happened by calling the pygame.event.get()
function, which returns a list of pygame.event.Event objects (which we will just call Event
objects for short).
The list of Event objects will be for each event that has happened since the last time the
pygame.event.get() function was called (Or, if pygame.event.get() has never been
called, the events that have happened since the start of the program).
7. while True: # main game loop 8. for event in pygame.event.get():
Line 8 is a for loop that will iterate over the list of Event objects that was returned by
pygame.event.get() On each iteration through the for loop, a variable named event
will be assigned the value of the next event object in this list. The list of Event objects returned
from pygame.event.get() will be in the order that the events happened. If the user clicked
the mouse and then pressed a keyboard key, the Event object for the mouse click would be the
first item in the list and the Event object for the keyboard press would be second. If no events
have happened, then pygame.event.get() will return a blank list.
9. if event.type == QUIT: 10. pygame.quit() 11. sys.exit()
Event objects have a member variable (also called attributes or properties) named type
which tells us what kind of event the object represents. Pygame has a constant variable for each
of possible types in the pygame.locals modules. Line 9 checks if the Event object's type is
equal to the constant QUIT Remember that since we used the from pygame.locals
import * form of the import statement, we only have to type QUIT instead of
pygame.locals.QUIT.
If the Event object is a quit event, then the pygame.quit() and sys.exit() functions are
called. The pygame.quit() function is sort of the opposite of the pygame.init()
function: it runs code that deactivates the Pygame library. Your programs should always call
pygame.quit() before they call sys.exit() to terminate the program. Normally it doesn't
really matter since Python closes it when the program exits anyway. But there is a bug in IDLE
that causes IDLE to pygame.quit() is called.
Since we have no if statements that run code for other types of Event object, there is no event-
handling code for when the user clicks the mouse, presses keyboard keys, or causes any other
type of Event objects to be created. The user can do things to create these Event objects but it
doesn't change anything in the program because the program does not have any event-handling
code for these types of Event objects. After the for loop on line 8 is done handling all the Event
objects that have been returned by pygame.event.get(), the program execution continues
to line 12.
12. pygame.display.update()
Line 12 calls the pygame.display.update() function, which draws the pygame.display.set_mode() to the screen (remember we stored this object
in the DISPLAYSURF variable). Since the pygame.display.update() is called.
That is the entire program. After line 12 is done, the infinite while loop starts again from the
beginning. This program does nothing besides make a black window appear on the screen,
constantly check for a QUIT event, and then redraws the
The window that the "Hello World" program creates is just
(рис 2.4) 8x8 Surface
We can refer to a specific pixel by using a
For example, in the above 8x8 image, we can see that the pixels at the XY coordinates (4, 0), (2,
2), (0, 5), and (5, 6) have been painted black, the pixel at (2, 4) has been painted gray, while all
the other pixels are painted white. XY coordinates are also called points. If you've taken a math
class and learned about Cartesian Coordinates, you might notice that the Y-axis starts at 0 at the
top and then increases going down, rather than increasing as it goes up. This is just how
The Pygame framework often represents
Functions and methods are almost the same thing. They can both be called to execute the code in
them. The difference between a function and a method is that a method will always be attached to
an object. Usually methods change something about that particular object (you can think of the
attached object as a sort of
This is a foo():
foo()
This is a foo(), which is attached to an object stored in a
variable named duckie:
duckie.foo()
A call to a function inside of a module may look like a sys.exit() is a call to function inside of a module,
because at the top of the program will be an import statement like import sys.
A constructor function is the same thing as a normal function call, except that its return value is a new object. Just by looking at source code, a function and constructor function look the same. Constructor functions (also called simply a "constructor" or sometimes "ctor" ("see-tor") for short) are just a name given to functions that return a new object. But usually ctors start with a capital letter. This is why when you write your own programs, your function names should only begin with a lowercase letter.
For example, pygame.Rect() and pygame. are both constructor functions
inside the pygame module that return new Rect and
Here's an example of a
import whammy fizzy() egg = Wombat() egg.bluhbluh() whammy.spam()
Even though these names are all made up, you can tell which is a whammy refers to a module, since you can see it is
being imported on the first line. The fizzy name has nothing before it and
Wombat() is also a egg.bluhbluh() call is a bluhbluh is attached to a
variable with an object in it.
Meanwhile, whammy. is a whammy was imported as a module earlier.
In particular, the pygame.display.set_mode() is called the
display Surface. Anything that is drawn on the display Surface object will be displayed on the
window when the pygame.display.update() function is called. It is a lot faster to draw
on a
Often your program will draw several different things to a
Drawing on
There are three
Because you can use any combination of 0 to 255 for each of the three "ValueError: invalid color argument".
For example, we will create the BLACK . With
no amount of red, green, or blue, the resulting color is completely black. The color black is the
absence of any color. The
You can mix the amount of red, green, and blue to form other colors. Here are the RGB values for a few common colors:
| Color | RGB Values |
|---|---|
| Aqua | ( 0, 255, 255) |
| Black | ( 0, 0, 0) |
| Blue | ( 0, 0, 255) |
| Fuchsia | (255, 0, 255) |
| Gray | (128, 128, 128) |
| Green | ( 0, 128, 0) |
| Lime | ( 0, 255, 0) |
| Maroon | (128, 0, 0) |
| Navy Blue | ( 0, 0, 128) |
| Olive | (128, 128, 0) |
| Purple | (128, 0, 128) |
| Red | (255, 0, 0) |
| Silver | (192, 192, 192) |
| Teal | ( 0, 128, 128) |
| White | (255, 255, 255) |
| Yellow | (255, 255, 0) |
When you look through a
This value is known as the alpha value. It is a measure of how opaque (that is, not transparent) a color is. Normally when you draw a pixel onto a surface object, the new color completely replaces whatever color was already there. But with colors that have an alpha value, you can instead just add a colored tint to the color that is already there.
For example, this
In order to draw using transparent colors, you must create a convert_alpha()method. For example, the following code creates a
anotherSurface = DISPLAYSURF.convert_alpha()
Once things have been drawn on the anotherSurface, then
anotherSurface can be "DISPLAYSURF so it will appear on the
screen. (See the "Drawing Images with pygame.image.load() and " section later
in this chapter).
It’s important to note that you cannot use transparent colors on convert_alpha() call, including the display pygame.display.set_mode().
If we were to create a color
(рис 2.5) Above is a screenshot of a drawing of the Invisible Pink Unicorn.
You need to know how to represent a color because Pygame’s drawing functions need a way to
know what color you want to draw with. A pygame.Color object. You can create Color objects by calling the
pygame.Color() constructor function and passing either three or four integers. You can store
this Color object in variables just like you can store
>>> import pygame >>> pygame.Color(255, 0, 0) (255, 0, 0, 255) >>> myColor = pygame.Color(255, 0, 0, 128) >>> myColor == (255, 0, 0, 128) True >>>
Any drawing function in Pygame (which we will learn about in a bit) that has a parameter for
color can have either the True).
Now that you know how to represent colors (as a pygame.Color object or a pygame.Rect objects so we can start using Pygame’s drawing
functions.
Pygame has two ways to represent rectangular areas (just like there are two ways to represent
colors). The first is a
The second way is as a pygame.Rect object, which we will call Rect objects for short. For
example, the code below creates a Rect object with a top left corner at (10, 20) that is 200 pixels
wide and 300 pixels tall:
>>> import pygame >>> spamRect = pygame.Rect(10, 20, 200, 300) >>> spamRect == (10, 20, 200, 300) True
The handy thing about this is that the Rect object automatically calculates the coordinates for
other features of the rectangle. For example, if you need to know the X coordinate of the right
edge of the pygame.Rect object we stored in the spamRect variable, you can just access the
Rect object’s right attribute:
>>> spamRect.right 210
The Pygame code for the Rect object automatically calculated that if the left edge is at the X
coordinate 10 and the rectangle is 200 pixels wide, then the right edge must be at the X
coordinate 210. If you right attribute, all the other attributes are automatically
>>> spam.right = 350 >>> spam.left 150
Here’s a list of all the attributes that pygame.Rectobjects provide (in our example, the
variable where the Rect object is stored in a variable named myRect):
| Attribute Name | Description |
|---|---|
myRect.left
|
The int value of the X-coordinate of the left side of the rectangle. |
myRect.right
|
The int value of the X-coordinate of the right side of the rectangle. |
myRect.top
|
The int value of the Y-coordinate of the |
myRect.bottom
|
The int value of the Y-coordinate of the bottom side. |
myRect.centerx
|
The int value of the X-coordinate of the center of the rectangle. |
myRect.centery
|
The int value of the Y-coordinate of the center of the rectangle. |
myRect.width
|
The int value of the width of the rectangle. |
myRect.height
|
The int value of the height of the rectangle. |
myRect.size
|
A |
myRect.topleft
|
A |
myRect.topright
|
A |
myRect.bottomleft
|
A |
myRect.bottomright
|
A |
myRect.midleft
|
A |
myRect.midright
|
A |
myRect.midtop
|
A |
myRect.midbottom
|
A |
Pygame provides several different functions for drawing different shapes onto a
1. import pygame, sys
2. from pygame.locals import *
3.
4. pygame.init()
5.
6. # set up the window
7. DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)
8. pygame.display.set_caption('Drawing')
9.
10. # set up the colors
11. BLACK = ( 0, 0, 0)
12. WHITE = (255, 255, 255)
13. RED = (255, 0, 0)
14. GREEN = ( 0, 255, 0)
15. BLUE = ( 0, 0, 255)
16.
17. # draw on the surface object
18. DISPLAYSURF.fill(WHITE)
19. pygame.draw.polygon(DISPLAYSURF, GREEN, ((146, 0), (291, 106), (236, 277),
(56, 277), (0, 106)))
20. pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4)
21. pygame.draw.line(DISPLAYSURF, BLUE, (120, 60), (60, 120))
22. pygame.draw.line(DISPLAYSURF, BLUE, (60, 120), (120, 120), 4)
23. pygame.draw.circle(DISPLAYSURF, BLUE, (300, 50), 20, 0)
24. pygame.draw.ellipse(DISPLAYSURF, RED, (300, 250, 40, 80), 1)
25. pygame.draw.rect(DISPLAYSURF, RED, (200, 150, 100, 50))
26.
27. pixObj = pygame.PixelArray(DISPLAYSURF)
28. pixObj[480][380] = BLACK
29. pixObj[482][382] = BLACK
30. pixObj[484][384] = BLACK
31. pixObj[486][386] = BLACK
32. pixObj[488][388] = BLACK
33. del pixObj
34.
35. # run the game loop
36. while True:
37. for event in pygame.event.get():
38. if event.type == QUIT:
39. pygame.quit()
40. sys.exit()
41. pygame.display.update()
When this program is run, the following window is displayed until the user closes the window:
(рис 2.6) Drawing
Notice how we make GREEN in the
The drawing functions are named after the shapes they draw. The parameters you pass these
functions tell them which drawing.py program, but here is a short description of each function:
fill() method is not a function but a method of pygame.Surface
objects. It will completely fill in the entire color parameter.surface and color parameters tell the function on what pointlist parameter is a width parameter is optional. If you leave it out, the polygon that is drawn will be filled
in, just like our green polygon on the screen is filled in with color. If you do pass an integer
value for the width parameter, only the outline of the polygon will be drawn. The integer
represents how many pixels width the polygon’s outline will be. Passing 1 for the width
parameter will make a skinny polygon, while passing 4 or 10 or 20 will make thicker
polygons. If you pass the integer 0 for the width parameter, the polygon will be filled in
(just like if you left the width parameter out entirely).
All of the pygame.draw drawing functions have optional width parameters at the end,
and they work the same way as pygame.draw.polygon()’s width parameter.
Probably a better name for the width parameter would have been thickness , since that
parameter controls how start_point and end_point parameters.pygame.draw.polygon(). The only
difference is that if you pass False for the closed parameter, there will not be a line from
the last point in the pointlist parameter to the first point. If you pass True, then it will
draw a line from the last point to the first.center_point parameter. The integer passed for
the radius parameter sets the size of the circle.
The radius of a circle is the distance from the center to the edge. (The radius of a circle is
always radius parameter will draw a circle that
has a radius of 20 pixels.
The bounding_rectangle parameter can be a pygame.Rect object or a pygame.draw.circle() function.rectangle_tuple is either a pygame.Rect object can be passed
instead. If the rectangle_tuple has the same size for the width and height, a square will
be drawn.Unfortunately, there isn’t a single function you can call that will set a single pixel to a color
(unless you call pygame.draw.line() with the same start and end point). The Pygame
framework needs to run some code behind the
Instead, you should create a pygame.PixelArray object (we’ll call them PixelArray objects
for short) of a method. (The method is
If you want to see if a get_locked() True if it is locked and False if it is not.
The PixelArray object that is returned from pygame.PixelArray() can have pixObj[480][380] =
BLACK will set the pixel at X coordinate 480 and Y coordinate 380 to be black (remember that
the BLACK variable stores the color
To tell Pygame that you are finished drawing del statement. This is what line 33 does. Deleting the PixelArray object will "unlock" the
"pygame..
After you are done calling the drawing functions to make the display pygame.display.update() to make the display
The one thing that you must remember is that pygame.display.update() will only make
the display pygame.display.set_mode()) appear on the screen. If you want the images on other
method (which is
Now that we know how to get the Pygame framework to draw to the screen, let’s learn how to
make animated pictures. A game with only still, unmoving images would be fairly dull. (Sales of
my game "Look At This
(рис 2.7)
If you changed the window so that 3, 0 was black and 4,0 was white, it would look like this:
(рис 2.8)
To the user, it looks like the black pixel has "moved" over to the left. If you redrew the window to have the black pixel at 2, 0, it would continue to look like the black pixel is moving left:
(рис 2.9)
It may look like the black pixel is moving, but this is just an illusion. To the computer, it is just showing three different images that each just happen to have one black pixel. Consider if the three following images were rapidly shown on the screen:
(рис 2.10)
To the user, it would look like the cat is moving towards the squirrel. But to the computer, they’re
just a bunch of pixels. The trick to making believable looking animation is to have your program
draw a picture to the window, wait a slightly different
picture.
Here is an example program
1. import pygame, sys
2. from pygame.locals import *
3.
4. pygame.init()
5.
6. FPS = 30 # frames per second setting
7. fpsClock = pygame.time.Clock()
8.
9. # set up the window
10. DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
11. pygame.display.set_caption('Animation')
12.
13. WHITE = (255, 255, 255)
14. catImg = pygame.image.load('cat.png')
15. catx = 10
16. caty = 10
17. direction = 'right'
18.
19. while True: # the main game loop
20. DISPLAYSURF.fill(WHITE)
21.
22. if direction == 'right':
23. catx += 5
24. if catx == 280:
25. direction = 'down'
26. elif direction == 'down':
27. caty += 5
28. if caty == 220:
29. direction = 'left'
30. elif direction == 'left':
31. catx -= 5
32. if catx == 10:
33. direction = 'up'
34. elif direction == 'up':
35. caty -= 5
36. if caty == 10:
37. direction = 'right'
38.
39. DISPLAYSURF.blit(catImg, (catx, caty))
40.
41. for event in pygame.event.get():
42. if event.type == QUIT:
43. pygame.quit()
44. sys.exit()
45.
46. pygame.display.update()
47. fpsClock.tick(FPS)
Look at that animated cat go! This program will be much more of a commercial success than my
game, "Look At This
The frame rate or refresh rate is the number of pictures that the program draws per second, and is measured in FPS or frames per second. (On computer monitors, the common name for FPS is hertz. Many monitors have a frame rate of 60 hertz, or 60 frames per second.) A low frame rate in video games can make the game look choppy or jumpy. If the program has too much code to run to draw to the screen frequently enough, then the FPS goes down. But the games in this book are simple enough that this won’t be issue even on old computers.
A pygame.time.Clock object can help us make sure our program runs at a certain maximum
Clock object will ensure that our tick() method of a
Clock object in the game loop can make sure the game runs at the same speed no matter how
fast of a computer it runs on. The Clock object is created on line 7 of the catanimation.py
program.
7. fpsClock = pygame.time.Clock()
The Clock object’s tick() method should be called at the very end of the game loop, after the
call to pygame.display.update(). The length of the pause is calculated based on how
long it has been since the previous call to tick(), which would have taken place at the end of
the previous iteration of the game loop. (The first time the tick() method is called, it doesn’t
pause at all.) In the animation program, is it run on line 47 as the last instruction in the game loop.
All you need to know is that you should call the tick() method once per iteration through the
game loop at the end of the loop. Usually this is right after the call to
pygame.display.update().
47. fpsClock.tick(FPS)
Try modifying the
The drawing functions are fine if you want to draw simple shapes on the screen, but many games have images (also called sprites). Pygame is able to load images onto Surface objects from PNG, JPG, GIF, and BMP image files. The differences between these image file formats is described at http://invpy.com/formats.
The image of the cat was stored in a file named cat.png. To load this file’s image, the string
'cat.png' is passed to the pygame.image.load() function. The
pygame.image.load()
If you get an "pygame.error: Couldn't open cat.png" when
calling pygame.image.load(), then make sure the cat.png file is in the same folder as the
catanimation.py file before you run the program.
39. DISPLAYSURF.blit(catImg, (catx, caty))
Line 39 of the animation program uses the method to copy catImg to DISPLAYSURF.
There are two parameters for . The first is the source DISPLAYSURF
If catx and caty were set to 100 and 200 and the width of catImg was 125 and the height
was 79, this call would copy this image onto DISPLAYSURF so that the top left corner
of the catImg was at the XY coordinate (100, 200) and the bottom right corner’s XY coordinate
was at (225, 279).
Note that you cannot
The rest of the game loop is just changing the catx, caty, and direction variables so that
the cat moves around the window. There is also a call to pygame.event.get() to handle the
QUIT event.
If you want to draw text to the screen, you could write several calls to pygame.draw.line()
to draw out the lines of each letter. This would be a headache to type out all those pygame.draw.line() calls and figure out all the XY coordinates, and probably wouldn’t
look very good.
(рис 2.11)
The above message would take forty one calls to the pygame.draw.line() function to
make. Instead, Pygame provides some much simpler functions for fonts and creating text. Here is
a small Hello World program using Pygame’s font functions. Type it into IDLE’s file editor and
save it as fonttext.py:
1. import pygame, sys
2. from pygame.locals import *
3.
4. pygame.init()
5. DISPLAYSURF = pygame.display.set_mode((400, 300))
6. pygame.display.set_caption('Hello World!')
7.
8. WHITE = (255, 255, 255)
9. GREEN = (0, 255, 0)
10. BLUE = (0, 0, 128)
11.
12. fontObj = pygame.font.Font('freesansbold.ttf', 32)
13. textSurfaceObj = fontObj.render('Hello world!', True, GREEN, BLUE)
14. textRectObj = textSurfaceObj.get_rect()
15. textRectObj.center = (200, 150)
16.
17. while True: # main game loop
18. DISPLAYSURF.fill(WHITE)
19. DISPLAYSURF.blit(textSurfaceObj, textRectObj)
20. for event in pygame.event.get():
21. if event.type == QUIT:
22. pygame.quit()
23. sys.exit()
24. pygame.display.update()
There are six steps to making text appear on the screen:
pygame.font.Font object (Like on line 12).render() method (Line 13).get_rect() method (Line 14). This Rect object will have the width and height correctly set for the text that was rendered, but the top and left attributes will be 0.pygame.display.set_mode() (Line 19).pygame.display.update() to make the display The parameters to the pygame.font.Font() constructor function is a string of the 'freesansbold.ttf' (this is a font that comes with Pygame) and the
integer 32 (for a 32-
See http://invpy.com/usingotherfonts for more info on using other fonts.
The parameters to the render()
Anti-aliasing is a graphics technique for making text and shapes look less blocky by adding a little bit of blur to their edges. It takes a little more computation time to draw with anti-aliasing, so although the graphics may look better, your program may run slower (but only just a little). If you zoom in on an aliased line and an anti-aliased line, they look like this:
(рис 2.12)
To make Pygame's text use anti-True for the second parameter of the
render() method. The pygame.draw.aaline() and pygame.draw.aalines()
functions have the same parameters as pygame.draw.line() and pygame.draw.lines(), except they will draw anti-aliased (
Playing sounds that are stored in sound files is even simpler than displaying images from image
files. First, you must create a pygame. object (which we will call Sound objects
for short) by calling the pygame. constructor function. It takes one string
parameter, which is the filename of the sound file. Pygame can load WAV, MP3, or OGG files.
The difference between these
To play this sound, call the Sound object's play() method. If you want to immediately stop the
Sound object from playing call the stop() method. The stop() method has no arguments.
Here is some
soundObj = pygame.mixer.Sound('beeps.wav')
soundObj.play()
import time
time.sleep(1) # wait and let the sound play for 1 second
soundObj.stop()
You can download the beeps.wav file from http://invpy.com/beeps.wav.
The program execution continues immediately after play() is called; it does not wait for the
sound to finish playing before moving on to the next line of code.
The Sound objects are good for sound effects to play when the player takes pygame. function and pass it a string argument of the sound file to
load. This file can be WAV, MP3, or
To begin playing the loaded sound file as the pygame. function. The -1 argument makes the
To stop playing the pygame.
function. This function has no arguments. Here is some
# Loading and playing a sound effect:
soundObj = pygame.mixer.Sound('beepingsound.wav')
soundObj.play()
# Loading and playing background music:
pygame.mixer.music.load(backgroundmusic.mp3')
pygame.mixer.music.play(-1, 0.0)
# ...some more of your code goes here...
pygame.mixer.music.stop()
This covers the basics of making graphical games with the Pygame framework. Of course, just
reading about these functions probably isn't enough to help you learn how to make games using
these functions. The rest of the chapters in this book each focus on the
Unlike the "Invent Your Own if-else statements, and conditions work, you can probably figure it out just
by seeing what’s in the code and how the program behaves. But if you are still stuck, you can
read the "Invent with Python" book (it’s for people who are completely new to programming) for
free online at http://inventwithpython.com.
Для получения официальных документов о завершении программы дополнительного профессионального образования (удостоверения о повышении квалификации, дипломов о профессиональной переподготовке и MBA) необходимо предоставить:
Внимание! Вы можете не заказывать доставку бумажной версии официального документы, а скачать его в электронном виде и распечатать самостоятельно. Информация о выданном документе в течение 1 месяца загружается в Федеральную информационную систему «Федеральный реестр сведений о документах об образовании и (или) о квалификации, документах об обучении» - ФИС ФРДО.
Доступ на новый сайт осуществляется с использованием адреса электронной почты, который был указан вами при регистрации на "старом". Мы постарались перенести все ваши данные с прежнего ресурса, однако не исключена вероятность потери части информации.
При возникновении проблемы со входом, воспользуйтесь функцией сброса пароля
Если вы обнаружите несоответствия, пожалуйста, сообщите нам.