Step-2: Displaying players and their blocks
# load the image
playerImage = pygame.image.load("player.png")
# set the position
playerXPosition = (width/2) - (pixel/2)
# So that the player will be
# at a height of 20 above the base
playerYPosition = height - pixel - 10
# set initially 0
playerXPositionChange = 0
# define a function for setting
# the image at particular
# coordinates
def player(x, y):
# paste image on screen object
screen.blit(playerImage, (x, y))
# load the image
blockImage = pygame.image.load("rectangleBlock.png")
# set the random position
blockXPosition = random.randint(0,(width - pixel))
blockYPosition = 0 - pixel
# set the speed of
# the block
blockXPositionChange = 0
blockYPositionChange = 2
# define a function for setting
# the image at particular
# coordinates
def block(x, y):
# paste image on screen object
screen.blit(blockImage,(x, y))

You can also try this code with Online Python Compiler
Run Code
Step-3: Crash Function
The collision condition is defined by the crash function.
The horizontal collision is checked in the first IF condition. If the player's Y position is smaller than the block's Y position, indicating that the block has moved out of the player's horizontal range, the next condition to check is horizontal. Because its Y position is at the top of the block and the bottom or base of the block is a block's top position + its pixel size, pixel is added to blockYPosition (image size).
The vertical collision is checked in the second IF condition. If the block is travelling through the horizontal range, only check for vertical collisions so that all four sides of the block are detected. If the players' X position is larger than the block's X position, the block will be to the left of the player. If the block's starting position is less than the player's starting position and the block's end position (block Y position + pixel) is greater than the player's starting position, the block will overlap and collide with the player. This can be seen in the block 2 vertical collision image above.
If the blocks start position is less than the player's end position and the blocks end position is more than the player's end position, the second range is supplied. This is shown for block 3 of the same image.
As a result, if a collision occurs, we will shift the block below the screen, i.e. 1000+ pixels below, to make it invisible and prevent the new block from appearing.
# define a function for
# collision detection
def crash():
# take a global variable
global blockYPosition
# check conditions
if playerYPosition < (blockYPosition + pixel):
if ((playerXPosition > blockXPosition
and playerXPosition < (blockXPosition + pixel))
or ((playerXPosition + pixel) > blockXPosition
and (playerXPosition + pixel) < (blockXPosition + pixel))):
blockYPosition = height + 1000

You can also try this code with Online Python Compiler
Run Code
Step-4: Gaming loop
running = True
while running:
# set the image on screen object
screen.blit(backgroundImg, (0, 0))
# loop through all events
for event in pygame.event.get():
# check the quit condition
if event.type == pygame.QUIT:
# quit the game
pygame.quit()
# movement key control of player
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerXPositionChange = -3
if event.key == pygame.K_RIGHT:
playerXPositionChange = 3
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or pygame.K_RIGHT :
playerXPositionChange = 0

You can also try this code with Online Python Compiler
Run Code
Step-5: Setting up the boundaries
# Boundaries to the Player
# if it comes at right end,
# stay at right end and
# does not exceed
if playerXPosition >= (width - pixel):
playerXPosition = (width - pixel)
# if it comes at left end,
# stay at left end and
# does not exceed
if playerXPosition <= 0:
playerXPosition = 0

You can also try this code with Online Python Compiler
Run Code
Step-6:
When the block moves away from the player without colliding, we must allow him to return from the top. As a result, if the block's Y position is less than the screen's height and less than height+200 (as above 1000+, the block appears when the block has collided), we relocate it back to the top.
# Multiple Blocks Move after each other
# and this condition used because of game over function
if (blockYPosition >= height - 0 and
blockYPosition <= (height + 200)):
blockYPosition = 0 - pixel
# random assignment of the value in range
blockXPosition = random.randint(0, (width - pixel))

You can also try this code with Online Python Compiler
Run Code
Step-7:
Movement to players and blocks are given and screen is refreshed.
# movement of player
playerXPosition += playerXPositionChange
# movement of Block
blockYPosition += blockYPositionChange
# player Function Call
player(playerXPosition, playerYPosition)
# block Function Call
block(blockXPosition, blockYPosition)
# crash function call
crash()
# update screen
pygame.display.update()

You can also try this code with Online Python Compiler
Run Code
Frequently Asked Questions
What does Flip () do in pygame?
For software displays, use flip(). It just permits a section of the screen to be refreshed, rather than the complete screen. If no argument is given, the Surface area is updated in the same way as pygame. show does.
What does clock tick do in Python?
tick(): Only call this method once every frame. It will calculate the number of milliseconds since the previous call. If you pass the optional framerate argument, the function will delay the game so that it runs slower than the ticks per second specified.
What is Doublebuf?
As stated in the tag's description, double-buffering involves applying all of the draw routines to a separate block of memory and then copying that block (buffer) to video memory in one operation. If you don't do this, you'll end up with graphical artefacts.
What is pygame surface?
a game written in Python Any image can be represented by a surface. The Surface has a set pixel format and resolution. Color palettes are used to map 8-bit pixels to 24-bit colour on surfaces. To use pygame, type pygame on the command prompt. To build a new image object, use the Surface() pygame object for expressing images.
Conclusion
So, in a nutshell, We saw how we can detect collisions in pygame and make a game out of it.
Check out our Coding Ninjas Studio Guided Path to learn about Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and more, Take a look at the mock test series and participate in the contests hosted by Coding Ninjas Studio if you want to improve your coding skills. If you are new to preparation and want to work for firms such as Amazon, Microsoft, Uber, and others, you should review the problems, interview experiences, and interview bundle for placement preparations.
Consider taking one of our paid courses to give yourself and your profession an edge!
Please vote for our blogs if you find them valuable and exciting.
Happy Learning!!