会玩,有人用 Python 模拟导弹防御!







import pygame,sysfrom math import *pygame.init()screen=pygame.display.set_mode((800,700),0,32)missile=pygame.image.load('element/red_pointer.png').convert_alpha()x1,y1=100,600 #导弹的初始发射位置velocity=800 #导弹速度time=1/1000 #每个时间片的长度clock=pygame.time.Clock()old_angle=0while 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)) #两点距离公式section=velocity*time #每个时间片需要移动的距离sina=(y1-y)/distancecosa=(x-x1)/distanceangle=atan2(y-y1,x-x1) #两点线段的弧度值x1,y1=(x1+section*cosa,y1-section*sina)d_angle = degrees(angle) #弧度转角度screen.blit(missile, (x1-missile.get_width(), y1-missile.get_height()/2))dis_angle=d_angle-old_angle #dis_angle就是到下一个位置需要改变的角度old_angle=d_angle #更新初始角度pygame.display.update()

missiled = pygame.transform.rotate(missile, -(d_angle))screen.blit(missiled, (x1-missile.get_width(), y1-missile.get_height()/2))







screen.blit(missiled, (x1-width+(x1-C[0]),y1-height/2+(y1-C[1])))

import pygame,sysfrom math import *pygame.init()font1=pygame.font.SysFont('microsoftyaheimicrosoftyaheiui',23)textc=font1.render('*',True,(250,0,0))screen=pygame.display.set_mode((800,700),0,32)missile=pygame.image.load('element/rect1.png').convert_alpha()height=missile.get_height()width=missile.get_width()pygame.mouse.set_visible(0)=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)=pygame.mouse.get_pos() #获取鼠标位置,鼠标就是需要打击的目标distance=sqrt(pow(x1-x,2)+pow(y1-y,2)) #两点距离公式section=velocity*time #每个时间片需要移动的距离sina=(y1-y)/distancecosa=(x-x1)/distanceangle=atan2(y-y1,x-x1) #两点间线段的弧度值fangle=degrees(angle) #弧度转角度=(x1+section*cosa,y1-section*sina)missiled=pygame.transform.rotate(missile,-(fangle))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))(x1-width+(x1-C[0]),y1-height/2+(y1-C[1])))(x,y)) #鼠标用一个红色*代替pygame.display.update()以上便是用Python模拟导弹自动追踪的代码实例。 
推荐阅读:
入门: 最全的零基础学Python的问题 | 零基础学了8个月的Python | 实战项目 |学Python就是这条捷径
干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 | 从万众期待到口碑扑街!唐探3令人失望 | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影
趣味:弹球游戏 | 九宫格 | 漂亮的花 | 两百行Python《天天酷跑》游戏!
AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影
小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!| 再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|
年度爆款文案
点阅读原文,领AI全套资料! 
评论


