Rect.move()不移动矩形

时间:2013-10-14 20:53:14

标签: python pygame

    '''
Created on 21. sep. 2013

Page 136 in ze almighty python book, 4.3

@author: Christian
'''

import sys,pygame,time

pygame.init()

numLevels = 15           # Number of levels    
unitSize = 25            # Height of one level 
white = (255,255,255)    # RGB Value of White
black = (0,0,0)          # RGB Value of Black
size = unitSize * (numLevels + 1)
xPos = size /2.0         # Constant position of X value 
screenSize = size,size   # Screen size to accomodate pygame 

screen = pygame.display.set_mode(screenSize)

for level in range(numLevels):
    yPos = (level + 1) * unitSize
    width = (level +1) * unitSize
    block = pygame.draw.rect(screen,white,(0,0,width,unitSize),0)
    block.move(xPos,yPos)
    pygame.time.wait(100)
    pygame.display.flip()

block.move(xPos,yPos)应该可以工作,但不是出于某种奇怪的原因。我不知道为什么。 我相当确定其他一切工作都很好,我已经搜索了几个小时的网站,然后来到这个网站寻求帮助。

2 个答案:

答案 0 :(得分:2)

从文档中看来,draw.rect在其构造函数中使用Rect,而不是元组:

block = pygame.draw.rect(screen, white, Rect(0, 0, width, unitSize), 0)

移动返回的Rect并不会再次神奇地绘制块。要再次绘制块,您需要再次绘制块:

block.move(xPos,yPos)
block = pygame.draw.rect(screen, white, block, 0)

当然,你现在屏幕上有两个街区,因为你画了两次。既然你想要移动块,为什么首先在旧位置绘制它?为什么不直接指定您想要的位置?

block = pygame.draw.rect(screen, white, Rect(xPos, yPos, width, unitSize), 0)

有关您正在尝试做的事情的更多信息,也许可以构建更好的答案。

答案 1 :(得分:1)

我不清楚你的代码试图完成什么(我没有认识到书的参考),所以这只是猜测。它首先构造一个Rect对象,然后在循环的每次迭代中绘制它之前逐步重新定位和重新调整(膨胀)它。

请注意使用move_ip()inflate_ip()来改变Rect对象“,这意味着他们修改了它的特性而不是返回一个新特性,但是没有绘制它(并且不返回任何东西)。与使用每次迭代创建新Rect相比,这使用的资源更少。

import sys, pygame, time

pygame.init()

numLevels = 15           # Number of levels
unitSize = 25            # Height of one level
white = (255, 255, 255)  # RGB Value of White
black = (0, 0, 0)        # RGB Value of Black
size = unitSize * (numLevels+1)
xPos = size / 2.0        # Constant position of X value
screenSize = size, size  # Screen size to accomodate pygame

screen = pygame.display.set_mode(screenSize)
block = pygame.Rect(0, 0, unitSize, unitSize)

for level in range(numLevels):
    block.move_ip(0, unitSize)
    block.inflate_ip(0, unitSize)
    pygame.draw.rect(screen, white, block, 0)
    pygame.time.wait(100)
    pygame.display.flip()