卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35000本站已运行393

在 Pygame 中使用自定义属性更新矩形时出现问题

在 pygame 中使用自定义属性更新矩形时出现问题

问题内容

我正在调试我的一个程序,我试图将自定义变量分配给矩形以更新其位置。

这是我的代码:

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
卓越飞翔博客
上一篇: 为什么当键入命令运行程序时,会在程序名前面自动插入./?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏