How to Develop Your Own Game Using Python


By NIIT Editorial

Published on 15/06/2021

10 minutes

Python is the most flexible programming language. This makes it a favorable programming language for each and every field including Web-Improvement, Machine Learning, Artificial Intelligence, GUI Application, and Game Development. 

Python gives an in-built library called pygame, which is used to foster the game. When we comprehend the fundamental ideas of Python programming, we can utilize the pygame library to make games with alluring designs, appropriate animation, and impressive sound. To learn about game development using python you can check out NIIT game developer course.

Getting Started: Background and Setup

The “pygame” is a Python covering for the SDL library, representing the Simple Direct Media Layer. SDL gives cross-stage admittance to your framework's basic interactive media equipment parts, like sound, video, mouse, console, and joystick. Pygame came to life as a trade for the slowed-down PySDL project. The cross-stage nature of both SDL and pygame implies you can compose games and rich mixed media Python programs for each stage in the platform that upholds them.

To install the pygame in the platform you have, use the pip command:
 

Shell

$ pip install pygame


To verify if the pygame has been installed in your platform, load one of the samples that come with the library:

Shell

$ python3 -m pygame.examples.aliens

Concepts of PyGame

As pygame and the SDL library are convenient across various stages and gadgets, the two of them need to characterise and work with deliberations for different hardware realities. Understanding those ideas and deliberations will help you plan and foster your own games.

  • Modules and Initialization

The pygame library is composed out of various Python constructs, which incorporate a few distinct modules. These modules give abstract admittance to explicit hardware on your framework, just as uniform strategies to work with that hardware. For instance, display permits uniform admittance to your video display, while joystick permits unique control of your joystick.

After successfully importing the pygame library in the model above, the initial thing you did was introduce PyGame using pygame.init(). Now the function calls separate init() elements of all the included pygame modules. Since these modules are reflections for specific hardware, this initial step is required so you can work with similar code on Linux, Windows, and Mac.

  • Surfaces and Displays

In addition to the modules, pygame likewise incorporates a few Python classes, which embody non-hardware and dependent concepts. One of which is the Surface that, at its basic, characterizes a rectangular region on which you can draw. Surface articles are utilized in numerous settings in pygame. Later you'll perceive how to stack a picture into a Surface and show it on the screen. To understand it better you can try to take up some game making courses.

In pygame, everything is seen on a single user-created display, which can be a window or a whole screen. The display is made utilizing .set_mode(), which returns a Surface addressing the visible part of the window. It is this Surface that you pass into functions of drawing like pygame.draw.circle(), and the content of that Surface is pushed to the display when you call the pygame.display.flip().

  • Rects and Images

Your fundamental pygame program draws a shape directly onto the display's surface. However, you can also work with pictures on the disk. The image module permits you to load and save the images in an assortment of well-known configurations. The images are stacked into Surface objects, which can be manipulated and then displayed in various ways. 

As referenced above, Surface objects are addressed by rectangles, as are other different objects in pygame, like windows and images. Rectangles are so intensely utilized that there is an uncommon Rect class just to deal with them. You'll utilize Rect images and objects in your game to draw enemies and players and to oversee impacts between them.

Initializing and Importing PyGame

After you import pygame, you'll likewise have to introduce it. This permits pygame to associate its deliberations to your particular hardware: 
 

Python

1.  # Import the pygame module

 2.  import pygame

 3.

 4.  # Import pygame.locals for easier access to key coordinates

 5.  # Updated to conform to flake8 and black standards

 6.  from pygame.locals import (

 7.    K_UP,

 8.    K_DOWN,

 9.    K_LEFT,

10.    K_RIGHT,

11.    K_ESCAPE,

12.    KEYDOWN,

13.    QUIT,

14. )

15.

16.  # Initialize pygame

17.  pygame.init()


The pygame library characterizes numerous things other than modules and classes. It additionally characterizes some local constants for things like keystrokes, mouse movements, and show credits. You reference these constants utilizing the syntax pygame.<CONSTANT>. Importing particular constants from pygame.locals, you can use <CONSTANT> instead. This will save you a few keystrokes and improve the overall readability.

Display setting

You make the display screen to use by calling pygame.display.set_mode() and passing a list with the ideal width and height. 
 

Python

1.   # Import the pygame module

 2.   import pygame

 3

 4.  # Import pygame.locals for easier access to key coordinates

 5.  # Updated to conform to flake8 and black standards

 6.  from pygame.locals import (

 7.    K_UP,

 8.    K_DOWN,

 9.    K_LEFT,

10.    K_RIGHT,

11.    K_ESCAPE,

12.    KEYDOWN,

13.    QUIT,

14.  )

15.

16.  # Initialize pygame

17.  pygame.init()

18.

19.  # Define constants for the screen width and height

20.  SCREEN_WIDTH = 800

21.  SCREEN_HEIGHT = 600

22.

23.  # Create the screen object

24.  # The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT

25.  screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

For this situation, the window is 800x600, as characterized by the constants SCREEN_WIDTH and SCREEN_HEIGHT on lines 20 and 21. This returns a Surface that addresses within measurements of the window. This is the segment of the window you can handle, while the OS controls the window boundaries and title bar. NIIT game development courses, provide proper know-how on how to utilize display settings optimally. 

Events

Key presses, mouse movements, and even movements of the joystick are a portion of the manners by which a client can give input. All client input brings about an occasion being produced. You can access the rundown of all active events in the queue by calling pygame.event.get().
 

Python

26.

27.  # Variable to keep the main loop running

28.   running = True

29.

30.   # Main loop

31.   while running:

32.   # Look at every event in the queue

33.    for event in pygame.event.get():

34.        # Did the user hit a key?

35.        if event.type == KEYDOWN:

36.            # Was it the Escape key? If so, stop the loop.

37.            if event.key == K_ESCAPE:

38.               running = False

39.

40.        # Did the user click the window close button? If so, stop the loop.

41.        elif event.type == QUIT:

42.            running = False

 

Use of .blit() / .flip() and Drawing on the Screen

The term blit represents Block Transfer, and .blit() is how you copy the content of one Surface to another.

Python

43.

44.  # Fill the screen with white

45.  screen.fill((255, 255, 255))

46.

47.  # Create a surface and pass in a tuple containing its length and width

48.  surf = pygame.Surface((50, 50))

49.

50.  # Give the surface a color to separate it from the background

51.  surf.fill((0, 0, 0))

52.  rect = surf.get_rect()

 

Python

53.

54.  # Put the center of surf at the center of the display

55.  surf_center = (

56.      (SCREEN_WIDTH-surf.get_width())/2,

57.      (SCREEN_HEIGHT-surf.get_height())/2

58.  )

59.

60.  # Draw surf at the new coordinates

61.  screen.blit(surf, surf_center)

62.  pygame.display.flip()

 

The call to pygame.display.flip() after the call to blit() updates the whole screen with all that has been drawn since the last flip. Without the call to .flip(), nothing is shown.

Sprites

In terms of programming, Sprite is a 2D portrayal of something on the screen. Basically, it's an image. Pygame gives a Sprite class, which is intended to hold one or a few graphical portrayals of any game item that you need to show on the screen.

  • Players

Use the Sprite object in the game to define the player.

(Insert the code after line 18)

Python

1.  # Import the pygame module

 2.  import pygame

 3.

 4.  # Import pygame.locals for easier access to key coordinates

 5.  # Updated to conform to flake8 and black standards

 6.  from pygame.locals import (

 7.      K_UP,

 8.      K_DOWN,

 9.      K_LEFT,

10.     K_RIGHT,

11.     K_ESCAPE,

12.     KEYDOWN,

13.     QUIT,

14.  )

15.

16.  # Define constants for the screen width and height

17.  SCREEN_WIDTH = 800

18.  SCREEN_HEIGHT = 600

19.

20.  # Define a player object by extending pygame.sprite.Sprite

21.  # The surface drawn on the screen is now an attribute of 'player'

22.  class Player(pygame.sprite.Sprite):

23.      def __init__(self):

24.          super(Player, self).__init__()

25.          self.surf = pygame.Surface((75, 25))

26.          self.surf.fill((255, 255, 255))

27.          self.rect = self.surf.get_rect()

28.

29.  # Initialize pygame

30.  pygame.init()

31.

32.  # Create the screen object

33.  # The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT

34.  screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

35.

36.  # Instantiate player. Right now, this is just a rectangle.

37.  player = Player()

38.

39.  # Variable to keep the main loop running

40.  running = True

41.

42.  # Main loop

43.  while running:

44.      # for loop through the event queue

45.      for event in pygame.event.get():

46.          # Check for KEYDOWN event

47.          if event.type == KEYDOWN:

48.              # If the Esc key is pressed, then exit the main loop

49.              if event.key == K_ESCAPE:

50.                  running = False

51.          # Check for QUIT event. If QUIT, then set running to false.

52.          elif event.type == QUIT:

53.              running = False

54.

55.      # Fill the screen with black

56.      screen.fill((0, 0, 0))

57.

58.      # Draw the player on the screen

59.      screen.blit(player.surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))

60.

61.      # Update the display

62.      pygame.display.flip()

  • User Input

Pygame additionally gives pygame.event.get_pressed(), which returns a  reference containing all the current KEYDOWN events in the queue.
 

Python

25.  # Move the sprite based on user keypresses

26.  def update(self, pressed_keys):

27.     if pressed_keys[K_UP]:

28.         self.rect.move_ip(0, -5)

29.     if pressed_keys[K_DOWN]:

30.        self.rect.move_ip(0, 5)

31.     if pressed_keys[K_LEFT]:

32.         self.rect.move_ip(-5, 0)

33.     if pressed_keys[K_RIGHT]:

34.         self.rect.move_ip(5, 0)

35.

36.     # Keep player on the screen

37.     if self.rect.left < 0:

38.         self.rect.left = 0

39.     if self.rect.right > SCREEN_WIDTH:

40.         self.rect.right = SCREEN_WIDTH

41.     if self.rect.top <= 0:

42.         self.rect.top = 0

43.     if self.rect.bottom >= SCREEN_HEIGHT:

44.         self.rect.bottom = SCREEN_HEIGHT

 

Now call .update() each casing to move the player sprite in response to the keypresses. Add this call just after the call to .get_pressed() :

 

Python

52.  # Main loop

53.  while running:

54.      # for loop through the event queue

55.      for event in pygame.event.get():

56.          # Check for KEYDOWN event

57.          if event.type == KEYDOWN:

58.              # If the Esc key is pressed, then exit the main loop

59.              if event.key == K_ESCAPE:

60.                  running = False

61.          # Check for QUIT event. If QUIT, then set running to false.

62.          elif event.type == QUIT:

63.              running = False

64.

65.      # Get all the keys currently pressed

66.      pressed_keys = pygame.key.get_pressed()

67.

68.      # Update the player sprite based on user keypresses

69.      player.update(pressed_keys)

70.

71.      # Fill the screen with black

72.      screen.fill((0, 0, 0))

  • Enemies

Use the previously used techniques to create a basic enemy class. Before that, import a random library:

Python

4.  # Import random for random numbers

 5.  import random

Now following the pattern of the Player create a new sprite class called  Enemy:
 

Python

55  .# Define the enemy object by extending pygame.sprite.Sprite

56.  # The surface you draw on the screen is now an attribute of 'enemy'

57.  class Enemy(pygame.sprite.Sprite):

58.      def __init__(self):

59.          super(Enemy, self).__init__()

60.          self.surf = pygame.Surface((20, 10))

61.          self.surf.fill((255, 255, 255))

62.          self.rect = self.surf.get_rect(

63.              center=(

64.                  random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),

65.                  random.randint(0, SCREEN_HEIGHT),

66.              )

67.          )

68.          self.speed = random.randint(5, 20)

69.

70.      # Move the sprite based on speed

71.      # Remove the sprite when it passes the left edge of the screen

72.      def update(self):

73.          self.rect.move_ip(-self.speed, 0)

74.          if self.rect.right < 0:

75.              self.kill()

Sprite Groups and Custom Events

Another very helpful class that pygame gives is the Sprite Group. This is an object that holds a gathering of Sprite objects.
 

Python

82.  # Create the 'player'

83.  player = Player()

84.

85.  # Create groups to hold enemy sprites and all sprites

86.  # - enemies is used for collision detection and position updates

87.  # - all_sprites is used for rendering

88.  enemies = pygame.sprite.Group()

89.  all_sprites = pygame.sprite.Group()

90.  all_sprites.add(player)

91.

92.  # Variable to keep the main loop running

93.  running = True

 

Since you have an all_sprites group, you can change how articles are drawn. Rather than calling .blit() on Player, you can repeat over everything in all_sprites :

 

Python

117.  # Fill the screen with black

118.  screen.fill((0, 0, 0))

119.

120.  # Draw all sprites

121.  for entity in all_sprites:

122.      screen.blit(entity.surf, entity.rect)

123.

124.  # Flip everything to the display

125.  pygame.display.flip()

 

The plan calls for enemies to show up at regular intervals. This implies that at set intervals, you need to complete two things: 

  1. Make a new Enemy.
  2. Add it to all_sprites and enemies.

Python

78.  # Create the screen object

79.  # The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT

80.  screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

81.

82.  # Create a custom event for adding a new enemy

83.  ADDENEMY = pygame.USEREVENT + 1

84.  pygame.time.set_timer(ADDENEMY, 250)

85.

86.  # Instantiate player. Right now, this is just a rectangle.

87.  player = Player()

Insert the new event into the queue at regular intervals throughout the game:

Python

100.  # Main loop

101.  while running:

102.      # Look at every event in the queue

103.      for event in pygame.event.get():

104.          # Did the user hit a key?

105.          if event.type == KEYDOWN:

106.              # Was it the Escape key? If so, stop the loop.

107.              if event.key == K_ESCAPE:

108.                  running = False

109.

110.          # Did the user click the window close button? If so, stop the loop.

111.          elif event.type == QUIT:

112.              running = False

113.

114.          # Add a new enemy?

115.          elif event.type == ADDENEMY:

116.              # Create the new enemy and add it to sprite groups

117.              new_enemy = Enemy()

118.              enemies.add(new_enemy)

119.              all_sprites.add(new_enemy)

120.

121.      # Get the set of keys pressed and check for user input

122.      pressed_keys = pygame.key.get_pressed()

123.      player.update(pressed_keys)

124.

125.      # Update enemy position

126.      enemies.update()

 

Collision Detection

For collision detection, use the method called .spritecollideany(), which accepts a Sprite and a Group as parameters.
 

Python

132.  # Draw all sprites

131.  for entity in all_sprites:

132.      screen.blit(entity.surf, entity.rect)

133.

134.  # Check if any enemies have collided with the player

135.  if pygame.sprite.spritecollideany(player, enemies):

136.      # If so, then remove the player and stop the loop

137.      player.kill()

138.      running = False

Game Speed

The module time contains a Clock. Utilizing Clock to build up a playable frame rate requires only two lines of code. The first make another Clock before the game loop starts:

Python

106.  # Setup the clock for a decent framerate

107.  clock = pygame.time.Clock()

The subsequent calls .tick() to illuminate pygame that the program has arrived at the end of the frame:

Python

188.  # Flip everything to the display

189.  pygame.display.flip()

190.

191.  # Ensure program maintains a rate of 30 frames per second

192.  clock.tick(30)

  )

Sound Effects

Pygame gives a mixer to deal with all sound-related activities. You'll utilize this module's classes and strategies to give background sound and audio cues for different actions. 

Python

106.   # Setup for sounds. Defaults are good.

107.  pygame.mixer.init()

108. 

109.  # Initialize pygame

110.  pygame.init()

111.

112.  # Set up the clock for a decent framerate

113.  clock = pygame.time.Clock()

pygame.mixer.init() acknowledges various contentions; however, the defaults work fine in some cases. Note that if you need to change the defaults, you need to call pygame.mixer.init() prior to calling pygame.init(). Otherwise, the defaults are going to be in effect regardless of your changes.

After the initialization of the system, you can get your sounds arrangement:

Python

135.   # Load and play background music

136.  # Sound source: http://ccmixter.org/files/Apoxode/59262

137.  # License: https://creativecommons.org/licenses/by/3.0/

138.  pygame.mixer.music.load("Electric_1.mp3")

139.  pygame.mixer.music.play(loops=-1)

140.

141.  # Load all sound files

142.  # Sound sources: Jon Fincher

143.  move_up_sound = pygame.mixer.Sound("Rising_p.ogg")

144.  move_down_sound = pygame.mixer.Sound("Falling_p.ogg")

145.  collision_sound = pygame.mixer.Sound("Collision.ogg")

Now you have to add a call .play() to add sound to the player’s movements:

Python

26.   # Define the Player object by extending pygame.sprite.Sprite

27.  # Instead of a surface, use an image for a better-looking sprite

28.  class Player(pygame.sprite.Sprite):

29.      def __init__(self):

30.          super(Player, self).__init__()

31.          self.surf = pygame.image.load("jet.png").convert()

32.          self.surf.set_colorkey((255, 255, 255), RLEACCEL)

33.          self.rect = self.surf.get_rect()

34.

35.      # Move the sprite based on keypresses

36.      def update(self, pressed_keys):

37.          if pressed_keys[K_UP]:

38.              self.rect.move_ip(0, -5)

39.              move_up_sound.play()

40.          if pressed_keys[K_DOWN]:

41.              self.rect.move_ip(0, 5)

42.              move_down_sound.play()


Now you play the sound when collisions are detected between the player and an enemy:
 

Python

201.  # Check if any enemies have collided with the player

202.  if pygame.sprite.spritecollideany(player, enemies):

203.      # If so, then remove the player

204.      player.kill()

205.

206.      # Stop any moving sounds and play the collision sound

207.      move_up_sound.stop()

208.      move_down_sound.stop()

209.      collision_sound.play()

210.

211.      # Stop the loop

212.      running = False

 

When the game is finished, all sounds should stop because of a crash or the client exits manually. To do this, add the accompanying lines toward the finish of the program after the loop:

 

Python

220.  # All done! Stop and quit the mixer.

221.  pygame.mixer.music.stop()

222.  pygame.mixer.quit()

 

Conclusion

Throughout this article, you have learnt how the game programming with pygame differs

from the basic procedural game programming. 

Apart from this, you have also learnt how to:

● Implement different event loops

● Draw the items on the screen

● Adding sound effects and music

● To handle user input

And to do this, you’ve used a subset of the pygame modules, incorporating the display,

mixer and music, time, image, event, as well as key modules. You have also used various

pygame classes, including Rect, Sprite, Sound, and Surface. Game programming courses can help you excel at game development and allow you to develop your own games.



Game Development Course

Becoming a Game Developer: A Course for Programmers. Design and Build Your Own Game using Unity.

Job Placement Assistance

Course duration: 20 weeks

Top