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

王林
发布: 2024-02-09 19:42:04
转载
449 人浏览过

在 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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!