Python日記 5 Pygame簡單應用 1

2022-09-15 15:48:18 字數 2333 閱讀 5810

終於把枯燥的基礎知識過了一遍了,準備按照書本的引導,結合pygame的庫做乙個alien_invasion小遊戲。

雖然很早就接觸程式設計,但是卻始終談不上乙個真正的程式設計師,不管是在專業儲備還是髮量上。我感覺學習過程就是從「script kid」、到「coder」、再到「programmer」,最後可能才能成為「engineer」。而我還沒有成為「coder」,還有很多路要走。

今天彎路走的太多了,就簡單鋪陳一下**得了,累了,毀滅吧,趕緊的。

1. alien_invasion.py

1

import

sys2

import

pygame

3from settings import

settings

4from ship import

ship56

defrun_game():7#

初始化遊戲並建立乙個螢幕物件

8pygame.init()

9 ai_settings =settings()

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

11 pygame.display.set_caption("

alien invasion")

12#建立一艘飛船

13 ship =ship(screen)14#

開始遊戲的主迴圈

15while

true:16#

監視鍵盤和滑鼠事件(時間迴圈)

17for event in

pygame.event.get():

18if event.type ==pygame.quit:

19sys.exit()20#

每次迴圈時都重繪螢幕

21screen.fill(ai_settings.bg_color)

22ship.blitme()23#

讓最近繪製的螢幕可見(螢幕更新迴圈)

24pygame.display.flip()

25 run_game()

把一些關鍵**分到外部的檔案中,很方便乾淨。

2. setting.py

1

class

settings():

2"""

儲存alien invasion的所有設定的類

"""3

def__init__

(self):

4"""

初始化遊戲的設定

"""5

#螢幕設定

6 self.screen_width = 1200

7 self.screen_height = 800

8 self.bg_color = (230, 230, 230)

感覺pygame和我之前遠古時期用過的一款圖形庫的操作蠻像的,easyx,好像是這麼拼,人生第一款圖形庫。

3. ship.py

1

import

pygame

2class

ship:

3def

__init__

(self, screen):

4"""

初始化飛船並設定其初始值

"""5 self.screen =screen6#

載入飛船影象並獲取其外接矩形

7 self.image = pygame.image.load('

images/ship.bmp')

8 self.rect =self.image.get_rect()

9 self.screen_rect =screen.get_rect()10#

將每艘新飛船放在螢幕底部**

11 self.rect.centerx =self.screen_rect.centerx

12 self.rect.bottom =self.screen_rect.bottom

13def

blitme(self):

14"""

在指定位置繪製飛船

"""15 self.screen.blit(self.image, self.rect)

明天還會繼續,今日份完結,撒花✿✿ヽ(°▽°)ノ✿

python菜鳥日記5

1.在python中我們可以匯入模組,來呼叫模組裡面的函式,在乙個模組中,我們可以定義很多的函式和變數,但有些函式我們並不希望被別人使用,只希望在模組內部使用,那麼,我們可以通過 下劃線 字首來實現,比如 abc,qiuhe,但是python並沒有強制限制訪問函式或變數,只是一種程式設計的習慣而已 ...

python學習日記(5)

格式限定 可作為閉包使用 print format python 學習日記 print format python 學習日記 print format python 學習日記 print format language python dairy 學習日記 article python 學習日記 pr...

Python之pygame學習矩形區域(5)

在pygame中矩形區域這個模擬較特殊,在遊戲中,所有可見的元素都是以矩形區域來描述位置。可以從left,top,width和height值的組合建立rect。也可以從已經是rect或具有名為 rect 的屬性的python物件建立rect。任何需要rect引數的pygame函式也接受這些值中的任何...