简体   繁体   中英

How to slowly draw a circle in Pygame?

I want to slowly draw a circle in pygame so the act of drawing is actually visible to the naked eye. I got a function on stackoverflow to draw a straight line by incrementing the end point and keeping the starting point same but couldn't figure out how to slowly draw a circle in the pygame screen.

You can use the standard sine and cose circle formula:

  • x = r * cos(radians(i)) + a
  • y = r * sin(radians(i)) + b

Where a is the x coordinate of the center of the circle, and b is the y coordinate of the center of the circle r is the radius of the circle.

To slow down the animation, use a Clock object. You can access the functions sin and cos from the built-in math module (note that you'll need to pass in the values as radians, hence the importation of the radians function) .

The implementation:

import pygame
from math import sin, cos, radians

pygame.init()
wn = pygame.display.set_mode((600, 600))

r = 100
a = 300
b = 200

clock = pygame.time.Clock()
for i in range(1, 361):
    clock.tick(30)
    pygame.draw.circle(wn, (255, 255, 255), (int(r * cos(radians(i)) + a), int(r * sin(radians(i)) + b)), 2)
    pygame.display.update()

Output:

在此处输入图像描述

If you prefer to use standard lines as the outline instead of overlapping dots, use the pygame.draw.line function like so:

import pygame
from math import sin, cos, radians

pygame.init()
wn = pygame.display.set_mode((600, 600))

r = 100
a = 300
b = 200

def x_y(r, i, a, b):
    return (int(r * cos(radians(i)) + a), int(r * sin(radians(i)) + b))

clock = pygame.time.Clock()
for i in range(0, 360, 2):
    clock.tick(30)
    pygame.draw.line(wn, (255, 255, 255), x_y(r, i, a, b), x_y(r, i+1, a, b), 2)
    pygame.display.update()

I recommend using the turtle library because it contains a circle function. For example circle(40) would draw a circle with a radius of 40 units. When you run the program the circle will be drawn in front of you

Your question states your main aim is to just draw a circle, so I would suggest you to consider using turtle.

You can run these codes and get the output:

import turtle
  
t = turtle.Turtle()
t.circle(50)
import pygame
pygame.init()
screen = pygame.display.set_mode((626, 416))

pygame.draw.circle(screen, (r,g,b), (x, y), R, w)
running = True
while running:
    pygame.display.update()
    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

This is how you can draw a circle on a pygame screen with (r, g, b) as color, (x, y) as center, R as radius and w as the thickness of the circle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM