how to make a game using pygame code example

Example 1: how to setup pygame

# To install pygame, type 'pip install pygame' in the 
# windows powershell or the os terminal

# To create a blank screen as a setup for a game, use:
import pygame
import sys

pygame.init()

clock = pygame.time.Clock()

FPS = 30 # How many times the screen will update per second

screen_width = 600 # How wide the window will be
screen_height = 600 # how high the window will be

screen = pygame.display.set_mode((screen_width, screen_height)) # creates the screen

while True:
    clock.tick(FPS) # updates the screen, the amount of times it does so depends on the FPS
    for event in pygame.event.get(): # Allows you to add various events
        if event.type == pygame.QUIT: # Allows the user to exit using the X button
            pygame.quit()
            sys.exit()

Example 2: simple game with python

# 1 - Import library
import pygame
from pygame.locals import *

# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))

# 3 - Load images
player = pygame.image.load("resources/images/dude.png")

# 4 - keep looping through
while 1:
    # 5 - clear the screen before drawing it again
    screen.fill(0)
    # 6 - draw the screen elements
    screen.blit(player, (100,100))
    # 7 - update the screen
    pygame.display.flip()
    # 8 - loop through the events
    for event in pygame.event.get():
        # check if the event is the X button 
        if event.type==pygame.QUIT:
            # if it is quit the game
            pygame.quit() 
            exit(0)

Example 3: how to make a game in pygame for beginners

import pygame
 
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
is_blue = True
x = 30
y = 30
 
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_SPACE:
                        is_blue = not is_blue
        
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_UP]: y -= 3
        if pressed[pygame.K_DOWN]: y += 3
        if pressed[pygame.K_LEFT]: x -= 3
        if pressed[pygame.K_RIGHT]: x += 3
        
        if is_blue: color = (0, 128, 255)
        else: color = (255, 100, 0)
        pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
        
        pygame.display.flip()