How do you create rect variables in python pygame

匆匆过客 提交于 2019-12-24 03:37:48

问题


I am programming in Python with the pygame library. I want to know how to make a rectangle variable, something like:

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

回答1:


Just do

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

this will return you a Rect object in pygame




回答2:


Perhaps something like this will work?

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) )

If you want a red rectangle with 100x150 size in 0x50 position, it will be:

rect1 = pygame.draw.rect( (0, 50), (255, 0, 0), (100, 150) )

To insert it into the screen you use:

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



回答3:


For rectangle draw pattern is : pygame.Rect(left, top, width, height)

You can modify this code according to your need.

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()


来源:https://stackoverflow.com/questions/26831033/how-do-you-create-rect-variables-in-python-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!