直线移动()不移动

2024-06-07 15:34:37 发布

您现在位置:Python中文网/ 问答频道 /正文

    '''
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()

在阻止。移动(xPos,yPos)应该可以工作,但由于某些奇怪的原因,它没有起作用。我不知道为什么。 我很确定其他一切都很好,我已经在互联网上搜索了几个小时才来到这个网站寻求帮助。在


Tags: ofinsizetimevaluergblevelscreen
2条回答

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

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

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

^{pr2}$

当然现在你的屏幕上有两个方块,因为你已经画了两次了。既然无论如何都要移动块,为什么首先在旧位置绘制它?为什么不直接指定您希望它开始的位置?在

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

有了更多关于你想做什么的信息,也许可以构造出一个更好的答案。在

我不清楚你的代码要完成什么(我也不认识参考书),所以这只是一个猜测。它首先构造一个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()

相关问题 更多 >

    热门问题