我正在调试我的一个程序,其中我试图将一个自定义变量赋给一个矩形,以更新它的位置.
以下是我的代码:
import os ; os.environ['PYGAME_HIDE_SUPPORT_PROMPT']='False'
import pygame, random
pygame.init()
display = pygame.display.set_mode((401, 401))
display.fill("white") ; pygame.display.flip()
class MyRect(pygame.Rect):
def __setattr__(self, attr, value): # Sets a custom attribute to a rectangle
super().__setattr__(attr, value)
if attr == 'xValue':
pygame.Rect.move(self, (value-self.centerx), 0) # Move the rectangle according to the xValue
def contains(self, coords):
return self.collidepoint(coords)
square = MyRect(175, 175, 50, 50)
pygame.draw.rect(display, 'steelBlue', square) # Draw the rectangle to the screen
square.xValue = 200
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() ; exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if square.contains(pygame.mouse.get_pos()):
square.xValue = random.randint(0, display.get_width()) # Update the square.xValue property
pygame.display.flip() # Update the screen
当我执行程序时,square.xValue属性发生了变化,但屏幕上正方形的位置没有变化.
我错过了什么?