,可以通过以下步骤实现:
import pygame
import sys
pygame.init()
screen_width = 800
screen_height = 600
bg_color = (255, 255, 255) # 白色背景
screen = pygame.display.set_mode((screen_width, screen_height))
screen.fill(bg_color)
rect_width = 100
rect_height = 50
rect_color = (255, 0, 0) # 红色矩形
rect = pygame.Rect((screen_width - rect_width) // 2, (screen_height - rect_height) // 2, rect_width, rect_height)
pygame.draw.rect(screen, rect_color, rect)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
完整代码示例:
import pygame
import sys
pygame.init()
screen_width = 800
screen_height = 600
bg_color = (255, 255, 255) # 白色背景
screen = pygame.display.set_mode((screen_width, screen_height))
screen.fill(bg_color)
rect_width = 100
rect_height = 50
rect_color = (255, 0, 0) # 红色矩形
rect = pygame.Rect((screen_width - rect_width) // 2, (screen_height - rect_height) // 2, rect_width, rect_height)
pygame.draw.rect(screen, rect_color, rect)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
这段代码使用pygame库创建了一个窗口,并在窗口中绘制了一个红色矩形。通过设置游戏主循环,保证窗口一直显示,直到用户关闭窗口。
领取专属 10元无门槛券
手把手带您无忧上云