python導彈自動追蹤以及實時圖片旋轉算法(呂萬友)

以下是 Python-pygame代碼實現:  

import sys, pygame
from math import *

pygame.init()
font1 = pygame.font.SysFont('microsoftyaheimicrosoftyaheiui', 23)
textc = font1.render('*', True, (250, 0, 0))  # this is the target that missile wants to attack
screen = pygame.display.set_mode((800, 700), 0, 32)  # set the attribution of screen
missile = pygame.image.load('C:/Users/win10/Desktop/rect1.png').convert_alpha()
bomb = pygame.image.load('C:/Users/win10/Desktop/bomb.png').convert_alpha()
height = missile.get_height()
width = missile.get_width()
pygame.mouse.set_visible(0)
x1, y1 = 100, 600  # 導彈的初始發射位置
velocity = 800  # 導彈速度
time = 1 / 1000  # 每個時間片的長度
clock = pygame.time.Clock()
A = ()
B = ()
C = ()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    clock.tick(300)
    x, y = pygame.mouse.get_pos()  # 獲取鼠標位置,鼠標就是需要打擊的目標
    distance = sqrt(pow(x1 - x, 2) + pow(y1 - y, 2))  # 兩點距離公式
    print('distance  :   ', distance)
    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))  # 得到旋轉角度後的missile圖片

    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)
    screen.fill((0, 0, 0))
    if distance > 1:
        screen.blit(missiled, (x1 - width + (x1 - C[0]), y1 - height / 2 + (y1 - C[1])))  # 旋轉後的missile 位塊顯示在 C點位置。
        screen.blit(textc, (x, y))  # 鼠標用一個紅色*代替
    else:
        screen.blit(bomb, (x, y))  # 旋轉後的missile 位塊顯示在 C點位置。
    pygame.display.update()

代碼中需要的照片:  

  分別命名爲: rect1.png  、bomb.png

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