Pygame中rect 初探


1. 來自CSDN博客的解釋:

rect對象是用來存儲矩形對象的,rect對象有一些虛擬屬性,

比如top.left,bottom.right這些是用來固定矩形的位置的,

還有size,width,height,這些是描述矩形大小,寬高分別是多大,

center為矩形的中心點,其實就是關於橫縱坐標的二元組,因此又有centerx,centery兩個屬性。此外,還有x,y。

 

2.來自Pygame中文文檔的解釋:

class pygame.Rect

Rect是用於存儲矩形坐標的pygame對象。

 

“構造”方法:

1).rect = pygame.Rect( left , top, width, height )

2). rect = pygame.Rect(( left , top),( width, height) )

3).rect = pygame.Rect(object)

 

例子:

1).《外星人入侵》里的bullet類:

self.rect = pygame.Rect(0, 0, ai_settings.bullet_width,ai_settings.bullet_height)

 

2). 《外星人入侵》里的ship類:

self.image = pygame.image.load('images/ship.bmp')

 self.rect = self.image.get_rect()

 

3).比較特殊的是這個:

在screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))

pygame.display.set_caption("Alien Invasion")

中並沒

screen.get_rect( )便返回了screen的rect對象。

有出現關於screen的rect,接下來請看ship類的__init()__

 

screen.get_rect( )便返回了screen的rect對象。

 

 

3.關於rect里面的各個屬性。先進行測試:

主要測試代碼為test.py文件

 

 

(1)測試1及結果

 

 

(2)測試2及結果

 

 

 

 

 

可見,rect.x和rect.y是分別自動等於rect.left和rect.top的,並且centerx和centery也是自動根據left,top,width和height計算得到的。我僅僅通過pygame.Rect(600,20,30,20)這行(實際只指定left, top,width, height),它就自動計算了x,y,centerx,centery等。

(3)測試3及結果

 

 

 

(4)

 

 

真相:實際上x就是left,y就是top


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM