1 / 44

PyGame Tutorial | PyGame Python Tutorial For Beginners | Python Certification Training | Edureka

** Python Certification Training: https://www.edureka.co/python ** <br>This Edureka PPT on PyGame Tutorial covers all the basic aspects of creating and running your own simple game. It establishes the concepts needed like images, sounds, geometry etc needed to build your own games using Python. Below is the agenda of this PPT: <br><br>What is PyGame? <br>Installing PyGame <br>Anatomy of PyGame <br>Working with Images <br>Working with Sounds <br>Working with Geometric Drawings <br>Working with Fonts and Text <br>Understanding Input Methods <br>Understanding Scene Logic <br><br>Follow us to never miss an update in the future. <br><br>Instagram: https://www.instagram.com/edureka_learning/ <br>Facebook: https://www.facebook.com/edurekaIN/ <br>Twitter: https://twitter.com/edurekain <br>LinkedIn: https://www.linkedin.com/company/edureka

EdurekaIN
Download Presentation

PyGame Tutorial | PyGame Python Tutorial For Beginners | Python Certification Training | Edureka

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Agenda Python Certification Training https://www.edureka.co/python

  2. Agenda 01 Introduction Why PyGame? 02 Getting Started Installing and working with PyGame 03 Concepts Coding concepts with PyGame 04 Practical Approach Use-Cases along the way to understand PyGame Python Certification Training https://www.edureka.co/python

  3. Making Your Own Game You decided to make your own game! Language? Deployment Platform? What sort of game? But how? Python Certification Training https://www.edureka.co/python

  4. Making Your Own Game Independency! I’m a happy gamer! Python Certification Training https://www.edureka.co/python

  5. What is PyGame? Python Certification Training https://www.edureka.co/python

  6. What Is PyGame? What is PyGame? It is a cross-platform set of Python modules designed for writing video games It includes computer graphics and sound libraries designed to be used with Python! PyGamecan handle time, video (both still images and vids), music, fonts, different image formats, cursors, mouse, keyboard, Joysticks and much muchmore. And all of that isverysimple. Python Certification Training https://www.edureka.co/python

  7. Installing PyGame Python Certification Training https://www.edureka.co/python

  8. Installing PyGame Installation is very easy! Python Certification Training https://www.edureka.co/python

  9. Prerequisites for learning PyGame Python Certification Training https://www.edureka.co/python

  10. Prerequisites Just the workflow in Python Python Certification Training https://www.edureka.co/python

  11. Anatomy of PyGame Python Certification Training https://www.edureka.co/python

  12. Anatomy Simple Python code! import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT : done = True pygame.display.flip() Programming in Python is fun! It's easier to understand and write PyGamecode Python Certification Training https://www.edureka.co/python

  13. Drawing An Object Simple Python code! # Add this somewhere after the event pumping and before the display.flip() pygame.draw.rect(screen, (0, 128, 255), pygame.Rect(30, 30, 60, 60)) Surface Instance to draw Tuple for colours (RGB) Instance –x, y , width, height Python Certification Training https://www.edureka.co/python

  14. Interactivity Simple Python code! Add before loop is_blue = True if is_blue: color = (0, 128, 255) else: color = (255, 100, 0) pygame.draw.rect(screen, color, pygame.Rect(30, 30, 60, 60)) Modify rectangle code to pick a colorconditionally if event.type == pygame.KEYDOWN and even t.key == pygame.K_SPACE: is_blue = not is_blue Add this to the for loop! Python Certification Training https://www.edureka.co/python

  15. Moving Objects Simple Python code! up_pressed = pygame.get_pressed()[pygame.K_UP] Let’s run the code and see where we stand at this point! Rectangle from previous frames remain on screen Moves EXTREMELY fast! Python Certification Training https://www.edureka.co/python

  16. Moving Objects Let’s fix the output! Reset screen to black before drawing rectangle screen.fill((0, 0, 0)) clock = pygame.time.Clock() ... while not done: ... # will block execution until 1/60 seconds have passed # since the previous time clock.tick was called. clock.tick(60) Fixing frame rate! Let’s run the code and see where we stand at this point! Python Certification Training https://www.edureka.co/python

  17. Working with Images! Python Certification Training https://www.edureka.co/python

  18. Images Very easy to add images! Instantiate a blank surface by calling the Surface constructor surface = pygame.Surface((100, 100)) What did we just do? Python Certification Training https://www.edureka.co/python

  19. Images Varying bitrate of image? 32-bit RGBA image surface = pygame.Surface((100, 100), pygame.SRCALPHA) What did we just do? This will create a 100 x 100 image that's initialized to transparent. Python Certification Training https://www.edureka.co/python

  20. Images Custom Image? Let’s load this PNG image How do we do that? We need the file to be loaded image = pygame.image.load('ball.png') Linux BALL.PNG same as ball.png NOT SAME Python Certification Training https://www.edureka.co/python

  21. Working with Sounds! Python Certification Training https://www.edureka.co/python

  22. Sounds Let’s start with the basics pygame.mixer.music.load('foo.mp3') pygame.mixer.music.play(0) Playing a song once Playing a song infinitely pygame.mixer.music.load('foo.mp3') pygame.mixer.music.play(-1) What does this do? pygame.mixer.music.play() Python Certification Training https://www.edureka.co/python

  23. Sounds More things to do with sounds! Queuing a song pygame.mixer.music.queue('next_song.mp3') Stopping a song pygame.mixer.music.stop() Python Certification Training https://www.edureka.co/python

  24. Sounds Simple code for sounds! ... USEREVENT + 1 ensures number assigned to SONG_END isn’t equal to any other event SONG_END = pygame.USEREVENT + 1 pygame.mixer.music.set_endevent(SONG_END) pygame.mixer.music.load('song.mp3') pygame.mixer.music.play() ... while True: ... for event in pygame.event.get(): ... if event.type == SONG_END: print("the song ended!") ... Python Certification Training https://www.edureka.co/python

  25. Sounds More operations with sound! Consider 5 songs _songs = ['song_1.mp3', 'song_2.mp3', 'song_3.mp3', 'song_4.mp3', 'song_5.mp3'] Add a flag _currently_playing_song = None import random def play_a_different_song(): global _currently_playing_song, _songs next_song = random.choice(_songs) while next_song == _currently_playing_ song: next_song = random.choice(_songs) _currently_playing_song = next_song pygame.mixer.music.load(next_song) pygame.mixer.music.play() Stopping a song Python Certification Training https://www.edureka.co/python

  26. Sounds More operations with sound! Consider 5 songs _songs = ['song_1.mp3', 'song_2.mp3', 'song_3.mp3', 'song_4.mp3', 'song_5.mp3'] def play_next_song(): global _songs _songs = _songs[1:] + [_songs[0]] # move current song to the back of list pygame.mixer.music.load(_songs[0]) pygame.mixer.music.play( Play in same sequence each time Python Certification Training https://www.edureka.co/python

  27. Sounds The music API is very centralized effect = pygame.mixer.Sound('beep.wav') effect.play() .play() method Sound library _sound_library = {} def play_sound(path): global _sound_library sound = _sound_library.get(path) if sound == None: canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep) sound = pygame.mixer.Sound(canonicalized_path) _sound_library[path] = sound sound.play() Python Certification Training https://www.edureka.co/python

  28. Geometric Drawing Python Certification Training https://www.edureka.co/python

  29. Geometric Drawing Drawing API is straightforward! Rectangle pygame.draw.rect(surface, color, pygame.Rect(left, top, width, height)) Circle pygame.draw.circle(surface, color, (x, y), radius) Python Certification Training https://www.edureka.co/python

  30. Geometric Drawing Drawing API is straightforward! Built-in Outlines # draw a rectangle pygame.draw.rect(surface, color, pygame.Rect(10, 10, 100, 100), 10) # draw a circle pygame.draw.circle(surface, color, (300, 60), 50, 10) Fix those gaps? Python Certification Training https://www.edureka.co/python

  31. Geometric Drawing Drawing API is straightforward! Acceptable Outlines Polygons Lines pygame.draw.polygon(surface, color, point_list) Python Certification Training https://www.edureka.co/python

  32. Geometric Drawing Drawing API is straightforward! Acceptable Outlines Polygons Lines pygame.draw.line(surface, color, (startX, startY), (endX, endY), width) Python Certification Training https://www.edureka.co/python

  33. Fonts & Text Python Certification Training https://www.edureka.co/python

  34. Fonts & Texts Quick answer to –How to render text? import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() done = False font = pygame.font.SysFont("comicsansms", 72) text = font.render("Hello, World", True, (0, 128, 0)) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: done = True screen.fill((255, 255, 255)) screen.blit(text, (320 - text.get_width() // 2, 240 - text.get_height() // 2)) pygame.display.flip() clock.tick(60) Python Certification Training https://www.edureka.co/python

  35. Fonts & Texts Here are certain useful tips! Enumerate default font of the system Enumerate fonts available on the system font = pygame.font.Font(None, size) all_fonts = pygame.font.get_fonts() Pass name of font file directly font = pygame.font.Font("myresources/fonts/Papyrus.ttf", 26) Python Certification Training https://www.edureka.co/python

  36. Fonts & Texts Let’s optimize the creation process! def make_font(fonts, size): available = pygame.font.get_fonts() # get_fonts() returns a list of lowercase spaceless font names choices = map(lambda x:x.lower().replace(' ', ''), fonts) for choice in choices: if choice in available: return pygame.font.SysFont(choice, size) return pygame.font.Font(None, size) _cached_text = {} def create_text(text, fonts, size, color): global _cached_text key = '|'.join(map(str, (fonts, size, color, text))) image = _cached_text.get(key, None) if image == None: font = get_font(fonts, size) image = font.render(text, True, color) _cached_text[key] = image return image _cached_fonts = {} def get_font(font_preferences, size): global _cached_fonts key = str(font_preferences) + '|' + str(size) font = _cached_fonts.get(key, None) if font == None: font = make_font(font_preferences, size) _cached_fonts[key] = font return font Python Certification Training https://www.edureka.co/python

  37. More on Input Python Certification Training https://www.edureka.co/python

  38. More on Input How do you get the state of any input device? Event Queue Polling Python Certification Training https://www.edureka.co/python

  39. More on Input How do you get the state of any input device? Event Queue Polling Event added to the queue must be emptied After each button press How can this be done? Pygame.event.get() Pygame.event.pump() Python Certification Training https://www.edureka.co/python

  40. More on Input How do you get the state of any input device? Event Queue Polling List of Booleans that describe state of each key Pygame.key.get_pressed() Returns the coordinates of mouse cursor Pygame.key.mouse.get_pos() Returns state of each mouse button Pygame.mouse.get_pressed() Python Certification Training https://www.edureka.co/python

  41. Centralized Scene Logic Python Certification Training https://www.edureka.co/python

  42. Scene Logic Class definition for a SceneBase: class SceneBase: def __init__(self): self.next = self def ProcessInput(self, events): print(“You didn't override this in the child class") def Update(self): print(“You didn't override this in the child class") def Render(self, screen): print(“You didn't override this in the child class") def SwitchToScene(self, next_scene): self.next = next_scene ProcessInput Receives all events happened since last frame Pygame.key.mouse.get_pos() Game logic for the scene goes here Render code goes here It receives main screen surface as input Pygame.mouse.get_pressed() Python Certification Training https://www.edureka.co/python

More Related