Pygame – Moving Rectangular objects

Pygame – Moving Rectangular Objects ”; Previous Next The Pygame.Rect class has functionality to store and manipulate rectangular areas. A Rect object can be constructed from left, top, width and height values. Functions in Rect class enable copying, moving nd resizing the Rect object. A Rect object has following virtual attributes − In addition to movement, Rect class has methods to test collision between rectangles. copy() Returns a new rectangle having the same position and size as the original. move() Returns a new rectangle that is moved by the given offset. The x and y arguments can be any integer value, positive or negative. move_ip() Same as the Rect.move() method, but operates in place. inflate(x,y) Returns a new rectangle with the size changed by the given offset. Negative values will shrink the rectangle. inflate_ip(x, y) Same as the Rect.inflate() method, but operates in place. clamp(Rect) Returns a new rectangle that is moved to be completely inside the argument Rect. clip(Rect) Returns a new rectangle that is cropped to be completely inside the argument Rect. union(Rect) Returns a new rectangle that completely covers the area of the two provided rectangles. union_ip(Rect) Same as the Rect.union() method, but operates in place. contains(Rect) Returns true when the argument is completely inside the Rect. collidepoint((x,y)) Returns true if the given point is inside the rectangle. colliderect(Rect) Returns true if any portion of either rectangle overlap Example In the following program, a Rect object is drawn with red outline. Using copy() method, its clone is created for movement. The movement is effected by move_ip() method. The arrow keys move the position of copied rectangle by incrementing/decrementing x/y coordinate by + or -5 pixels. import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300)) rect1 = Rect(50, 60, 200, 80) rect2=rect1.copy() running = True x=0 y=0 while running: for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == KEYDOWN: if event.key==K_LEFT: x= -5 y=0 if event.key == K_RIGHT: x=5 y=0 if event.key == K_UP: x = 0 y = -5 if event.key == K_DOWN: x = 0 y = 5 rect2.move_ip(x,y) screen.fill((127,127,127)) pygame.draw.rect(screen, (255,0,0), rect1, 1) pygame.draw.rect(screen, (0,0,255), rect2, 5) pygame.display.update() pygame.quit() Output The following output shows rectangle with red outline is the original rectangle. Its copy keeps moving responding to arrow keys and has blue outline Example Changing the move_ip() method to inflate_ip() method to grow/shrink the rectangle depending upon the arrow pressed. while running: for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == KEYDOWN: if event.key==K_LEFT: x= -5 y=0 if event.key == K_RIGHT: x=5 y=0 if event.key == K_UP: x = 0 y = -5 if event.key == K_DOWN: x = 0 y = 5 rect2.inflate_ip(x,y) screen.fill((127,127,127)) pygame.draw.rect(screen, (255,0,0), rect1, 1) pygame.draw.rect(screen, (0,0,255), rect2, 5) pygame.display.update() Output The following is the screenshot of the arrow key-press activity − Example To make the rectangle move by detecting MOUSEMOTION event, we need to first press the mouse inside the original rectangle. To verify whether mouse position is inside the rectangle, we use collidepoint() method of the Rect object. While the mouse is in motion, the rectangle object is moved in place by move_ip() method. Movement shall stop when mouse is released. import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300)) rect = Rect(50, 60, 200, 80) moving = False running = True while running: for event in pygame.event.get(): if event.type == QUIT: running = False elif event.type == MOUSEBUTTONDOWN: if rect.collidepoint(event.pos): moving = True elif event.type == MOUSEBUTTONUP: moving = False elif event.type == MOUSEMOTION and moving: rect.move_ip(event.rel) screen.fill((127,127,127)) pygame.draw.rect(screen, (255,0,0), rect) if moving: pygame.draw.rect(screen, (0,0,255), rect, 4) pygame.display.flip() pygame.quit() Output Example To draw rectangle by mouse, capture the mouse pointer coordinates in MOUSEBUTTONDOWN and MOUSEBUTTONUP events, calculate the topleft coordinates, width and height and call rect() function. import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_caption(“Draw Rectangle with Mouse”) screen.fill((127,127,127)) x=0 y=0 w=0 h=0 drawmode=True running = True while running: for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == MOUSEBUTTONDOWN: x,y = pygame.mouse.get_pos() drawmode = True if event.type == MOUSEBUTTONUP: x1,y1 = pygame.mouse.get_pos() w=x1-x h=y1-y drawmode= False rect = pygame.Rect(x,y,w,h) if drawmode == False: pygame.draw.rect(screen, (255,0,0), rect) pygame.display.flip() pygame.quit() Output Print Page Previous Next Advertisements ”;

Pygame – Discussion

Discuss Pygame ”; Previous Next Pygame is a popular Python library used for developing video games. It is free, open source and cross-platform wrapper around Simple DirectMedia Library (SDL). Abstraction of SDL functions provided by Pygame makes development of multi-media applications using Python very easy. Print Page Previous Next Advertisements ”;

Pygame – Moving an image

Pygame – Moving an Image ”; Previous Next Movement of an object is an important aspect of any computer game. A computer game creates illusion of movement by drawing and erasing an object at incremental position. Following code draws an image by incrementing x coordinate position in an event loop and erasing it with the background color. Example image_filename = ”pygame.png” import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300), 0, 32) pygame.display.set_caption(“Moving Image”) img = pygame.image.load(image_filename) x = 0 while True: screen.fill((255,255,255)) for event in pygame.event.get(): if event.type == QUIT: exit() screen.blit(img, (x, 100)) x= x+0.5 if x > 400: x = x-400 pygame.display.update() Output The Pygame logo image starts displaying at left border and repeatedly shifts towards right. If it reaches right border, its position is reset to left. In the following program, the image is displayed at (0,150) position to begin with. When user presses arrow keys (left, right, up, down), the image changes its location by 5 pixels. If a KEYDOWN event occurs, the program checks if the key value is K_LEFT, K_RIGHT, K_UP or K_DOWN. The x coordinate changes by +5 or -5 if it is K_LEFT or K_RIGHT. Value of y coordinate changes by -5 or +5 if key value is K_UP or K_DOWN. image_filename = ”pygame.png” import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_caption(“Moving with arrows”) img = pygame.image.load(image_filename) x = 0 y= 150 while True: screen.fill((255,255,255)) screen.blit(img, (x, y)) for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN: if event.key == K_RIGHT: x= x+5 if event.key == K_LEFT: x=x-5 if event.key == K_UP: y=y-5 if event.key == K_DOWN: y=y+5 pygame.display.update() Print Page Previous Next Advertisements ”;

Pygame – Playing music

Pygame – Playing Music ”; Previous Next The mixer also has a special streaming channel for music playback and is accessed through the pygame.mixer.musicpygame module for controlling streamed audio module. The difference between the music playback and regular Sound playback is that the music is streamed, and never actually loaded all at once. The mixer system only supports a single music stream at once. First of all, we need to load the music from a music file. Pygame can load WAV, MP3, or OGG files. pygame.mixer.music.load(filename or object) This will load a music filename/file object and prepare it for playback. If a music stream is already playing it will be stopped. This does not start the music playing. The playback is controlled by following functions − play(loops=0, start=0.0, fade_ms = 0) This will play the loaded music stream. If the music is already playing it will be restarted. loops argument tells how many times to repeat the music. The music repeats indefinitely if this argument is set to -1. start denotes the music starts playing from. The position as time in seconds. fade_ms argument makes the music start playing at 0 volume and fade up to full volume over the given time. Other useful functions are given below − rewind() Resets playback of the current music to the beginning. stop() Stops the music playback if it is currently playing. It Won”t Unload the music. pause() Temporarily stop playback of the music stream. unpause() This will resume the playback of a music stream after it has been paused. fadeout(time) Fade out and stop the currently playing music. set_volume(volume) Set the volume of the music playback. set_pos(pos) This sets the position in the music file where playback will start. In the following program, a music file starts playing on clicking PLAY button. The PAUSE button acts as a toggle to pause/unpause play. Click on STOP stops the playback. import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) 20. Pygame — Playing music done = False white = (255,255,255) pygame.mixer.music.load(“mario_theme.wav”) font = pygame.font.SysFont(“Arial”, 14) text1=font.render(” PLAY “, True, white) text2=font.render(” PAUSE “, True, white) text3=font.render(” STOP “, True, white) rect1 = text1.get_rect(topleft=(10,10)) rect2 = text2.get_rect(topleft= (100,10)) rect3 = text3.get_rect(topleft= (200,10)) bg = (127,127,127) psmode=True screen = pygame.display.set_mode((400,300)) screen.fill(bg) while not done: for event in pygame.event.get(): screen.blit(text1, rect1) pygame.draw.rect(screen, (255,0,0),rect1,2) screen.blit(text2, rect2) pygame.draw.rect(screen, (255,0,0),rect2,2) pygame.draw.rect(screen, (255,0,0),rect3,2) screen.blit(text3, rect3) if event.type == pygame.QUIT: done = True if event.type == pygame.MOUSEBUTTONDOWN: if rect1.collidepoint(event.pos): pygame.mixer.music.play() if rect2.collidepoint(event.pos): if psmode==True: pygame.mixer.music.pause() psmode=False else: if psmode==False: pygame.mixer.music.unpause() psmode=True if rect3.collidepoint(event.pos): pygame.mixer.music.stop() pygame.display.update() Print Page Previous Next Advertisements ”;

Pygame – Errors and Exception

Pygame – Errors and Exception ”; Previous Next Top level pygame module defines pygame.error as a standard Pygame exception. This exception is raised whenever a pygame or SDL operation fails. You can catch any anticipated problems and deal with the error. The exception is always raised with a descriptive message about the problem. >>> import pygame pygame 1.9.6 Hello from the pygame community. https://www.pygame.org/contribute.html >>> screen = pygame.display.set_mode((640, -1)) Traceback (most recent call last): File “<pyshell#1>”, line 1, in <module> screen = pygame.display.set_mode((640, -1)) pygame.error: Cannot set negative sized display mode Being derived from the RuntimeError exception, which can also be used to catch these raised errors. >>> try: screen = pygame.display.set_mode((640, -1)) except pygame.error as e: print (“unable to set display: “, e) unable to set display Cannot set: negative sized display mode There are two more functions in this module to set and retrieve error message. set_error(error_msg) SDL maintains an internal error message. When pygame.error()standard pygame exception is raised, this string is used as error message. It gets the current error message. get_error() It returns the string as error message of pygame.error() message. Print Page Previous Next Advertisements ”;

Pygame – PyOpenGL

Pygame – PyOpenGL ”; Previous Next OpenGL is a cross-language, cross-platform API for rendering 2D and 3D vector graphics. By interacting with a graphics processing unit (GPU), it achieves hardware-accelerated rendering. PyOpenGL library is Python’s binding for OpenGL. We need to install it using pip utility − pip3 install pyopengl First we shall import functions from OpenGL.GL and OpenGL.GLU (utility functions) modules. OpenGL specifies objects within the space by defining vertices or nodes. Lines between vertices are called edges. The OpenGL code is written between glBegin and glEnd. In our example, we shall draw a cube with following vertices and edges − verticies = ( (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (1, -1, 1), (1, 1, 1), (-1, -1, 1), (-1, 1, 1) ) edges = ( (0,1), (0,3), (0,4), (2,1), (2,3), (2,7), (6,3), (6,4), (6,7), (5,1), (5,4), (5,7) ) The cube() function performs OpenGL drawing − def Cube(): glBegin(GL_LINES) for edge in edges: for vertex in edge: glVertex3fv(verticies[vertex]) glEnd() The GL_LINES attribute to glBegin() tells that lines are to be drawn. We need to specify OPENGL and DOUBLEBUF flags in set_mode() function that sets up the display. pygame.display.set_mode(display, DOUBLEBUF|OPENGL) Then call the gluPerspective() determines the perspective. The first parameter is the degree of the field of view. The second value is the aspect ratio. The next two values here are the znear and zfar, which are the near and far clipping planes. gluPerspective(45, (display[0]/display[1]), 0.1, 50.0) glTranslatef(0.0,0.0, -5) Inside the Pygame event loop, first rotate the current matrix, clear the color buffer and depth buffer, and call cube() function. Finally, we update the display window. while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() glRotatef(1, 3, 1, 1) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) Cube() pygame.display.flip() pygame.time.wait(10) Example The complete code of the example is as follows − import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * verticies = ( (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (1, -1, 1), (1, 1, 1), (-1, -1, 1), (-1, 1, 1) ) edges = ( (0,1), (0,3), (0,4), (2,1), (2,3), (2,7), (6,3), (6,4), (6,7), (5,1), (5,4), (5,7) ) def Cube(): glBegin(GL_LINES) for edge in edges: for vertex in edge: glVertex3fv(verticies[vertex]) glEnd() def main(): pygame.init() display = (800,600) pygame.display.set_mode(display, DOUBLEBUF|OPENGL) gluPerspective(45, (display[0]/display[1]), 0.1, 50.0) glTranslatef(0.0,0.0, -5) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() glRotatef(1, 3, 1, 1) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) Cube() pygame.display.flip() pygame.time.wait(10) main() Output Run the above code. You will see a rotating cube on Pygame’s window surface. This is a short demonstration of capability of PyOpenGL. A detailed discussion of this library is beyond the scope of this tutorial. Print Page Previous Next Advertisements ”;

Pygame – Mixer channels

Pygame – Mixer Channels ”; Previous Next The Sound object can be played on a specific channel instead of the default channel automatically chosen. First create a channel object using the following command − pygame.mixer.Channel(id) Following functions are defined in the mixer.channel class − play(Sound, loops=0, maxtime=0, fade_ms=0) This will begin playback of a Sound on a specific Channel. stop() Stop sound playback on a channel. After playback is stopped the channel becomes available for new Sounds to play on it pause() Temporarily stop the playback of sound on a channel. unpause() Resume the playback on a paused channel. set_volume(value) Set the volume (loudness) of a playing sound. The value argument is between 0.0 and 1.0. queue(Sound) When a Sound is queued on a Channel, it will begin playing immediately after the current Sound is finished. Print Page Previous Next Advertisements ”;

Pygame – Color object

Pygame – Color Object ”; Previous Next The Color class in Pygame is used to represent color of screen background, text, shapes and all other Pygame objects. It constructed by passing color values for Red, Green, Blue colors and optionally alpha value that represents opaque value. Each of these values range between 0 to 255. color = pygame.Color(r, g, b, a=255) Default value of alpha is 255, meaning fully opaque. Individual attributes are accessible and can be set. pygame.Color.r Gets or sets the red value of the Color. pygame.Color.g Gets or sets the green value of the Color. pygame.Color.b Gets or sets the blue value of the Color. pygame.Color.a Gets or sets the alpha value of the Color. Alternative color models like CMY, HSVA, HSLA and i1i2i3 can also be used. pygame.Color.cmy Gets or sets the CMY representation of the Color. Cyan, Magenta, Yellow pygame.Color.hsva Gets or sets the HSVA representation of the Color. Hue, Saturation, Value pygame.Color.hsla Gets or sets the HSLA representation of the Color. Hue, Saturation, Lightness pygame.Color.i1i2i3 Gets or sets the I1I2I3 representation of the Color. We can use predefined string constants to represent RGBA color combinations. Some of the predefined colors are listed below − ”black”: (0, 0, 0, 255) ”blue”: (0, 0, 255, 255), ”cyan”: (0, 255, 255, 255), ”gold”: (255, 215, 0, 255), ”gray”: (190, 190, 190, 255), ”green”: (0, 255, 0, 255), ”orange”: (255, 165, 0, 255), ”purple”: (160, 32, 240, 255), ”red”: (255, 0, 0, 255), ”violet”: (238, 130, 238, 255) ”yellow”: (255, 255, 0, 255), ”white”: (255, 255, 255, 255) To enlist all predefined colors run following for loop − for k, v in THECOLORS.items(): THECOLORS[unicode_(k)] = v Print Page Previous Next Advertisements ”;

Pygame – Use Text as Buttons

Pygame – Use Text as Buttons ”; Previous Next Button is an important element in a typical game window. We can use a text or image surface object as button, so that when clicked it can fire a certain action. Let us try to display three buttons with text captions. text1=font.render(” START “, True, white) text2=font.render(” PLAY “, True, white) text3=font.render(” STOP “, True, white) In order to draw a border around these buttons obtain their Rect object. rect1 = text1.get_rect(topleft=(10,10)) rect2 = text2.get_rect(topleft= (100,10)) rect3 = text3.get_rect(topleft= (200,10)) Inside the event loop, blit the text buttons with red border around them. screen.blit(text1, rect1) pygame.draw.rect(screen, (255,0,0),rect1,2) screen.blit(text2, rect2) pygame.draw.rect(screen, (255,0,0),rect2,2) pygame.draw.rect(screen, (255,0,0),rect3,2) screen.blit(text3, rect3) Use collidepoint() function of Rect object to identify which button has been clicked. if event.type == pygame.MOUSEBUTTONDOWN: if rect1.collidepoint(event.pos): msg = “START Button was pressed” if rect2.collidepoint(event.pos): msg = “PLAY Button was pressed” if rect3.collidepoint(event.pos): msg = “STOP Button was pressed” Display appropriate message as a text surface − img=font.render(msg, True, (0,0,255)) imgrect=img.get_rect() imgrect.center = (200 , 150 ) pygame.draw.rect(screen, bg, imgrect) screen.blit(img, imgrect) Example Following is the complete code − import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) done = False font = pygame.font.SysFont(“Arial”, 14) text1=font.render(” START “, True, white) text2=font.render(” PLAY “, True, white) text3=font.render(” STOP “, True, white) rect1 = text1.get_rect(topleft=(10,10)) rect2 = text2.get_rect(topleft= (100,10)) rect3 = text3.get_rect(topleft= (200,10)) bg = (127,127,127) msg=” “ screen = pygame.display.set_mode((400,300)) screen.fill(bg) while not done: for event in pygame.event.get(): screen.blit(text1, rect1) pygame.draw.rect(screen, (255,0,0),rect1,2) screen.blit(text2, rect2) pygame.draw.rect(screen, (255,0,0),rect2,2) pygame.draw.rect(screen, (255,0,0),rect3,2) screen.blit(text3, rect3) if event.type == pygame.QUIT: done = True if event.type == pygame.MOUSEBUTTONDOWN: if rect1.collidepoint(event.pos): msg = “START Button was pressed” if rect2.collidepoint(event.pos): msg = “PLAY Button was pressed” if rect3.collidepoint(event.pos): msg = “STOP Button was pressed” img=font.render(msg, True, (0,0,255)) imgrect=img.get_rect() imgrect.center = (200 , 150 ) pygame.draw.rect(screen, bg, imgrect) screen.blit(img, imgrect) pygame.display.update() Output When each button is clicked, display window shows the following output − Print Page Previous Next Advertisements ”;

Pygame – Moving with Numeric pad keys

Pygame – Moving with Numeric Pad Keys ”; Previous Next If we want to effect diagonal movement of an object on game window, we need to use numeric key pad keys. While keys 4,6,8 and 2 correspond to left, right, up and down arrows, num keys 7, 9, 3 and 1 can be used to move the object in up-left, up-right, down-right and down-left diagonal movements. These keys are identified by Pygame with following values − K_KP1 keypad 1 K_KP2 keypad 2 K_KP3 keypad 3 K_KP4 keypad 4 K_KP5 keypad 5 K_KP6 keypad 6 K_KP7 keypad 7 K_KP8 keypad 8 K_KP9 keypad 9 Example For left, right, up and down arrow press, x and y coordinates are incremented/decremented as before. For diagonal movement, both coordinates are changed as per direction. For instance, for K_KP7 key-press, both x and y are decremented by 5, for K_KP9 x is incremented and y is decremented. image_filename = ”pygame.png” import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_caption(“Moving with arrows”) img = pygame.image.load(image_filename) x = 0 y= 150 while True: screen.fill((255,255,255)) screen.blit(img, (x, y)) for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN: if event.key == K_KP6: x= x+5 if event.key == K_KP4: x=x-5 if event.key == K_KP8: y=y-5 if event.key == K_KP2: y=y+5 if event.key == K_KP7: x=x-5 y=y-5 if event.key == K_KP9: x=x+5 y=y-5 if event.key == K_KP3: x=x+5 y=y+5 if event.key == K_KP1: x=x-5 y=y+5 pygame.display.update() Print Page Previous Next Advertisements ”;