第12章:外星人入侵遊戲(一)

1. 安裝Pygame包
下載地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame
安裝:把下載好的複製到項目文件夾下 —— 運行 —— cmd —— 切換到存放pygame目錄下 —— 執行pip安裝
pip install pygame-1.9.6-cp37-cp37m-win_amd64.whl
拓展:
切換到其他盤的dos命令:直接輸入"盤符:"
進入文件夾:cd
回到上一層:cd..
回到根目錄:cd/

2. 創建遊戲窗口

3.

4.加載飛船圖片
pygame.image.load(相對路徑/絕對路徑)
    例如:pygame.image.load('images/ship.bmp')
注意:加載好的圖片顯示了滿屏,需要對尺寸不符合要求的圖片進行處理
pygame.transform.scale(image,(寬,高))
    例如:self.image = pygame.transform.scale(pygame.image.load('images/ship.bmp'),(80,70))

5.阻止飛船在移動時,移到了屏幕外
屏幕的座標如下圖所示:
比如:screen_rect = pygame.Rect(0, 0, 136, 168)
pygame.rect參數的解釋如下: pygame.Rect(left, top, width, height)

if self.moving_right and self.rect.right < self.screen_rect.right:    
    self.center += self.ai_settings.ship_speed
#圖片右邊的值小於屏幕右邊的值時,纔可以向右移動
if self.moving_left and self.rect.left> 0:
    self.center -= self.ai_settings.ship_speed
#圖片左邊的值大於0時,即左邊沒有靠邊,纔可以向右左移動
if self.moving_up and self.rect.top > 0:
    self.bottomer -= self.ai_settings.ship_speed
#圖片頂部的座標大於0時,即頂部沒有靠頂時,纔可以向上移動
if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
    self.bottomer += self.ai_settings.ship_speed
#圖片底邊的值小於屏幕底邊的值時,纔可以向下移動

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章