如何在Python Pygame中创建矩形变量

3

我正在使用 pygame 库编写 Python 代码。我想知道如何创建一个矩形变量,类似于:

import ...
rect1 = #RECT VARIABLE
rect2 = #RECT VARIABLE

2
一个 PyGame 的矩形?rect1 == pygame.Rect(x, y, w, h)。请参考:http://www.pygame.org/docs/ref/rect.html - Marcus Møller
1
import pygamerect1 = pygame.Rect(left, top, width, height)等等-- 请仔细阅读文档。 - martineau
但是当你 blit 矩形时,你该怎么做呢? - David Wolters
3个回答

3

只需要执行

pygame.Rect(left, top, width, height)

这会在pygame中返回一个Rect对象。

1
也许像这样会有效果?
import pygame
# your whole code until you need a rectangle
rect1 = pygame.draw.rect( (x_coordinate, y_coordinate), (#a rgb color), (#size of rect in pixels) )

如果您想在 0x50 位置创建一个大小为 100x150 的红色矩形,将如下所示:
rect1 = pygame.draw.rect( (0, 50), (255, 0, 0), (100, 150) )

将其插入到屏幕中,您可以使用以下代码:

pygame.screen_you_have_created.blit(rect1, 0, 50)

-1

绘制矩形的模式为:pygame.Rect(left, top, width, height)

您可以根据需要修改此代码。

import pygame, sys
from pygame.locals import *
pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('Title')
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
basicFont = pygame.font.SysFont(None, 48)
message =  'Hello '

text = basicFont.render(message, False, WHITE, BLUE)
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
windowSurface.fill(WHITE)
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK
del pixArray
windowSurface.blit(text, textRect)
pygame.display.update()
while True:
    for event in pygame.event.get():
        if event.type == K_ESCAPE:
            pygame.quit()
            sys.exit()

2
你在第一行中解释了如何定义一个矩形,但是你的代码根本没有使用它,而是使用了get_rect方法。这很令人困惑。我认为原问题下面的两个评论更相关。 - elParaguayo
那么当你 blit 矩形时,你不提供坐标吗? - David Wolters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接