【问题标题】:Pygame -> Moving a rect inside a class methodPygame -> 在类方法中移动矩形
【发布时间】:2016-06-15 04:31:30
【问题描述】:

我有一个名为 Block 的类,我用它来绘制和移动块:

class Block:
    def __init__(self, pos_x, pos_y, size_x, size_y):
        self._posX = pos_x
        self._posY = pos_y
        self._sizeX = size_x
        self._r = pygame.draw.rect(gameDisplay, (200,100,100), (pos_x,pos_y,size_x,size_y), 0)

    def bMove(self, new_x, new_y):
        self._r.left = new_x
        self._r.top = new_y

现在,绘图部分效果很好。问题是我无法使用带有 ie 的 bMove 类移动矩形。 'Box1.bMove(100, 100)'。 代码编译没有任何错误,但在游戏中矩形没有发生变化。 即使使用 'move(x,y)' 或将类修改为如下所示:

class Block:
    def __init__(self, pos_x, pos_y, size_x, size_y):
        self._posX = pos_x
        self._posY = pos_y
        self._sizeX = size_x
        pygame.draw.rect(gameDisplay, (200,100,100), (pos_x,pos_y,size_x,size_y), 0)

    def bMove(self, new_x, new_y):
        self.left = new_x
        self.top = new_y

没有做任何好事。 有谁知道如何解决这个问题? 任何帮助将不胜感激

【问题讨论】:

  • 您没有在bMove 方法中绘制矩形。 __init__ 仅在您创建类的实例时调用一次。
  • 那么正确的方法是在init之外绘制它?
  • 如果你在 init 里面绘制它,你不能移动它,所以是的。
  • 你能告诉我一个适当的代码修改作为答案吗?

标签: python class pygame


【解决方案1】:

__init__ 只被调用一次,当你创建一个类的实例时。

您正在尝试更新 Block 的位置并绘制它,因此您需要一个可以重复执行此操作的方法。

class Block:
    def __init__(self, pos_x, pos_y, size_x, size_y):
        self._posX = pos_x
        self._posY = pos_y
        self._sizeX = size_x
        self._sizeY = size_y
        self._r = pygame.Rect(pos_x,pos_y,size_x,size_y)

    def bMove(self, new_x, new_y):
        self._r.left = new_x
        self._r.top = new_y

        pygame.draw.rect(gameDisplay, (200,100,100), self._r)

这是一些测试代码:

import pygame

pygame.init()

size = [640, 480]
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Block')

clock = pygame.time.Clock()

class Block():
    def __init__(self, pos_x, pos_y, size_x, size_y):
        self._posX = pos_x
        self._posY = pos_y
        self._sizeX = size_x
        self._sizeY = size_y
        self._r = pygame.Rect(pos_x,pos_y,size_x,size_y)

    def bMove(self, new_x, new_y):
        self._r.left = new_x
        self._r.top = new_y

        pygame.draw.rect(screen, (200,100,100), self._r)

block = Block(0, 0, 50, 50)

done = False
while done == False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    screen.fill((255, 255, 255))

    x, y = pygame.mouse.get_pos()
    block.bMove(x, y)

    pygame.display.update()
    clock.tick(20)

pygame.quit()

【讨论】:

  • 每次我想移动它时会不会创建一个新的矩形实例?
  • 仅当您确实通过每次调用 Block() 创建实例时。
  • 谢谢百万:)
猜你喜欢
  • 2016-11-11
  • 2014-12-02
  • 2016-06-19
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多