我有一个名为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
没有做任何好事。 有人知道如何解决这个问题吗? 任何帮助都将很乐意欣赏
答案 0 :(得分: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()