1.效果圖

2.注意事項,代碼里有說明
3.完整的代碼
#導出模塊 import pygame,sys from math import * #設置RESIZABLE前,必須導出下面的模塊,否則報錯 #同事放大窗口就會發現,窗口的背景默認黑色,但游戲的屏幕大小設定是固定的,如果設置不同顏色就會發現 from pygame.locals import * #初始化 pygame.init() #標題設置 pygame.display.set_caption("導彈追蹤鼠標游戲") #如果不設置就是默認pygame window #screen=pygame.display.set_mode((800,700),0,32) #屏幕大小等設置 #RESIZABLE,屏幕大小可調節,我比較喜歡這個,一般都加入set_mode中 screen=pygame.display.set_mode((800,700),RESIZABLE,0,32) #鼠標頭的設置,大小、樣式、顏色、可見 font1=pygame.font.SysFont('microsoftyaheimicrosoftyaheiui',23) textc=font1.render('*',True,(250,0,0)) #鼠標為紅色的* #在游戲區的屏幕里,0代表原始鼠標箭頭不可見False;1代表可見,為True pygame.mouse.set_visible(0) #圖片導彈引入和大小取值 #導彈圖片不能太大,自己可以隨意設定一張圖片,放在指定的目錄下 missile=pygame.image.load('missile1.png').convert_alpha() height=missile.get_height() width=missile.get_width() #定義導彈的相關參數 x1,y1=100,600 #導彈的初始發射位置 velocity=800 #導彈速度 time=1/1000 #每個時間片的長度 # 創建時鍾對象 (可以控制游戲循環頻率) clock=pygame.time.Clock() #定義三個空的元組,用來放坐標x和y A=() B=() C=() while True: #游戲的pygame的while循環 #退出設定,一般在pygame中固定在while的第一步 for event in pygame.event.get(): if event.type==pygame.QUIT: sys.exit() clock.tick(300) #每秒循環300次 x,y=pygame.mouse.get_pos() #獲取鼠標位置,鼠標就是需要打擊的目標 #----以下是本游戲的關鍵,在以后類似的設置中可作為固定模塊使用,可以收藏---- distance=sqrt(pow(x1-x,2)+pow(y1-y,2)) #兩點距離公式 section=velocity*time #每個時間片需要移動的距離 #公式 sina=(y1-y)/distance cosa=(x-x1)/distance angle=atan2(y-y1,x-x1) #兩點間線段的弧度值 fangle=degrees(angle) #弧度轉角度 x1,y1=(x1+section*cosa,y1-section*sina) missiled=pygame.transform.rotate(missile,-(fangle)) #下面4個if為轉角轉彎設置 if 0<=-fangle<=90: A=(width*cosa+x1-width,y1-height/2) B=(A[0]+height*sina,A[1]+height*cosa) if 90<-fangle<=180: A = (x1 - width, y1 - height/2+height*(-cosa)) B = (x1 - width+height*sina, y1 - height/2) if -90<=-fangle<0: A = (x1 - width+missiled.get_width(), y1 - height/2+missiled.get_height()-height*cosa) B = (A[0]+height*sina, y1 - height/2+missiled.get_height()) if -180<-fangle<-90: A = (x1-width-height*sina, y1 - height/2+missiled.get_height()) B = (x1 - width,A[1]+height*cosa ) #----以上是關鍵---- #獲取動態坐標 C = ((A[0] + B[0]) / 2, (A[1] + B[1]) / 2) #屏幕的fill只能放在blit的前面 screen.fill((0,25,120)) #游戲所在的活動的屏幕bg背景填充深藍色 #注意上面設置RESIZABLE提到的區別的黑色(0,0,0) #修改bug,增加1,目的就是將mx和my由float轉換成int,因為在元組中需要int格式的數據 mx=int(float(x1-width+(x1-C[0]))) my=int(float(y1-height/2+(y1-C[1]))) #圖片顯示及位置mx和my,(mx,my)這是一個元組 #screen.blit(missiled, (x1-width+(x1-C[0]),y1-height/2+(y1-C[1]))) #報錯bug screen.blit(missiled, (mx,my)) #修改bug,增加2 #鼠標顯示及位置 screen.blit(textc, (x,y)) #鼠標用一個紅色*代替 #游戲顯示不斷更新 pygame.display.update()
