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))