[英]In this python pygame code, am I updating atrribute for the rectangle object .midbottom?
所以我正在学习 No Starch Presses 的 Python 速成课程 2e。 我终于完成了创建 Alien Invasion 游戏的部分。 在这两个特定的代码行之前,我正在理解所有内容。
有一个名为外星人入侵的 class 拥有一个屏幕矩形,该屏幕矩形将传递给 ai_game 中的这个 class。
\\
进口 pygame
class 船:"""A class 管理船"""
def __init__(self, ai_game):
"""Initialize the ship and set its starting position"""
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
#load the ship image and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
#Start each new ship at the bottom center of the screen
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
"""Draw the ship at its current location"""
self.screen.blit(self.image, self.rect)
\
我不理解的两行如下。 表面之下发生了什么? 我当然知道作者说他们在做什么,但我试图了解它是如何做到这一点的,而不仅仅是它在做什么,所以我可能会理解规则和逻辑,而不仅仅是接受表面价值的规则和逻辑。
\\
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
"""Draw the ship at its current location"""
self.screen.blit(self.image, self.rect)
\\
self.rect
表示 memory 中的 object 存储有关屏幕上矩形 object 的数据,对吗? 我的主要问题是.midbottom
之后的 self.rect rect object 的属性? 那么在第一个语句中是.midbottom
属性被设置为屏幕矩形的.midbottom
属性吗? 当我也在学习 python 时,它说要小心以这种方式设置彼此相等的值,因为在你看到它们相等之后改变一个也可能改变另一个。 继续前进,好吧,如果这是真的,船对象.midbottom
属性被设置为屏幕.midbottom
属性,当调用 blit() 方法时,blit() 如何知道 position 船的位置? 我从来没有告诉它把船停在哪里。 blitmethod 是否具有将船设置为唯一已知位置的默认行为? 我已经读到默认情况下,所有内容都位于(0,0),因此如果您向船舶 object 提供数据,它将自动将船舶放置在用户最后输入数据的位置。
一个Rect object 恰好有 4 个属性x
、 y
、 width
、 height
。 但是有很多虚拟属性。 如果您在后台设置虚拟属性,则会更改属性x
、 y
、 width
、 height
。 见pygame.Rect
:
Rect object 有几个虚拟属性可用于移动和对齐 Rect:
x,y top, left, bottom, right topleft, bottomleft, topright, bottomright midtop, midleft, midbottom, midright center, centerx, centery size, width, height w,h
所有这些属性都可以分配给:
rect1.right = 10 rect2.center = (20,30)
position 存储在rect
属性中。 参见blit
:
在此 Surface 上绘制源 Surface。 可以使用 dest 参数定位平局。 dest 参数可以是一对坐标,表示 blit 左上角的 position或 Rect,其中矩形的左上角将用作 blit 的 position 。
首先使用Surface的大小创建pygame.Rect
object :
self.rect = self.image.get_rect()
然后设置矩形的(中底)position。
self.rect.midbottom = self.screen_rect.midbottom
该指令更改x和y坐标,使矩形的中底点位于 window 的中底点。 该指令将完美对齐 window 底部中心的矩形。
最后,在存储在Rect中的 position 处绘制Surface :
self.screen.blit(self.image, self.rect)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.