Pygame เป็นไลบรารีมัลติมีเดียสำหรับ Python ใช้สร้างเกมและแอปพลิเคชันมัลติมีเดีย ในบทความนี้ เราจะดูวิธีใช้โมดูล pygame เพื่อวาดรูปทรงหลายรูปบนหน้าจอ โดยคำนึงถึงความสูง ความกว้าง และตำแหน่งในหน้าต่าง pygame
ในโปรแกรมด้านล่าง เราเริ่มต้นโมดูล pygame แล้วกำหนดสีและมิติของรูปภาพ ต่อไปเราเพิ่มรูปทรงต่างๆ ตามไวยากรณ์ และระบุ Argument ให้ฟังก์ชันวาดอย่างระมัดระวัง เพื่อไม่ให้รูปทับซ้อนกัน ฟังก์ชัน screen.blit จะวาดหน้าจอ ในขณะที่ While Loop จะคอยฟังการคลิกจบเกม
ตัวอย่าง
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()
ผลลัพธ์
การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ −
