Pygame Draw Circle Tutorial – Complete Guide

Have you ever watched a starlit night and wondered, “How would I recreate this starry night in Pygame?” or perhaps have you ever tried to design a game character with circular features and not known how to go about it? Well, we are here to navigate through the workings of drawing circles in Pygame, one of the easiest yet most powerful shapes used in game design. In this tutorial, not only will we explore the technical side of drawing circles in Pygame, but we’ll also dive into practical examples, bringing those circles to life.

What Is Pygame?

Pygame is a cross-platform set of Python modules that are crafted to make game creation a piece of cake. Using Pygame, developers can use Python to write video games, providing them freedom to create virtually any game that imagination sparks.

Why Learn to Draw Circles in Pygame?

The circle is a fundamental shape in not only game design but also in representing numerous aspects of reality in a simplified form. Be it representing a player in a basic Pong game, designing fancy game characters, or creating in-game items like coins or bubbles, the uses are limitless. Thus, learning to draw a circle in Pygame:

  • Enhances your ability to recreate reality in your games
  • Pushes the creative bounds of your game design
  • Enriches your understanding of Pygame and its usability

By the end of this tutorial, you will have a solid grasp on how to draw and manipulate circles in Pygame, catapulting your game design prowess to a whole new level. Whether you’re just starting your coding journey or you’re an experienced coder seeking to create unique designs in your games, hop on board and let’s start drawing!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Drawing a Basic Circle in Pygame

Our journey to mastering circles in Pygame starts with learning how to draw a simple circle. We’ll initiate by setting up Pygame and then draw a circle.

First, import the Pygame module and initialize it:

import pygame
pygame.init()

Next, let’s set the dimensions of our game window and start it:

screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("My first <a href="https://gamedevacademy.org/pygame-circle-tutorial-complete-guide/" title="Pygame Circle Tutorial – Complete Guide" target="_blank" rel="noopener">Pygame Circle"</a>)

Finally, we draw our first circle. Pygame provides a method called pygame.draw.circle() for that purpose. This method takes in the following parameters:

  • Surface: where the circle is to be drawn
  • Color: color of the circle in RGB format
  • Position: center point of the circle
  • Radius: from the center of the circle to its edges

Prepared with this knowledge, let’s try it out:

color = (255, 102, 0)
pygame.draw.circle(screen, color, (400,300), 75)
pygame.display.flip()

Changing Circle Attributes

The beauty of Pygame lies in its versatility, not just in drawing the circle but also in tweaking its attributes. Here’s how we can manipulate the color, position, and radius of our circle.

To randomly change the color each time you run the program:

import random

color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
pygame.draw.circle(screen, color, (400,300), 75)
pygame.display.flip()

To move the circle randomly across the screen:

position = (random.randint(0,800), random.randint(0,600))
pygame.draw.circle(screen, color, position, 75)
pygame.display.flip()

To randomize the radius of the circle:

radius = random.randint(50,100)
pygame.draw.circle(screen, color, position, radius)
pygame.display.flip()

You can even combine all these attributes to create a game of guessing the radius, color, or position of the circle each time you re-run the program. The more you experiment, the more fun you’ll have!

Creating Filled and Hollow Circles

To provide depth to our animations or to create objects like bubbles, sometimes we need hollow circles. Pygame equips us with the attribute to either fill or hollow out our circles.

For creating a hollow circle, you can use an optional attribute width. If width=0, then it’s a filled circle. If width=1 or is not provided, then it’s a hollow circle. Here’s how:

#Hollow Circle
pygame.draw.circle(screen, color, (400,300), 75,1)
#Filled Circle
pygame.draw.circle(screen, color, (400,300), 75,0)

Keep in mind that width should be less than or equal to the radius; otherwise, it might lead to unexpected results.

Create a Cluster of Circles

Drawing one circle is fun, but what about creating a beautiful constellation of circles? We can use loops to draw a cluster of circles. This code will draw 20 circles with random colors, random positions, and random radii:

for _ in range(20):

    color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
    position = (random.randint(0,800), random.randint(0,600))
    radius = random.randint(50,100)

    pygame.draw.circle(screen, color, position, radius)

pygame.display.flip()

Animating Circles

Static circles are cool, but animated circles bring the game to life! To animate the circle, we just need to change its position over time. This could be done using a variable that increments its value in each frame, which is then used for the circle’s position:

running = True
x = 400

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    x += 5
    if x > 800:  # if the circle goes off-screen
        x = 0  # bring it back from the left
 
    screen.fill((0, 0, 0))  # fill screen with black
    pygame.draw.circle(screen, color, (x, 300), 75)
    pygame.display.flip()

That’s it. By using the pygame.draw.circle() method and playing with the attributes, you have a world of creativity at your disposal. From clusters of stars in the sky to bouncing balls, the possibilities of using circles in Pygame are endless. Happy gaming!

Controlling Circle Movements

Building upon the animation concept, let’s now learn how to control our circle using keyboard inputs. This will enable the player to interact with the game, a crucial aspect of game development.

Pygame handles keyboard input through events. The Keydown event is triggered when a key is pressed:

y = 300
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                y -= 10
            elif event.key == pygame.K_DOWN:
                y += 10

    screen.fill((0, 0, 0))
    pygame.draw.circle(screen, color, (400, y), 75)
    pygame.display.flip()

In this example, when a player presses the “UP” or “DOWN” keys, the circle moves 10 units upward or downward respectively.

Interacting Circles

Our Pygame world gets more interesting when multiple circles interact with each other. Let’s create a scenario where a small circle (target) is moving around randomly and a larger circle (player) is controlled by the player. If the player catches the target, the target randomly jumps to a new position:

x_target = random.randint(100,700)
y_target = random.randint(100,500)
radius_target = random.randint(20,50)

x_player = 400
y_player = 300
radius_player = 75

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_player -= 10
            elif event.key == pygame.K_RIGHT:
                x_player += 10
            elif event.key == pygame.K_UP:
                y_player -= 10
            elif event.key == pygame.K_DOWN:
                y_player += 10

    if ((x_player - x_target)**2 + (y_player - y_target)**2)**0.5 <= radius_player:
        x_target = random.randint(100,700)
        y_target = random.randint(100,500)

    screen.fill((0, 0, 0))
    pygame.draw.circle(screen, color, (x_player, y_player), radius_player)
    pygame.draw.circle(screen, (255,0,0), (x_target, y_target), radius_target)

    pygame.display.flip()

We take the Euclidean distance between the player and the target, and if it’s less than or equal to the player’s radius, we know that the player caught the target. This way, we can facilitate interactions between multiple circles.

Animating Multiple Circles

Multiple circling bodies moving around on a screen can give impressive effects. It could be an asteroid shower or magical lanterns in the sky in the game world.

Let’s explore how we can animate multiple circles:

circle_data = [(random.randint(0,800), random.randint(0,600), random.randint(50,75)) for _ in range(10)]

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((0, 0, 0))
  
    for i in range(len(circle_data)):
        pygame.draw.circle(screen, color, circle_data[i][:2], circle_data[i][2])
        circle_data[i] = ((circle_data[i][0]+5)%800, circle_data[i][1],circle_data[i][2])

    pygame.display.flip()

In this example, 10 circles are created with random initial positions and radii. In each frame, the circles are redrawn offset by five X-coordinates, creating the effect of moving circles.

Putting It All Together

By now, we have learned a variety of actions that can be performed with circles in Pygame. If you’re embarking on creating a graphics-intensive game, mastering these techniques is fundamental. Whether it’s Pac-Man, Asteroids, Super Mario Bros., or your own unique creation, Pygame circles provide a solid foundation to design diverse graphics and animation interactions. Keep exploring and be creative with Pygame’s circles to bring your own games and imagination to life!

Where to Go Next?

Your journey of mastering circles in Pygame doesn’t need to stop here. As you move forward, there will be many more aspects to consider, such as rotating circles, complex interactions, or particle systems using circles. The road to mastery has no end, it’s the joy of walking on the pathway that matters.

If you wish to delve deeper into Python and its vast applications, consider checking out our Python Mini-Degree. It’s a comprehensive collection of courses that take you from a beginner to a confident Python programmer. Learn to code, create your own games and apps, and even get insights into more complex domains like machine learning, data science, and more! It’s a great way to learn Python at a deeper level and apply it pragmatically, while also having the flexibility to learn at your own pace.

If Python specific learning is what you seek, we offer a broader collection of Python courses that cater to various levels of competency. Continue on your Python journey across game development, AI, algorithms, and much more with Zenva – your one-stop solution to go from beginner to professional in the exciting world of coding.

Conclusion

Drawing and animating circles in Pygame opens up a universe of possibilities for your game developments. From intricate animations to exciting player interaction, mastering circles in Pygame pushes your creativity and technical skills to new horizons. We hope this tutorial propels you further into the world of Pygame and brings more fun and functionality to your python creations.

Remember, this is just the beginning of your journey. At Zenva, we are here to support and enhance your learning curve across Python, Pygame and beyond. With self-paced learning and deep-dive tutorials, you’re always one step closer to becoming the game developer you aspire to be. Keep exploring, keep innovating, and keep gaming!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.