diff --git a/docs/1_intro/intro.rst b/docs/1_intro/intro.rst index 8aa4ad2..9295a7f 100644 --- a/docs/1_intro/intro.rst +++ b/docs/1_intro/intro.rst @@ -5,7 +5,7 @@ Pygame is a multimedia library for Python for making games and multimedia applications. It is a wrapper around the SDL (Simple DirectMedia Layer) library. -In this section we indroduce the basics of pygame functions without defining classes and objects. +In this section we introduce the basics of pygame functions without defining classes and objects. Import the module @@ -24,15 +24,15 @@ Pygame website to the console (as a side effect):: The Pygame import statement is always placed at the beginning of the program. It imports the pygame classes, methods and attributes into the current name space. -Now this new methods can be called via ``pygame.method()``. +Now these new methods can be called via ``pygame.method()``. -For exemple we can now initialize or quit **pygame** with the following command:: +For example we can now initialize or quit **pygame** with the following command:: pygame.init() pygame.quit() The function ``display.set_mode()`` sets the screen size. It returns -a ``Surface`` object wich we assign to the variable ``screen``. +a ``Surface`` object which we assign to the variable ``screen``. This variable will be one of the most used variables. It represents the window we see:: @@ -62,14 +62,14 @@ The following is an infinite loop which prints all events to the console:: Try to move the mouse, click a mouse button, or type something on the keyboard. Every action you do produces an event which will be printed on the console. -This will look something like this:: +It will look something like this:: -As we are in an infite loop, it is impossible to quit this program from within the application. +As we are in an infinite loop, it is impossible to quit this program from within the application. In order to quit the program, make the console the active window and type ``ctrl-C``. This will write the following message to the console:: @@ -98,7 +98,7 @@ If it occurs, we set ``running`` to ``False``:: pygame.quit() -Once the event loop, we call the ``pygame.quit()`` function to end the application +Once the event loop ends, we call the ``pygame.quit()`` function to end the application correctly. .. image:: intro2.png @@ -119,7 +119,7 @@ A total of 16 million different colors can be represented this way. .. image:: AdditiveColorMixing.png :scale: 50 % -Let's define the base colors as tuples of the tree base values. +Let's define the base colors as tuples of the three base values. Since colors are constants, we will write them using capitals. The absence of all colors results in black. The maximum value for all three components results in white. @@ -129,13 +129,13 @@ Three identical intermediate values result in gray:: GRAY = (127, 127, 127) WHITE = (255, 255, 255) -The tree base colors are defined as:: +The three base colors are defined as:: RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) -By mixing two base colors we obtained more colors:: +By mixing two base colors we obtain more colors:: YELLOW = (255, 255, 0) CYAN = (0, 255, 255) @@ -158,7 +158,7 @@ At this point nothing will be displayed. In order to show anything, the function Switch the background color --------------------------- -At the beginning of the program we add a new veriable ``background`` +At the beginning of the program we add a new variable ``background`` and initialize it to gray:: background = GRAY @@ -188,8 +188,8 @@ Pressing the R and G keys allows you to switch the background color. Import pygame.locals -------------------- -The ``pygame.locals`` module contains some 280 constants used and defined by pygme. -Placing this statement at the beginning of your programm imports them all:: +The ``pygame.locals`` module contains some 280 constants used and defined by pygame. +Placing this statement at the beginning of your program imports them all:: import pygame from pygame.locals import * @@ -221,10 +221,10 @@ Instead of writing ``pygame.KEYDOWN`` we can now just write ``KEYDOWN``. Use a dictionary to decode keys ------------------------------- -The easiest way to decode many keys, is to use a dictionary. +The easiest way to decode many keys is to use a dictionary. Instead of defining many if-else cases, we just create a dictionary with the keyboard key entries. -In this exemple we want to associate 8 different keys with 8 different background colors. -At the beginning of the programm we define this key-color dictionary:: +In this example we want to associate 8 different keys with 8 different background colors. +At the beginning of the program we define this key-color dictionary:: key_dict = {K_k:BLACK, K_r:RED, K_g:GREEN, K_b:BLUE, K_y:YELLOW, K_c:CYAN, K_m:MAGENTA, K_w:WHITE} @@ -236,7 +236,7 @@ Printing the dictionary to the console gives this result:: {107: (0, 0, 0), 114: (255, 0, 0), 103: (0, 255, 0), 98: (0, 0, 255), 121: (255, 255, 0), 99: (0, 255, 255), 109: (255, 0, 255), 119: (255, 255, 255)} -The keys are presented here with their ASCII code. For exaple the ASCII code for +The keys are presented here with their keycode. For example the keycode for ``k`` is 107. Colors are represented as tuples. The color black is represented as (0, 0, 0). The event loop now becomes very simple. @@ -256,7 +256,7 @@ Try to press the 8 specified keys to change the background color. Change the window caption ------------------------- -The fonction ``pygame.display.set_caption(title)`` allows to change the caption (title) +The function ``pygame.display.set_caption(title)`` allows us to change the caption (title) of the application window. We can add this to the event loop:: if event.key in key_dict: @@ -331,22 +331,24 @@ Then we move the rectangle and check the left/right and top/bottom borders:: if rect.top < 0 or rect.bottom > height: speed[1] = -speed[1] -Finaly we draw a green background, a red rectangle and the ball image:: +Finally we draw a green background, a red rectangle and the ball image:: screen.fill(GREEN) pygame.draw.rect(screen, RED, rect, 1) screen.blit(ball, rect) pygame.display.update() +When the event loop ends, close the application:: + pygame.quit() -This is what the ball and the ``Rect`` outline looks: +This is what the ball and the ``Rect`` outline looks like: .. image:: intro6.png :download:`ball.gif` Try to understand what the program does. -Then try to modify it's parameters. +Then try to modify its parameters. -:download:`intro6.py` \ No newline at end of file +:download:`intro6.py` diff --git a/docs/2_draw/draw.rst b/docs/2_draw/draw.rst index 907ef75..05be1e0 100644 --- a/docs/2_draw/draw.rst +++ b/docs/2_draw/draw.rst @@ -1,8 +1,9 @@ Drawing graphics primitives ============================ -The ``pygame.draw`` module allows to draw simple shapes to a surface. -This can be the screen surface or any Surface object such as an image or drawing: +The ``pygame.draw`` module allows us to draw simple shapes to a surface. +This can be the screen surface or any Surface object such as an image or drawing. +The available shapes include: - rectangle - polygon @@ -11,9 +12,9 @@ This can be the screen surface or any Surface object such as an image or drawing The functions have in common that they: -- take a **Surface** object as first argument -- take a color as second argument -- take a width parameter as last argument +- take a **Surface** object as the first argument +- take a color as the second argument +- take a width parameter as a keyword argument - return a **Rect** object which bounds the changed area the following format:: @@ -28,7 +29,7 @@ Draw solid and outlined rectangles ---------------------------------- The following draws first the background color and then adds three overlapping solid rectangles -and next to it three oulined overlapping rectangles with increasing line width:: +and next to them three outlined overlapping rectangles with increasing line width:: screen.fill(background) pygame.draw.rect(screen, RED, (50, 20, 120, 100)) @@ -41,14 +42,14 @@ and next to it three oulined overlapping rectangles with increasing line width:: .. image:: draw1.png -Try to modifiy the parameters and play with the drawing function. +Try to modify the parameters and play with the drawing function. Draw solid and outlined ellipses -------------------------------- The following code draws first the background color and then adds three overlapping solid ellipses -and next to it three oulined overlapping ellipses with increasing line width:: +and next to them three outlined overlapping ellipses with increasing line width:: screen.fill(background) pygame.draw.ellipse(screen, RED, (50, 20, 160, 100)) @@ -70,7 +71,7 @@ Detect the mouse ---------------- Pressing the mouse buttons produces MOUSEBUTTONDOWN and MOUSEBUTTONUP events. -The flollowing code in the event loop detects them and writes the event to the console:: +The following code in the event loop detects them and writes the event to the console:: for event in pygame.event.get(): if event.type == QUIT: @@ -80,7 +81,7 @@ The flollowing code in the event loop detects them and writes the event to the c elif event.type == MOUSEBUTTONUP: print(event) -Pressing the mouse buttons produces this kind of events:: +Pressing the mouse buttons produces these kinds of events:: @@ -88,12 +89,12 @@ Pressing the mouse buttons produces this kind of events:: Just moving the mouse produces a MOUSEMOTION event. -The following code detects them an writes the event to the console:: +The following code detects them and writes the event to the console:: elif event.type == MOUSEMOTION: print(event) -Moving the mosue produces this kind of event:: +Moving the mouse produces this kind of event:: @@ -103,7 +104,7 @@ Moving the mosue produces this kind of event:: Draw a rectangle with the mouse ------------------------------- -We can use this three events to draw a rectangle on the screen. +We can use these three events to draw a rectangle on the screen. We define the rectangle by its diagonal start and end point. We also need a flag which indicates if the mouse button is down and if we are drawing:: @@ -112,7 +113,7 @@ We also need a flag which indicates if the mouse button is down and if we are dr drawing = False When the mouse button is pressed, we set start and end to the current mouse position -and indciate with the flag that the drawing mode has started:: +and indicate with the flag that the drawing mode has started:: elif event.type == MOUSEBUTTONDOWN: start = event.pos @@ -169,7 +170,7 @@ MOUSEBUTTONUP event, we create a rectangle and append it to the rectangle list:: drawing = False In the drawing code, we first fill the background color, then iterate through the -rectagle list to draw the objects (red, thickness=3), and finally we draw the current rectangle which +rectangle list to draw the objects (red, thickness=3), and finally we draw the current rectangle which is in the process of being drawn (blue, thickness=1):: screen.fill(GRAY) @@ -236,4 +237,4 @@ Here is the complete file: .. literalinclude:: mouse4.py -:download:`mouse4.py` \ No newline at end of file +:download:`mouse4.py` diff --git a/docs/3_image/image.rst b/docs/3_image/image.rst index 0fb0350..1660947 100644 --- a/docs/3_image/image.rst +++ b/docs/3_image/image.rst @@ -4,7 +4,7 @@ Work with images Load an image ------------- -The ``pyagme.image`` module provides methods for loading and saving +The ``pygame.image`` module provides methods for loading and saving images. The method ``load()`` loads an image from the file system and returns a Surface object. The method ``convert()`` optimizes the image format and makes drawing faster:: @@ -40,7 +40,7 @@ Then we blit the image, draw a red rectangle around it and finally update the sc Move the image with the mouse ----------------------------- -At the beginning of the programm we set a boolean variable ``moving`` to False. +At the beginning of the program we set a boolean variable ``moving`` to False. Only when the mouse button is pressed, and when the mouse position is within the image (collidepoint) we set it to True:: elif event.type == MOUSEBUTTONDOWN: @@ -82,7 +82,7 @@ In order to show the image rectangle, we add a green border to the original imag rect0 = img0.get_rect() pygame.draw.rect(img0, GREEN, rect0, 1) -Then we place the place the image in the center of the screen:: +Then we place the image in the center of the screen:: center = w//2, h//2 img = img0 @@ -94,9 +94,9 @@ First we define the global variables **scale** and **angle**:: angle = 0 scale = 1 -We use the R key to increment rotation by 10 degrees and -(decrement if the SHIFT key is pressed). The function ``rotozoom()`` allows to combine -rotation and scaling. We always transform the orignial image (img0). Repeated rotation or scaling of +We use the R key to increment rotation by 10 degrees +(or decrement if the SHIFT key is pressed). The function ``rotozoom()`` allows us to combine +rotation and scaling. We always transform the original image (img0). Repeated rotation or scaling of an image would degrade its quality:: if event.type == KEYDOWN: @@ -118,7 +118,7 @@ is pressed):: img = pygame.transform.rotozoom(img0, angle, scale) As the image is transformed the bounding rectangle changes size. It must be -recalulated and placed at the center again:: +recalculated and placed at the center again:: rect = img.get_rect() rect.center = center @@ -150,14 +150,14 @@ and the V key to flip the image vertically:: Detect edges with the Laplacian ------------------------------- -The fonction ``laplacien(img)`` allows to detect the outline of the image:: +The function ``laplacian(img)`` allows us to detect the outline of the image:: elif event.key == K_l: img = pygame.transform.laplacian(img) .. image:: image2.png -The fonction ``scale2x(img)`` doubles the size of a pixel:: +The function ``scale2x(img)`` doubles the size of a pixel:: elif event.key == K_2: img = pygame.transform.scale2x(img) @@ -172,7 +172,7 @@ At the beginning we import the ``math`` module:: import math -At the beginning we store the initial mouse position:: +We store the initial mouse position:: mouse = pygame.mouse.get_pos() @@ -186,8 +186,8 @@ We also calculate the center-mouse distance **d** :: y = mouse[1] - center[1] d = math.sqrt(x ** 2 + y ** 2) -The ``atan2(y, x)`` math function allows to find the rotation angle. We need to -transform radians in degrees. From the distance mouse-center we calculate the +The ``atan2(y, x)`` math function allows us to find the rotation angle. We need to +transform radians to degrees. From the distance mouse-center we calculate the scale argument:: angle = math.degrees(-math.atan2(y, x)) @@ -196,8 +196,8 @@ scale argument:: rect = img.get_rect() rect.center = center -To finally draw the transformed image we first fille the whole screen background (GRAY), -blit the transformed image, surround it with a red rectangle. +To finally draw the transformed image we first fill the whole screen background (GRAY), +blit the transformed image, and surround it with a red rectangle. In order to give visual feedback for the mouse action when transforming an image, we @@ -218,4 +218,4 @@ Here is the full code. .. literalinclude:: image2.py -:download:`image2.py` \ No newline at end of file +:download:`image2.py` diff --git a/docs/4_text/text.rst b/docs/4_text/text.rst index 40ef10a..d9b68bf 100644 --- a/docs/4_text/text.rst +++ b/docs/4_text/text.rst @@ -20,7 +20,7 @@ A newline character is not rendered. Initialize a font ----------------- -Initializing the font can take a few seconds. On a MacBook Air the the creation of +Initializing the font can take a few seconds. On a MacBook Air the creation of a system Font object:: t0 = time.time() @@ -102,7 +102,7 @@ is juxtaposed to the text bounding rectangle:: cursor = Rect(rect.topright, (3, rect.height)) Inside the event loop we watch out for KEYDOWN events. If the key press is a -BACKSPACE and the lenght of the string is larger than 0, then we remove the last character, +BACKSPACE and the length of the string is larger than 0, then we remove the last character, else we append the new character to the text variable:: if event.type == KEYDOWN: diff --git a/docs/5_app/app.rst b/docs/5_app/app.rst index d4310bd..3dcb769 100644 --- a/docs/5_app/app.rst +++ b/docs/5_app/app.rst @@ -4,10 +4,10 @@ Making apps with Pygame In this section we are going to create applications and games with Pygame. From here on we will be using an object-oriented programming (OOP) approach. -Pygame only allows to create one single window. Different from other applications, +Pygame only allows us to create one single window. Different from other applications, those based on Pygame cannot have multiple windows. If for example dialog window is needed, it must be displayed within the main window. -Within an application we provide multples scenes (environments, rooms, or levels). +Within an application we provide multiple scenes (environments, rooms, or levels). Each scene contains different objects such as: - text @@ -24,7 +24,7 @@ the ``pygame`` module, as well as a series of useful constants:: import pygame from pygame.locals import * -Then we create define the App class which initializes Pygame and opens a the app +Then we define the App class which initializes Pygame and opens the app window:: class App: @@ -48,7 +48,7 @@ Further we have to define the main event loop:: App.running = False pygame.quit() -At the end of the module we run a demo, if the programm is run directly and not +At the end of the module we run a demo, if the program is run directly and not imported as a module:: if __name__ == '__main__': @@ -74,7 +74,7 @@ instantiate text objects:: self.set_font() self.render() -The ``Font`` object needs to be created initially and everytime +The ``Font`` object needs to be created initially and every time the font name or the font size changes:: def set_font(self): @@ -116,10 +116,10 @@ intercept the S key and print a message:: if event.key == K_s: print('Key press S') -If the application has many shortcuts, the keys alone may not be enoufht and modifier keys (cmd, ctrl, alt, shift) can be used +If the application has many shortcuts, the keys alone may not be enough and modifier keys (cmd, ctrl, alt, shift) can be used to increase the number of combinations. The easiest way to represent these shortcuts is under the form of a dictionary, -where the key/mod tuples are associated with a command strings. +where the key/mod tuples are associated with command strings. The dictionary has this shape:: self.shortcuts = { @@ -217,7 +217,7 @@ and make this scene the current scene:: App.scenes.append(self) App.scene = self -Then we set a scene id, which is kept as class attribute of the Scene class. +Then we set a scene id, which is kept as a class attribute of the Scene class. Then we set the nodes list to the empty list and set the background color:: # Set the instance id and increment the class id @@ -324,7 +324,7 @@ node gap or node direction can be changed:: Here we change the node placement direction to horizontal, dir=(0, 1). At any time we can change the node position or gap. -We can place the inital node position at (0, 0) and change the gap to (0, 0):: +We can place the initial node position at (0, 0) and change the gap to (0, 0):: Scene(caption='Nodes - horizontal placement') Node(dir=(1, 0), pos=(0, 0), gap=(0, 0)) @@ -337,7 +337,7 @@ We can place the inital node position at (0, 0) and change the gap to (0, 0):: .. image:: node1b.png -The placement can also be diagonal by chosing the direction vector +The placement can also be diagonal by choosing the direction vector dir = (1, 1):: Scene(caption='Nodes - diagonale placement') @@ -349,4 +349,4 @@ dir = (1, 1):: Here is the complete code: -.. literalinclude:: node1.py \ No newline at end of file +.. literalinclude:: node1.py diff --git a/docs/6_gui/gui.rst b/docs/6_gui/gui.rst index 8340625..6de69f8 100644 --- a/docs/6_gui/gui.rst +++ b/docs/6_gui/gui.rst @@ -6,10 +6,10 @@ The graphical user interface (GUI) consists of all the elements the user can int - text - button -- checkbutton -- radiobutton +- checkbox +- radio button - menu (pop-up, pull-down) -- listboxe +- listbox - slider Text attributes @@ -87,7 +87,7 @@ In the vertical direction the text image can be aligned at the top, middle or bo self.img0.blit(self.text_img, (x, y)) self.img = self.img0.copy() -The image `img0` is the orignal, used for scaling. The `img` is the one used for drawing. +The image `img0` is the original, used for scaling. The `img` is the one used for drawing. Here is a code example: @@ -127,9 +127,9 @@ The class attribute ``TextEdit.cursor`` defines the cursor color and width:: cursor = Color('red'), 2 # cursor color and width -Inside the conxtructor, the cursor is placed at the end of the text. +Inside the constructor, the cursor is placed at the end of the text. A cursor image is created and filled with the cursor color. The cursor rectangle -is initally placed at the end of the text:: +is initially placed at the end of the text:: col, d = TextEdit.cursor self.cursor = len(self.text) @@ -142,7 +142,7 @@ Get the character index ^^^^^^^^^^^^^^^^^^^^^^^ The cursor is represented as an integer index in the range [0 .. n] where n is the -lenght of the text. Each letter has a different width. The list +length of the text. Each letter has a different width. The list ``self.char_positions`` remembers the x position of each letter:: def set_char_positions(self): @@ -165,9 +165,9 @@ When we click with the mouse anywhere in the text, we need to know the character Move the cursor ^^^^^^^^^^^^^^^ -The arrow keys allow to move the cursor to the left or to the right. +The arrow keys allow us to move the cursor to the left or to the right. The argument ``d`` is 1 or -1 and indicates the direction of movement. -The cursor movement is limit to the interval [0 .. n]:: +The cursor movement is limited to the interval [0 .. n]:: def move_cursor(self, d): """Move the cursor by d charactors, and limit to text length.""" @@ -293,4 +293,4 @@ The text printed to the console looks like this: 4 clicks in Text0 3 clicks in Ellipse1 1 clicks in Rectangle2 - 2 clicks in None \ No newline at end of file + 2 clicks in None diff --git a/docs/7_sound/sound.rst b/docs/7_sound/sound.rst index 71d8a4f..d2d6be3 100644 --- a/docs/7_sound/sound.rst +++ b/docs/7_sound/sound.rst @@ -4,10 +4,10 @@ Playing sound Making sounds ------------- -The ``pygame.mixer`` module allows to play compressed OGG files or uncompressed WAV files. +The ``pygame.mixer`` module allows us to play compressed OGG files or uncompressed WAV files. This checks the initialization parameters and prints the number of channels available. -It opens a sound object and prays it:: +It opens a sound object and plays it:: print('init =', pygame.mixer.get_init()) print('channels =', pygame.mixer.get_num_channels()) @@ -27,4 +27,4 @@ Here is a code example: Which produces the following result. -.. image:: sound1.png \ No newline at end of file +.. image:: sound1.png diff --git a/docs/9_board/board.rst b/docs/9_board/board.rst index ad4f43f..618d378 100644 --- a/docs/9_board/board.rst +++ b/docs/9_board/board.rst @@ -2,7 +2,7 @@ Board Games =========== In this section we create the framework for board games. -These games are based on a nxm grid. Each cell can have +These games are based on a NxM grid. Each cell can have * text * color @@ -24,4 +24,4 @@ Adding background color Create a checkerboard pattern ----------------------------- -.. image:: board4.png \ No newline at end of file +.. image:: board4.png diff --git a/docs/rect/rect.rst b/docs/rect/rect.rst index eb9bab7..7e690ac 100644 --- a/docs/rect/rect.rst +++ b/docs/rect/rect.rst @@ -176,8 +176,8 @@ if the rectangle is outside of the application window. The common code --------------- -The common has been placed to a separate file: +The common code has been placed in a separate file: .. literalinclude:: rect.py -:download:`rect.py` \ No newline at end of file +:download:`rect.py`