Python - 在 PyGame 視窗中繪製不同的形狀


Pygame 是一個適用於 Python 的多媒體庫,用於製作遊戲和多媒體應用程式。在本文中,我們將看到如何使用 pygame 模組在螢幕上繪製許多不同的形狀,同時考慮其高度、寬度和在 pygame 視窗中的位置。

在下面的程式中,我們初始化 pygame 模組,然後定義圖片的顏色和尺寸。接下來,我們根據語法新增不同的形狀,並仔細提及繪圖函式的引數,以便影像不會相互重疊。screen.blit 函式繪製螢幕,而 while 迴圈持續監聽遊戲結束時的點選事件。

示例

import pygame
pygame.init()
# define the RGB value
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 150)
black = (0, 0, 0)
red = (255, 0, 0)
# assigning values to X and Y variable
X = 400
Y = 400
# create display surface
display_surface = pygame.display.set_mode((X, Y))
# set the pygame window name
pygame.display.set_caption('Drawing')
# fill the surface object
display_surface.fill(white)
# draw a circle using draw.circle()
pygame.draw.circle(display_surface,
                  black, (300, 250), 80, 0)
# draw a ellipse using draw.ellipse()
pygame.draw.ellipse(display_surface, red,
                  (50, 200, 100, 150), 4)
# draw a rectangle using draw.rect()
pygame.draw.rect(display_surface, blue,
                  (50, 50, 150, 100))
# infinite loop
while True:
   # iterate over the list of Event
   for event in pygame.event.get():
      # if event object type is QUIT
      if event.type == pygame.QUIT:
         # deactivates the pygame library
         pygame.quit()
         # quit the program.
         quit()
      pygame.display.update()

輸出

執行上述程式碼會得到以下結果 −

更新時間:2021 年 1 月 25 日

302 次瀏覽

開啟你的 事業

完成課程可獲得認證

立即開始
廣告