《外星人入侵》之學習筆記
1、資料型別轉換錯誤
ValueError: invalid literal for int() with base 10:
a = '10' b = 'ha' c = '' print(int(a)) print(int(b)) print(int(c)) #10 #ValueError: invalid literal for int() with base 10: 'ha' #不能將字串轉換為整數 #ValueError: invalid literal for int() with base 10: '' #不能將空字元轉換為整數 #空格和小數也不行,小數如果不在引號內就可以
2、建立一個藍色背景的遊戲視窗
#外星人入侵 import sys import pygame def run_game(): pygame.init()#初始化遊戲 screen = pygame.display.set_mode((600,500))#建立螢幕 pygame.display.set_caption("外星人入侵")#命名 bg_color = (0,0,255)#背景色 while True: for event in pygame.event.get():#監視鍵盤和滑鼠事件 if event == pygame.QUIT: sys.exit() screen.fill(bg_color)#每次迴圈都重繪螢幕 pygame.display.flip()#顯示最近繪製的螢幕 run_game()
3、新增飛船影象:在遊戲中幾乎可以使用任何型別的影象檔案,但使用點陣圖(.bmp)最為簡單,因為Python預設載入點陣圖。
雖然可配置Python使用其他檔案型別,但有些檔案型別要求你在計算機上安裝相應的影象庫。
方法:pygame.image.load('images\ship.bmp'),圖片檔案最好放在程式的下一級資料夾內
4、get_rect()函式可以獲取相應surface的屬性rect(外接矩形)。處理rect物件時,可使用矩形四角和中心的x,y座標的值來指定矩形的位置。
要將遊戲元素居中,可設定相應的rect物件的屬性center,centerx,centery。
要將遊戲元素與螢幕邊界對齊,可設定屬性top,bottom,left,right。
要調整遊戲元素的水平或垂直位置,可使用X和Y,他們分別是相應矩形左上角的x和y座標。
注意:在Python中,座標原點(0,0)位於螢幕左上角,向右下方移動時,座標值增大。
def center_ship(self): '''讓飛船在螢幕底部居中''' self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom
5、screen.blit(image,rect)按照指定位置繪製圖片
def blitme(self): '''在指定位置繪製飛船''' self.screen.blit(self.image, self.rect)
6、檢測滑鼠和鍵盤型別
event.type == pygame.QUIT#退出 event.type == pygame.KEYDOWN#鍵盤按下 event.type == pygame.KEYUP#鍵盤松開 event.key == pygame.K_RIGHT#鍵盤向右鍵 event.key == pygame.K_LEFT#鍵盤向左鍵 event.key == pygame.K_DOWN#鍵盤向下鍵 event.key == pygame.K_UP#鍵盤向上鍵 event.key == pygame.K_SPACE#空格鍵 event.key == pygame.K_q#q鍵 event.type == pygame.MOUSEBUTTONDOWN#滑鼠鍵
7、get_pos() 獲取座標
button.rect.collidepoint(mouse_x,mouse_y) 檢查滑鼠單擊位置是否在按鈕的rect內
#獲得滑鼠點選位置的座標 mouse_x,mouse_y = pygame.mouse.get_pos() #檢測滑鼠的單擊位置是否在play按鈕的rect內 button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y)
8、模組python.sprite中的Sprite類,通過使用精靈,可將遊戲中相關的元素編組,進而同時操作編組中的所有元素。
使用方法:建立一個繼承類Sprite的類
from pygame.sprite import Sprite class Bullet(Sprite): '''一個對飛船射出的子彈管理的類,繼承精靈類Sprint''' def __init__(self,ai_settings,screen,ship): #在飛船所在的位置建立一個子彈類 super().__init__()
9、pygame.Rect(x,y,width,height) 從空白處建立一個矩形。
建立這個類的例項時,必須提供矩形左上角的x,y座標,還有矩形的寬度和高度。
#在(0,0)處建立一個表示子彈的矩形,再移到正確位置 self.rect = pygame.Rect(0,0,ai_settings.bullet_width, ai_settings.bullet_height) self.rect.centerx = ship.rect.centerx self.rect.top = ship.rect.top
10、draw.rect()該函式使用儲存在color中的顏色填充圖形的rect佔據的螢幕部分
#在螢幕上繪製子彈 pygame.draw.rect(screen,color,rect)
11、bullets.sprites() 函式返回一個列表
# 在螢幕上繪製所有子彈 for bullet in bullets.sprites(): bullet.draw_bullet()
12、pygame.sprite.groupcollide(bullets,aliens,True,True) 函式用於檢測兩個編組的成員之間的碰撞;
將每顆子彈的rect同每個外星人的rect進行比較,返回一個字典,其中其中包含發生了碰撞的子彈和外星人;
在這個字典中,每個鍵都是一顆子彈,相應的值都是被擊中的外星人。
兩個實參True,告訴Python刪除發生碰撞的子彈和外星人,如果想讓子彈能夠穿行到螢幕頂端,可將第一個布林實參設定為False,這樣只刪除被擊中的外星人。
13、pygame.sprite.spritecollideany(ship,aliens) 函式接受兩個實參,一個精靈,一個編組,它檢查編組是否有成員與精靈發生碰撞。
14、模組time中的函式sleep(1),可以使遊戲暫停,括號內單位為秒。
15、模組python.font,它讓pygame能夠將文字渲染到螢幕上。
font.render(msg,True,text_color,bg_color)
import pygame.font #先指定用什麼字型和字號來渲染文字 button.font = pygame.font.SysFont(None,48) #實參None代表使用預設字型,48指定文字字號 #將文字轉換為影象,顯示到螢幕上 msg_image = self.font.render(msg,True,self.text_color, self.button_color) #msg為文字內容,布林實參代表開啟反鋸齒功能(讓文字的邊緣更平滑) #剩下兩個是文字顏色和背景顏色,如果不指定背景色,預設背景透明
例如:將得分顯示到螢幕右上角
def prep_score(self): '''將得分變為10的整數倍,用逗號表示千位分隔符''' rounded_score = round(self.stats.score,-1) # 將數值轉換為字串時,在其中插入逗號 score_str = "{:,}".format(rounded_score) #將得分渲染為一幅影象 self.score_image = self.font.render(score_str,True,self.text_color, self.ai_settings.bg_color) #將得分放在螢幕右上角 self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20 def show_score(self): '''在螢幕上顯示得分''' self.screen.blit(self.score_image,self.score_rect)
16、通過向set_visible()傳遞False,讓Python隱藏游標,True,讓游標可見
# 隱藏游標 pygame.mouse.set_visible(False)
17、initialize_dynamic_settings() 用來初始化隨著遊戲進行而變化的屬性。
def initialize_dynamic_settings(self): '''初始化隨遊戲進行而變化的量''' # 飛船的移動速度 self.ship_speed_factor = 1.5 # 子彈的移動速度 self.bullet_speed_factor = 5 # 外星人的移動速度 self.alien_speed_factor = 0.5 self.fleet_direction = 1 # 1表示向右移動,-1表示向左移動 # 記分 self.alien_points = 50
18、遊戲每次退出時將最高分儲存到文字中,每次點選play按鈕,讀取文字中的最高得分
#開始遊戲時讀取最高分 with open('high_score.txt','r') as hs_object: self.high_score = int(hs_object.read()) #遊戲結束時,儲存最高分 with open("high_score.txt", 'w') as hs_object: hs_object.write(str(stats.high_score))