Table of Contents
Pygame's Draw
Drawing a rectangle
Draw a polygon
Draw a circle
Drawing an ellipse
Drawing arc curve
Draw a straight line
Draw multiple straight lines
Home Backend Development Python Tutorial How to use Pygame's Draw drawing method in Python

How to use Pygame's Draw drawing method in Python

Apr 19, 2023 pm 04:46 PM
python pygame draw

Pygame's Draw

Pygame provides a draw module for drawing some simple graphics shapes, such as rectangles, polygons, circles, straight lines, arcs, etc.

The common methods of the pygame.draw module are shown in the following table:

Name Description
pygame.draw.rect() Draw a rectangle
pygame.draw.polygon () Draw a polygon
pygame.draw.circle() Draw a circle based on the center and radius Shape
pygame.draw.ellipse() Draw an ellipse
pygame.draw.arc() Draw an arc (waving part of the ellipse)
pygame.draw.line() Draw line segments (straight lines)
pygame.draw.lines() Draw multiple continuous line segments
pygame.draw.aaline() Draw a smooth line segment (anti-aliasing)
pygame.draw.aalines() Draw multiple continuous line segments

The methods of using the functions in the table are similar. They can all draw some simple shapes on the Surface object, and the return value is a Rect object, representing the rectangular area in which the graphics is actually drawn. The above drawing functions all provide a color parameter. We can pass the color parameter value in the following three ways:

  • pygame.color Object

  • RGB Triplets

  • RGBA Quadruples

The following is a detailed description of the parameters of some of the above methods:

Drawing a rectangle

The syntax format for drawing a rectangle is as follows:

pygame.draw.rect(surface, color, rect, width)
Copy after login

The parameter description is as follows:

  • surface: refers to the main game window. Unless there are special circumstances, it will generally be drawn on the main screen;

  • color: This parameter is used for coloring the graphic;

  • rect: The position and size of the drawn graphic;

  • width: Optional parameter, specifies the width of the border, the default is 0, which means filling the rectangular area.

Note that when width > 0, it indicates the width of the wireframe; when width < 0, no graphics will be drawn at this time.

Draw a polygon

pygame.draw.polygon(surface, color, points, width)
Copy after login

The parameters are described as follows

  • points: A list parameter that represents the vertices that make up the polygon 3 or more (x,y) coordinates, representing these polygon vertices through tuples or lists.

  • The remaining parameters are the same as the above function.

Draw a circle

pygame.circle(surface, color, pos, radius, width=0)
Copy after login

The parameter description is as follows

  • pos: This parameter is used to specify The center position of the circle;

  • radius: used to specify the radius of the circle;

  • The remaining parameters are the same as the above functions.

Drawing an ellipse

pygame.draw.ellipse(surface, color, Rect, width=0)
Copy after login

The process of drawing an ellipse is actually to draw an inscribed ellipse inside the rectangular area (Rect)

Parameters The description is as follows

  • The remaining parameters are the same as the above function.

Drawing arc curve

pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1)
Copy after login

The process of drawing an ellipse is actually to draw an inscribed ellipse inside the rectangular area (Rect)
The parameters are explained as follows

  • start_angle : is the starting angle of the arc;

  • stop_angle : is the termination angle;

  • The remaining parameters are the same as the above function.

Draw a straight line

pygame.draw.line(surface, color, start_pos, end_pos, width=1)
Copy after login

The parameter description is as follows

  • start_pos : is the starting position of the line segment ;

  • end_pos : is the end position of the line segment;;

  • The remaining parameters are the same as the above function.

If you are drawing a smooth line to eliminate aliasing, use the blend = 1 parameter at this time, as shown below:

pygame.aaline(surface, color, startpos, endpos, blend=1)
Copy after login

The blend parameter indicates that by drawing the blended background Shadows to implement anti-aliasing.

Draw multiple straight lines

The parameter description is as follows

  • pointlist : The parameter value is a list, including a series of point coordinates List of ;

  • closed : Boolean parameter, if set to True, it means that the first endpoint of the straight line and the last endpoint of the straight line should be connected end to end;;

  • The remaining parameters are the same as the above function.

If you draw an anti-aliased straight line, use the following method:

pygame.draw.aalines(surface, color, closed, pointlist, blend=1)
Copy after login

Except that blend = 1 is specified, the meaning of the remaining parameters is the same as the above function.

The above drawing method is demonstrated through a set of simple examples:

import pygame
from math import pi

# 初始化
pygame.init()
# 设置主屏幕大小
size = (500, 450)
screen = pygame.display.set_mode(size)
# 设置标题
pygame.display.set_caption("Python自学网")
# 设置一个控制主循环的变量
done = False
# 创建时钟对象
clock = pygame.time.Clock()
while not done:
    # 设置游戏的fps
    clock.tick(10)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True  # 若检测到关闭窗口,则将done置为True
    # 绘制一条宽度为 3 的红色对角线
    pygame.draw.line(screen, (0, 255, 0), [0, 0], (500, 450), 3)
    # 绘制多条蓝色的直线(连续直线,非抗锯齿),False 表示首尾不相连
    pygame.draw.lines(screen, (0, 0, 255), False, [[0, 80], [50, 90], [200, 80], [220, 30]], 1)
    # 绘制一个灰色的矩形区域,以灰色填充区域
    pygame.draw.rect(screen, (155, 155, 155), (75, 10, 50, 20), 0)
    # 绘制一个线框宽度为2的矩形区域
    pygame.draw.rect(screen, (0, 0, 0), [150, 10, 50, 20], 2)
    # 绘制一个椭圆形,其线宽为2
    pygame.draw.ellipse(screen, (255, 0, 0), (225, 10, 50, 20), 2)
    # 绘制一个实心的红色椭圆形
    pygame.draw.ellipse(screen, (255, 0, 0), (300, 10, 50, 20))
    # 绘制一个绿色边框(宽度为2)三角形
    pygame.draw.polygon(screen, (100, 200, 45), [[100, 100], [0, 200], [200, 200]], 2)
    # 绘制一个蓝色实心的圆形,其中[60,250]表示圆心的位置,40为半径,width默认为0
    pygame.draw.circle(screen, (0, 0, 255), [60, 250], 40)
    # 绘制一个圆弧,其中0表示弧线的开始位置,pi/2表示弧线的结束位置,2表示线宽
    pygame.draw.arc(screen, (255, 10, 0), (210, 75, 150, 125), 0, pi / 2, 2)
    # 刷新显示屏幕
    pygame.display.flip()
# 点击关闭,退出pygame程序
pygame.quit()
Copy after login

The above is the detailed content of How to use Pygame's Draw drawing method in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Can mysql workbench connect to mariadb Can mysql workbench connect to mariadb Apr 08, 2025 pm 02:33 PM

MySQL Workbench can connect to MariaDB, provided that the configuration is correct. First select "MariaDB" as the connector type. In the connection configuration, set HOST, PORT, USER, PASSWORD, and DATABASE correctly. When testing the connection, check that the MariaDB service is started, whether the username and password are correct, whether the port number is correct, whether the firewall allows connections, and whether the database exists. In advanced usage, use connection pooling technology to optimize performance. Common errors include insufficient permissions, network connection problems, etc. When debugging errors, carefully analyze error information and use debugging tools. Optimizing network configuration can improve performance

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to solve mysql cannot connect to local host How to solve mysql cannot connect to local host Apr 08, 2025 pm 02:24 PM

The MySQL connection may be due to the following reasons: MySQL service is not started, the firewall intercepts the connection, the port number is incorrect, the user name or password is incorrect, the listening address in my.cnf is improperly configured, etc. The troubleshooting steps include: 1. Check whether the MySQL service is running; 2. Adjust the firewall settings to allow MySQL to listen to port 3306; 3. Confirm that the port number is consistent with the actual port number; 4. Check whether the user name and password are correct; 5. Make sure the bind-address settings in my.cnf are correct.

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

See all articles