我正在调试我的一个程序,其中我试图将一个自定义变量赋给一个矩形,以更新它的位置.

以下是我的代码:

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属性发生了变化,但屏幕上正方形的位置没有变化.

我错过了什么?

推荐答案

你必须重新绘制场景.更改后,您必须重新绘制矩形.清除显示并在应用程序循环中绘制矩形:

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

    display.fill("white");   
    pygame.draw.rect(display, 'steelBlue', square)     
    pygame.display.flip() # Update the screen

Python相关问答推荐

使用图片生成PDF Django rest框架

如何在PIL、Python中对图像应用彩色面膜?

acme错误-Veritas错误:模块收件箱没有属性linear_util'

时间序列分解

需要计算60,000个坐标之间的距离

有症状地 destruct 了Python中的regex?

在线条上绘制表面

Python,Fitting into a System of Equations

如何获取numpy数组的特定索引值?

将tdqm与cx.Oracle查询集成

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

在Django admin中自动完成相关字段筛选

多指标不同顺序串联大Pandas 模型

计算分布的标准差

如何在BeautifulSoup/CSS Select 器中处理regex?

当条件满足时停止ODE集成?

BeautifulSoup:超过24个字符(从a到z)的迭代失败:降低了首次深入了解数据集的复杂性:

使用Python TCP套接字发送整数并使用C#接收—接收正确数据时出错

如何根据一定条件生成段id

如何从数据框列中提取特定部分并将该值填充到其他列中?