Advertisement
zaslavsky

pygame example

Sep 21st, 2014
4,414
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.76 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. #  battlefield.py
  5. #  
  6. #  Copyright 2014 Dmitry Zaslavsky <zaslavsky@CELESTIA>
  7. #   _____________________________
  8. #__/                             \_____
  9. #       mail:zaslavsky@live.ru
  10. #       Phone: 8-903-257-06-31
  11. #       www.vk.com/dmitry.zaslavsky
  12. #__                               _____
  13. #  \_____________________________/
  14. #
  15. #
  16. import pygame, random , math , configparser
  17. from pygame import gfxdraw
  18.  
  19.        
  20. def error(ID): # Printing errors messages
  21.     if ID==1:print("ERROR:\n\tFile (data\config.ini) not found or Broken\n\tPleace check (config.ini) file")
  22.     if ID==2:print(("ERROR:\n\tFile (Image File) not found\n\tor wrong file path in (config.ini) > (imageFile)\n\tCheck Data files"))
  23.     print("\a\a\a\nPress any key...")
  24.     input()    
  25.    
  26.  
  27. #Read INI File.
  28. config = configparser.ConfigParser()
  29. config.read('data\config.ini')
  30. try:data=config['OPTIONS']
  31. except:error(1)
  32. IMAGEFILE=data.get('ImageFile')
  33. SECTORCOLOR = (0,0,0)
  34.  
  35. #Pygame init
  36.  
  37. mainloop = True
  38.  
  39. pygame.init()
  40. pygame.display.set_caption("Battlefield")
  41. try:background = image = pygame.image.load(IMAGEFILE)
  42. except:error(2)
  43. WH=W,H=background.get_size()
  44. screen=pygame.display.set_mode(WH)
  45. background = background.convert()
  46. image = image.convert()
  47.  
  48. ######################################
  49. def rand(a,b): #short randomization
  50.     return random.randint(a,b)
  51.  
  52. def getdata(): # read INI file
  53.     global dotx,doty,DOT,FAR,FOV,targets,ENEMYES,TARGETS,PURE,ANGLEWEIGHT
  54.     TARGETS=[]
  55.     data=config['OPTIONS']
  56.     RANDOM=int(data.get('Generate'))
  57.     PURE=int(data.get('Make_angle_pure'))
  58.     ANGLEWEIGHT=int(data.get('angles_weight'))
  59.     if RANDOM == 0:
  60.         data=config['VALUES']
  61.         DOT=(data.get('DOTCORD'))
  62.         DOT=DOT.split(',')
  63.         DOT=dotx,doty=int(DOT[0]),int(DOT[1])
  64.         FOV=int(data.get('FOV'))
  65.         FAR=int(data.get('FAR'))
  66.         ENEMYES=((data.get('ENEMYES')))
  67.         TARGETS=parser(ENEMYES)
  68.     else:
  69.         data=config['GENERATE_VALUES']
  70.        
  71.         DOTA=(data.get('DOTCORD_MAX'))
  72.         DOTA=DOTA.split(',')
  73.         DOTA=dotax,dotay=int(DOTA[0]),int(DOTA[1])
  74.        
  75.         FOVA=int(data.get('FOV_MAX'))
  76.         FARA=int(data.get('FAR_MAX'))
  77.        
  78.         DOTB=(data.get('DOTCORD_MIN'))
  79.         DOTB=DOTB.split(',')
  80.         DOTB=dotbx,dotby=int(DOTB[0]),int(DOTB[1])
  81.        
  82.         FOVB=int(data.get('FOV_MIN'))
  83.         FARB=int(data.get('FAR_MIN'))
  84.        
  85.         DOT=dotx,doty=rand(dotbx,dotax),rand(dotby,dotay)
  86.         FOV=rand(FOVB,FOVA)
  87.         FAR=rand(FARB,FARA)
  88.        
  89.         ENEMYESCOUNT=int(data.get('ENEMYESCOUNT'))
  90.         TARGETS=randenemy(ENEMYESCOUNT)
  91.  
  92.  
  93. def parser(array):# Parser for INI
  94.     output=[]
  95.     for i in (array.split('\n')):
  96.         part=int(i.split(',')[0]),int(i.split(',')[1])
  97.         output.append(part)
  98.     return output
  99.    
  100. def corect(array): # Cordinate localization
  101.     output=[]
  102.     for i in array:
  103.         data=x,y=(i[0]-dotx,i[1]-doty)
  104.         output.append(data)
  105.     return output
  106.    
  107.    
  108.  
  109. def enemydraw(array): # draw red dots =D
  110.     for i in array:
  111.         pygame.draw.circle(background, (0,0,0), i, 7)
  112.         pygame.draw.circle(background, (255,0,0), i, 5)
  113.         pygame.draw.circle(background, (0,0,0), i, 2)
  114.  
  115. def randenemy(count): #  generate enemy positions
  116.     output=[]
  117.     while count!=0:
  118.         data=x,y=(rand(0,W),rand(0,H))
  119.         output.append(data)
  120.         count-=1
  121.     return output
  122.            
  123. def angle(x,y):             # return angle
  124.     rad=math.atan2(y,x)
  125.     angle=math.degrees(rad)
  126.     if angle<0:angle+=360
  127.     return angle
  128.    
  129. def drawsector(angle,far,tar): #drawing fire range
  130.     agh=tar-(angle/2)
  131.     for i in range(angle-1):
  132.         poo=angletocord(agh+i,far)
  133.         pygame.draw.aaline(background, (255,255,0), (dotx,doty),poo,5)
  134.     cord=x,y=dotx,doty
  135.     a1=math.radians(tar+(angle/2))
  136.     a2=math.radians(tar-(angle/2))
  137.     lx1=(math.cos(a1)*far)+x
  138.     ly1=(math.sin(a1)*far)+y
  139.     lx2=(math.cos(a2)*far)+x
  140.     ly2=(math.sin(a2)*far)+y
  141.     pygame.draw.aaline(background, (SECTORCOLOR), (x,y),(lx1,ly1),5)
  142.     pygame.draw.aaline(background, (SECTORCOLOR), (x,y),(lx2,ly2),5)
  143.    
  144. def angletocord(angle,far): #angle to coordinat
  145.     x=(math.cos(math.radians(angle))*far)+dotx
  146.     y=(math.sin(math.radians(angle))*far)+doty
  147.     out=x,y
  148.     return out
  149.        
  150. def pureangle(array):# make angle good
  151.     angle=0
  152.     output=[]
  153.     cluster=[]
  154.     for i in range(len(array)):
  155.         if array[i]==(max(array)):
  156.             cluster.append(i)
  157.             try:
  158.                 if array[i+1]!=(max(array)):
  159.                     output.append(cluster)
  160.                     cluster=[]
  161.             except:
  162.                 output.append(cluster)
  163.                 cluster=[]
  164.     for i in output:cluster.append(len(i))
  165.     for i in output[cluster.index(max(cluster))]:angle+=i
  166.     angle=(angle/len(output[cluster.index(max(cluster))]))
  167.     return angle
  168.  
  169. def optimize(targets): # seporate enemyes who stay beyond the circle
  170.     output=[]
  171.     for i in range(len(targets)):
  172.         x=targets[i][0]
  173.         y=targets[i][1]
  174.         gipo=math.sqrt((x**2)+(y**2))
  175.         if gipo<FAR:output.append(targets[i])
  176.     return output
  177.                
  178. def findangle(targets): # finding better shooting angle
  179.     Rotate=0
  180.     angles=[]
  181.     targets=optimize(targets)
  182.     while Rotate!=360:
  183.         count=0
  184.         for i in range(len(targets)):
  185.             x=targets[i][0]
  186.             y=targets[i][1]
  187.             a=(Rotate-FOV/2)
  188.             b=(Rotate+FOV/2)
  189.             gipo=math.sqrt((x**2)+(y**2))
  190.             if ANGLEWEIGHT==1:
  191.                 if a<angle(x,y)<b and gipo<FAR:count+=1
  192.             else:
  193.                 if a<angle(x,y)<b and gipo<FAR:count+=1
  194.         angles.append(count)
  195.         if ANGLEWEIGHT==1:
  196.             poo=angletocord(Rotate,count*10)
  197.             pygame.draw.aaline(background, (0,255,0), (dotx,doty),poo,5)
  198.         Rotate+=1
  199.     if PURE==1:V=(pureangle(angles))
  200.     else:V=angles.index(max(angles))
  201.     print("\n_____________________________________________________")
  202.     print("Gun angle: "+str(360-V))
  203.     print("Targets covered: ")+str(max(angles))
  204.     if (max(angles))==0:print("Sad situation. No Enemyes to shoot")
  205.     return V
  206.  
  207. def execute(): # execute algoritm and little bit drawing
  208.     try:getdata()
  209.     except:
  210.         print("fail")
  211.         quit()
  212.     pygame.draw.circle(background, (0,0,0), (dotx,doty), 11, 0)
  213.     pygame.draw.circle(background, (40,130,40), (dotx,doty), 9, 0)
  214.     pygame.draw.circle(background, (100,200,90), (dotx,doty), 7, 0)
  215.     pygame.draw.circle(background, (0,0,0), (dotx,doty), 4, 0)
  216.     pygame.gfxdraw.aacircle(background, dotx,doty, FAR, (160,120,217))
  217.     direction=findangle(corect(TARGETS))
  218.     drawsector(FOV,FAR,direction)
  219.     enemydraw(TARGETS)
  220.     pygame.gfxdraw.arc(background, dotx, doty, FAR, direction-FOV/2, direction+FOV/2,SECTORCOLOR)
  221.  
  222. #we start here!
  223. execute()# predraw
  224. while mainloop:#main loop
  225.     for event in pygame.event.get():
  226.         if event.type == pygame.QUIT:
  227.             mainloop = False
  228.         elif event.type == pygame.KEYDOWN:
  229.             if event.key == pygame.K_ESCAPE:
  230.                 mainloop = False
  231.             if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
  232.                 background.blit(image, (0,0))
  233.                 execute()
  234.                 screen.blit(image, (0,0))
  235.                 #pygame.draw.circle(background, (100,100,100), (random.randint(0,500),random.randint(0,500)), 3, 0)
  236.     screen.blit(background, (0,0))                    
  237.     pygame.display.update()            
  238.     pygame.display.flip()
  239. pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement