Pygame – Mouse events

Pygame – Mouse Events ”; Previous Next Pygame recongnizes three mouse events, namely, MOUSEMOTION, MOUSEBUTTONUP, and MOUSEBUTTONDOWN. The corresponding event object returns the coordinates of position at which mouse is pressed/released and the button number. For example, a MOUSEBUTTONDOWN event object will display following result − <Event(1025-MouseButtonDown {”pos”: (398, 328), ”button”: 1, ”window”: None})> Example To obtain the coordinates of position of button down, we can use get_pos() function associated with event object. import pygame, sys pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption(“Hello World”) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: pos=pygame.mouse.get_pos() btn=pygame.mouse print (“x = {}, y = {}”.format(pos[0], pos[1])) Output Run above code and press the mouse button at random positions on the game window. x = 192, y = 160 x = 419, y = 245 x = 204, y = 405 x = 449, y = 17 x = 12, y = 15 The MOUSEMOTION event object captures instantaneous position of moving mouse location. if event.type == pygame.MOUSEMOTION: pos=event.pos print (“x = {}, y = {}”.format(pos[0], pos[1])) Other important functions and attributes in pygame.mouse module are as follows − pygame.key.get_pressed get the state of the mouse buttons pygame.mouse.get_pos get the mouse cursor position pygame.mouse.get_rel get the amount of mouse movement pygame.mouse.set_pos set the mouse cursor position pygame.mouse.set_visible hide or show the mouse cursor pygame.mouse.get_visible get the current visibility state of the mouse cursor pygame.mouse.get_focused check if the display is receiving mouse input pygame.mouse.set_cursor set the image for the mouse cursor pygame.mouse.set_system_cursor set the mouse cursor to a system variant Pygame defines following system cursors − pygame.SYSTEM_CURSOR_ARROW arrow pygame.SYSTEM_CURSOR_IBEAM i-beam pygame.SYSTEM_CURSOR_WAIT wait pygame.SYSTEM_CURSOR_CROSSHAIR crosshair pygame.SYSTEM_CURSOR_SIZENWSE double arrow pointing northwest and southeast pygame.SYSTEM_CURSOR_SIZENESW double arrow pointing northeast and southwest pygame.SYSTEM_CURSOR_SIZEWE double arrow pointing west and east pygame.SYSTEM_CURSOR_SIZENS double arrow pointing north and south pygame.SYSTEM_CURSOR_SIZEALL four pointed arrow pygame.SYSTEM_CURSOR_NO slashed circle or crossbones pygame.SYSTEM_CURSOR_HAND hand Following statement will set the game window cursor to crosshair. pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_CROSSHAIR) Print Page Previous Next Advertisements ”;

Pygame – Displaying Text in Window

Pygame – Displaying Text in Window ”; Previous Next To display text on the Pygame window, we need to obtain a font object first, with the help of SysFont() function defined in pygame.font module. Fnt= SysFont(name, size, bold=False, italic=False) List of fonts installed in current machine can be obtained by get_fonts() function. fonts = pygame.font.get_fonts() for f in fonts: print(f) Let us define a font object representing Arial font of 36 point size. font = pygame.font.SysFont(“Arial”, 36) Next we obtain a new Surface object for rendering Hello World text in the newly created font with render() method of Font object. txtsurf = font.render(“Hello, World”, True, white) First argument is a one-line string, second argument represents antialias. If it is set to False, the rendered image is an 8-bit image, and 24-bit if true. An optional background color argument can also be used. We now need to blit the text Surface at the center of screen window. screen.blit(txtsurf,(200 – txtsurf.get_width() // 2, 150 – txtsurf.get_height() // 2)) Example Following is the complete code − import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) done = False white=(255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) bg = (127,127,127) while not done: for event in pygame.event.get(): screen.fill(bg) if event.type == pygame.QUIT: done = True font = pygame.font.SysFont(“Arial”, 36) txtsurf = font.render(“Hello, World”, True, white) screen.blit(txtsurf,(200 – txtsurf.get_width() // 2, 150 – txtsurf.get_height() // 2)) pygame.display.update() Output In addition to SysFont() method, a Font object can also be obtained from a font file (having .ttf extension) or a Python file object pointing towards the ttf file. It is also possible to construct a font object with .ttc file. The font class defines following methods − bold() Gets or sets whether the font should be rendered in bold. italic() Gets or sets whether the font should be rendered in italics. underline() Gets or sets whether the font should be rendered with an underline. render() draw text on a new Surface size() calculate size needed to render text set_underline() control if text is rendered with an underline get_underline() check if text will be rendered with an underline set_bold() enable fake rendering of bold text get_bold() check if text will be rendered bold set_italic() enable fake rendering of italic text metrics() gets the metrics for each character get_italic() check if the text will be rendered italic get_linesize() get the line space of the font text get_height() get the height of the font get_ascent() get the ascent of the font get_descent() get the descent of the font Given below is example to use ttf and ttc files to render text. font1 = pygame.font.SysFont(”chalkduster.ttf”, 72) img1 = font1.render(”Hello World”, True, BLUE) font2 = pygame.font.SysFont(”didot.ttc”, 72) img2 = font2.render(”Hello Pygame”, True, GREEN) screen.blit(img1, (20, 50)) screen.blit(img2, (20, 120)) pygame.display.update() In the above example, a predefined string has been rendered as a surface object. However, it is possible to read key value of KEYDOWN event to interactively enter a string and display it. To begin with, we render an empty string. Next, we define the bounding rectangle and then a cursor rectangle which is placed to overlap the text bounding rectangle. Each keystroke identified in KEYDOWN event is appended to original empty string and repeatedly rendered. Example Following code initially displays a blank window. Each letter pressed will be displayed alongside each other. import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) done = False white=(255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) bg = (127,127,127) text=”” while not done: for event in pygame.event.get(): screen.fill(bg) if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: text=text+event.unicode font = pygame.font.SysFont(“Arial”, 36) img = font.render(text, True, white) rect = img.get_rect() cursor = pygame.Rect(rect.topright, (3, rect.height)) img = font.render(text, True, white) rect.size=img.get_size() cursor.topleft = rect.topright screen.blit(img,(200 – img.get_width() // 2, 150 – img.get_height() // 2)) pygame.display.update() Output Run the above code and enter some text. Sample output is as follows − Print Page Previous Next Advertisements ”;

Pygame – Load cursor

Pygame – Load Cursor ”; Previous Next Pygame can let you control system cursor. Onlu black and white cursors can be used in Pygame. The pygame.cursors module defines contain predefined cursor enumerations. pygame.cursors.arrow pygame.cursors.diamond pygame.cursors.broken_x pygame.cursors.tri_left pygame.cursors.tri_right The arrow cursor is the default choice. To use another cursor, we use set_cursor() function in pygame.mouse module. pygame.mouse.set_cursor(pygame.cursors.broken_x) Example In the following example, this cursor can be seen on the display window. import pygame,sys from pygame.locals import * pygame.init() pygame.mouse.set_cursor(pygame.cursors.broken_x) canvas=pygame.display.set_mode((400,300)) pygame.display.set_caption(“Cursor”) while True: for event in pygame.event.get(): if(event.type == QUIT): pygame.quit() sys.exit(1) Output This module also contains a few cursors as formatted strings. To use them, use pygame.cursors.compile() function. pygame.cursors.thickarrow_strings pygame.cursors.sizer_x_strings pygame.cursors.sizer_y_strings pygame.cursors.sizer_xy_strings pygame.cursor.textmarker_strings cursor = pygame.cursors.compile(pygame.cursors.textmarker_strings) pygame.mouse.set_cursor((10,10), (0, 0), *cursor) Print Page Previous Next Advertisements ”;

Pygame – Using Camera module

Pygame – Using Camera Module ”; Previous Next Earlier versions of Pygame upto 1.9.6 contain pygame.camera module. This module contains functionality to capture camera feed on the game window and grab an image from it. The camera devices available to the system are enumerated in a list returned by list_cameras() method. pygame.camera.list_cameras() To initialize a camera object, use camera id, resolution and format arguments. pygame.camera.Camera(device, (width, height), format) The default format is RGB. Width and height parameters are by default 640×480. The camera module has following methods defined in Camera class. pygame.camera.Camera.start() opens, initializes, and starts capturing pygame.camera.Camera.stop() stops, uninitializes, and closes the camera pygame.camera.Camera.get_controls() gets current values of user controls pygame.camera.Camera.set_controls() changes camera settings if supported by the camera pygame.camera.Camera.get_size() returns the dimensions of the images being recorded pygame.camera.Camera.query_image() checks if a frame is ready pygame.camera.Camera.get_image() captures an image as a Surface pygame.camera.Camera.get_raw() returns an unmodified image as a string Example Following programs captures live feed from computer’s default web camera. import pygame import pygame.camera pygame.init() gameDisplay = pygame.display.set_mode((640,480)) pygame.camera.init() print (pygame.camera.list_cameras()) cam = pygame.camera.Camera(0) cam.start() while True: img = cam.get_image() gameDisplay.blit(img,(0,0)) pygame.display.update() for event in pygame.event.get() : if event.type == pygame.QUIT : cam.stop() pygame.quit() exit() Please note that on Windows OS, you may have to install Videocapture module. pip3 install VideoCapture Output Print Page Previous Next Advertisements ”;

Pygame – Drawing shapes

Pygame – Drawing Shapes ”; Previous Next Different shapes such as rectangle, circle, ellipse, polygon and line can be drawn on the game window by using functions in pygame.draw module − draw a rectangle rect(surface, color, rect) draw a polygon polygon(surface, color, points) draw a circle circle(surface, color, center, radius) draw an ellipse ellipse(surface, color, rect) draw an elliptical arc arc(surface, color, rect, start_angle, stop_angle) draw a straight line line(surface, color, start_pos, end_pos, width) Example Following example uses these functions to draw different shapes − import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) done = False red = (255,0,0) green = (0,255,0) blue = (0,0,255) white = (255,255,255) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.draw.rect(screen, red, pygame.Rect(100, 30, 60, 60)) pygame.draw.polygon(screen, blue, ((25,75),(76,125),(275,200),(350,25),(60,280))) pygame.draw.circle(screen, white, (180,180), 60) pygame.draw.line(screen, red, (10,200), (300,10), 4) pygame.draw.ellipse(screen, green, (250, 200, 130, 80)) pygame.display.update() Output If an optional integer parameter is added to the functions, the shape will be drawn with specified color as outline color. Number corresponds to thickness of the outline and background color inside the shape. pygame.draw.rect(screen, red, pygame.Rect(100, 30, 60, 60),1) pygame.draw.circle(screen, white, (180,180), 60,2) pygame.draw.ellipse(screen, green, (250, 200, 130, 80),5) Output Print Page Previous Next Advertisements ”;

Pygame – Playing Movie

Pygame – Playing Movie ”; Previous Next Pygame has discontinued support for video files in its latest version. However, earlier versions on Python 2.7 distributions, it can be still used. For this section, Pygame 1.9.2 and Python 2.7.18 has been used. The pygame.movie module supports playback video and audio from basic encoded MPEG-1 video files. Movie playback happens in background threads, which makes playback easy to manage. the pygame.mixerpygame module for loading and playing sounds module must be uninitialized if the movie’s sound is to be played. To begin with obtain a Movie object by following syntax − movie = pygame.movie.Movie(”sample.mpg”) The Movie class provides following methods to control playback. pygame.movie.Movie.play start playback of a movie pygame.movie.Movie.stop stop movie playback pygame.movie.Movie.pause temporarily stop and resume playback pygame.movie.Movie.skip advance the movie playback position pygame.movie.Movie.rewind restart the movie playback pygame.movie.Movie.get_time get the current vide playback time pygame.movie.Movie.get_length the total length of the movie in seconds pygame.movie.Movie.get_size get the resolution of the video pygame.movie.Movie.has_audio check if the movie file contains audio pygame.movie.Movie.set_volume set the audio playback volume pygame.movie.Movie.set_display set the video target Surface Following code plays a .MPG file on the Pygame display window. − import pygame FPS = 60 pygame.init() clock = pygame.time.Clock() movie = pygame.movie.Movie(”sample_640x360.mpg”) screen = pygame.display.set_mode(movie.get_size()) movie_screen = pygame.Surface(movie.get_size()).convert() movie.set_display(movie_screen) movie.play() playing = True while playing: for event in pygame.event.get(): if event.type == pygame.QUIT: movie.stop() playing = False screen.blit(movie_screen,(0,0)) pygame.display.update() clock.tick(FPS) pygame.quit() Print Page Previous Next Advertisements ”;

Pygame – Home

Pygame Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Audience This tutorial is designed for software programmers who want to develop video games using Python Programming language. Prerequisites Before proceeding with this tutorial, you need a basic knowledge on Python Programming language, and an understanding of the game that is to be developed is also essential. Print Page Previous Next Advertisements ”;

Pygame – Hello World

Pygame – Hello World ”; Previous Next First step is to import and initialize pygame modules with the help of init() function. import pygame pygame.init() We now set up Pygame display window of preferred size, and give it a caption. screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption(“Hello World”) This will render a game window which needs to be put in an infinite event loop. All event objects generated by user interactions such as mouse movement and click etc. are stored in an event queue. We shall terminate the event loop when pygame.QUIT is intercepted. This event is generated when user clicks the CLOSE button on the title bar. while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() Complete code for displaying Pygame window with Hello World caption is as follows − import pygame, sys pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption(“Hello World”) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() Save above script as hello.py and run to get following output − This window will be closed only if the close (X) button is clicked. Print Page Previous Next Advertisements ”;

Pygame – Loading image

Pygame – Loading Image ”; Previous Next The pygame.image module contains functions for loading and saving images from file or file like object. An image is loaded as a Surface object which eventually is rendered on Pygame display window. First we obtain a Surface object by load() function. img = pygame.image.load(”pygame.png”) Next we obtain a rect object out of this Surface and then use Surface.blit() function to render the image − rect = img.get_rect() rect.center = 200, 150 screen.blit(img, rect) Example The complete program for displaying Pygame logo on the display window is as follows − import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) img = pygame.image.load(”pygame.png”) done = False bg = (127,127,127) while not done: for event in pygame.event.get(): screen.fill(bg) rect = img.get_rect() rect.center = 200, 150 screen.blit(img, rect) if event.type == pygame.QUIT: done = True pygame.display.update() Output The output for the above code is as follows − The blit() function can take an optional special-flags parameter with one of the following values − BLEND_RGBA_ADD BLEND_RGBA_SUB BLEND_RGBA_MULT BLEND_RGBA_MIN BLEND_RGBA_MAX BLEND_RGB_ADD BLEND_RGB_SUB BLEND_RGB_MULT BLEND_RGB_MIN BLEND_RGB_MAX The pygame.Surface module also has a convert() function which optimizes the image format and makes drawing faster. The pygame.image module has a save() function that saves contents of Surface object to an image file. Pygame supports the following image formats − Loading image formats Saving image formats JPG PNG GIF (non-animated) BMP PCX TGA (uncompressed) TIF LBM (and PBM) PBM (and PGM, PPM) XPM BMP TGA PNG JPEG Example Following program draws three circles on the display surface and save it as a circles.png file using image.save() function. import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) done = False white=(255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) bg = (127,127,127) while not done: for event in pygame.event.get(): screen.fill(bg) if event.type == pygame.QUIT: done = True pygame.draw.circle(screen, red, (200,150), 60,2) pygame.draw.circle(screen, green, (200,150), 80,2) pygame.draw.circle(screen, blue, (200,150), 100,2) pygame.display.update() pygame.image.save(screen, “circles.png”) Output The circles.png should be created in the current working folder. Print Page Previous Next Advertisements ”;

Pygame – Useful Resources

Pygame – Useful Resources ”; Previous Next The following resources contain additional information on Pygame. Please use them to get more in-depth knowledge on this. Useful Links on Pygame Pygame @ Wikipedia − Pygame, its history and various other terms has been explained in simple language. Pygame − Pygame Official Website of Pygame Useful Books on Pygame To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;