【问题标题】:How do you create rect variables in python pygame如何在 python pygame 中创建 rect 变量
【发布时间】:2015-01-06 00:04:36
【问题描述】:

我在 Python 中使用 pygame 库进行编程。我想知道如何制作一个矩形变量,例如:

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

【问题讨论】:

  • 一个 PyGame 矩形? rect1 == pygame.Rect(x, y, w, h)。看到这个:pygame.org/docs/ref/rect.html
  • import pygamerect1 = pygame.Rect(left, top, width, height) 等 -- RTFM。
  • 但是当你blit rect时你会怎么做?

标签: python python-2.7 variables pygame rect


【解决方案1】:

做吧

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

这将在 pygame 中返回一个 Rect 对象

【讨论】:

    【解决方案2】:

    也许这样的事情会起作用?

    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)
    

    【讨论】:

      【解决方案3】:

      对于矩形的绘制模式是: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()
      

      【讨论】:

      • 您已经在第一行中解释了如何定义 Rect,但您的代码根本没有使用它,而是使用了 get_rect 方法。这只是令人困惑。我认为原始问题下方的两个 cmets 更相关。
      • 所以当你对矩形进行 blit 时,你不提供坐标?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      相关资源
      最近更新 更多