如何使用 Pygame 在 Python 中繪製矩形?

Patricia Arquette
發布: 2024-10-26 06:15:30
原創
995 人瀏覽過

How to Draw a Rectangle in Python Using Pygame?

使用 Pygame 繪製矩形

在 Python 中,您可以使用 pygame.draw.rect 函數在 Pygame 顯示器上繪製矩形。

語法

pygame.draw.rect的語法如下:

pygame.draw.rect(surface, color, rect, width=0)
登入後複製

其中:

  • surface矩形。
  • color 是長方形的顏色。它可以是表示 RGB 值的三個整數的元組(例如,(255, 0, 0) 表示紅色)或 pygame.Color 物件。
  • rect 是表示尺寸和位置的 pygame.Rect 物件矩形。
  • width(可選)是矩形邊框的寬度。如果省略,則預設為 0,從而產生一個填滿的矩形。

範例

以下是如何在 Pygame 視窗中繪製藍色矩形的範例:

<code class="python">import pygame

# Initialize Pygame
pygame.init()

# Set up the display
DISPLAY = pygame.display.set_mode((500, 400), 0, 32)

# Create the colors
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)

# Fill the display with white
DISPLAY.fill(WHITE)

# Draw the rectangle
pygame.draw.rect(DISPLAY, BLUE, (200, 150, 100, 50))

# Update the display
pygame.display.update()

# Keep the window open until the user quits
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()</code>
登入後複製

此程式碼建立 500x400 像素的白色顯示。然後它繪製一個座標 (200, 150) 和尺寸 (100, 50) 的藍色矩形。

以上是如何使用 Pygame 在 Python 中繪製矩形?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!