Setting up Screen for Pygame in Python

In this module, I’m going to discuss the creation of a blank screen in pygame using Python. pygame is an interesting subject for designing personalized user games it follows the same syntax as Python since pygame is a module that Python supports.

First, before creating the window in pygame we must import pygame package using the syntax as follows:

import pygame

In the above syntax, we imported the pygame package by importing this package we can use pygame functionalities.

After importing pygame we need to call a function which is defined as follows :

pygame.init()

Before calling any other pygame function you need to call this function.

                        Display window using set_mode()

wind=pygame.display.set_mode((width,height))

it takes tuple values as input that represents the width and height of window

wind is an object that refers to display.set_mode() function by using this object we can modify, design the window.

Example :

wind=pygame.display.set_mode((750,650))

it creates a window of width – 750 pixels and height – 650 pixels

The following code will display the window

import pygame
import sys
pygame.init()
wind=pygame.display.set_mode((750,650))
pygame.display.set_caption("Display Window")
while True:
         for eve in pygame.event.get():
              if eve.type==pygame.QUIT:
                   pygame.quit()
                   sys.exit()

Output:

https://drive.google.com/open?id=1uJ1MocHBIlroWElUvEwtOANvpz9NNDkW

  • we will get the output as a window of size 750-pixels width and 650 pixels height

pygame.display.set_caption()

Gives title for window prompt that we have generated.

while True:

it is considered as a game loop in Python which is always True .you can terminate the loop by using sys.exit().

The following are tasks performed by while Loop :

  • HANDLE EVENTS
  • UPDATE GAME STATE
  • DRAW GAME STATE TO SCREEN

Certain events are performed on the window we have created. To perform these events we use

for eve in pygame.event.get():

This method looks at which events have been created.

for loop will iterate over list of event objects given by pygame.event.get().

If the user pressed the keyboard or clicking mouse the first event in the list will be pressing the keyboard and clicking mouse will be the second event.

If no events have happened it will return a blank list.

if eve.type==pygame.QUIT:

In the above code, we used eve. type it will give information regarding the events that the object represents.

Here the event performed is QUIT  whose action is to close window panel when the close button is clicked and the functions that execute the quit is as follows:

pygame.quit()
sys.exit()

pygame.quit()  helps us to come out of the pygame library.

Also read:

Leave a Reply