首页  >  文章  >  后端开发  >  在 Pygame 中使用自定义属性更新矩形时出现问题

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

王林
王林转载
2024-02-09 19:42:04431浏览

在 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

以上是在 Pygame 中使用自定义属性更新矩形时出现问题的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除