TankorSmash

squares.py

Nov 17th, 2011
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 34.78 KB | None | 0 0
  1. import pygame as pygame
  2. #from pygame.locals import *
  3. import random
  4. import os.path
  5. import glob
  6. import math
  7. import time
  8. import Tkinter as tk
  9. #import statsWin
  10. import GUI2
  11.  
  12. #import thread
  13. #import threading
  14. import multiprocessing as multi
  15.  
  16. #constants
  17. WIDTH = 800
  18. HEIGHT = 600
  19.    
  20. FRAMERATE = 30
  21.  
  22. #directions
  23. UP = (0, -1)
  24. DOWN = (0, 1)
  25. LEFT = (-1, 0)
  26. RIGHT = (1, 0)
  27.  
  28. TLEFT = (-1,-1)
  29. TRIGHT = (1,-1)
  30. BLEFT = (-1,1)
  31. BRIGHT = (1,1)
  32.  
  33. DIRECTIONS = [UP,DOWN,LEFT,RIGHT,TLEFT,TRIGHT,BLEFT,BRIGHT]
  34.  
  35. STOP = (0,0)
  36.  
  37. #colors
  38. BLACK = (0,0,0)
  39. WHITE = (255,255,255)
  40.  
  41. RED = (255,0,0)
  42. GREEN = (0,255,0)
  43. BLUE = (0,0,255)
  44.  
  45. #keyboard directions and their equivalents
  46. keyDirs = {
  47.             pygame.K_DOWN : DOWN,
  48.             pygame.K_UP : UP,
  49.             pygame.K_LEFT: LEFT,
  50.             pygame.K_RIGHT: RIGHT,
  51.            
  52.             pygame.K_s : DOWN,
  53.             pygame.K_w : UP,
  54.             pygame.K_a: LEFT,
  55.             pygame.K_d: RIGHT,
  56.            
  57.             pygame.K_KP2: DOWN,
  58.             pygame.K_KP8: UP,
  59.             pygame.K_KP4: LEFT,
  60.             pygame.K_KP6: RIGHT,
  61.            
  62.             pygame.K_KP7: TLEFT,
  63.             pygame.K_KP9: TRIGHT,
  64.             pygame.K_KP1: BLEFT,
  65.             pygame.K_KP3: BRIGHT,
  66.            
  67.             }
  68.  
  69.  
  70. #rotations
  71. leftTurns= {
  72.             UP:LEFT,
  73.             LEFT:DOWN,
  74.             DOWN:RIGHT,
  75.             RIGHT:UP}
  76.  
  77.  
  78. rightTurns = {
  79.             UP:RIGHT,
  80.             RIGHT:DOWN,
  81.             DOWN:LEFT,
  82.             LEFT:UP}
  83.  
  84.  
  85. acrossTurns = {UP:DOWN,
  86.                DOWN:UP,
  87.                LEFT:RIGHT,
  88.                RIGHT:LEFT}
  89.  
  90. #ai levels
  91. DUMB = 0
  92. AVG = 1
  93. SMART = 2
  94.  
  95. #-#lists#-#
  96. ALLTHINGS = set()
  97.  
  98. #all live chars
  99. MEN = []
  100.  
  101. # ...and their AIs
  102. AIs = []
  103.  
  104. #all live bullets
  105. BULLETS = []
  106. SHRAPNEL = []
  107.  
  108. #all dead things
  109. STATS = []
  110.  
  111. mousePressed = False
  112.  
  113. def isKey(event, k):
  114.     '''short for event.key == pygame.K-KEY'''
  115.     #getattr wo
  116.     methodToCall = getattr(pygame, 'K_{0}'.format(k))
  117.     if event.key == methodToCall:        return True
  118.        
  119.    
  120.  
  121.  
  122.  
  123. #set game icon
  124. def seticon(iconname):
  125.     """
  126.    give an iconname, a bitmap sized 32x32 pixels, black (0,0,0) will be alpha channel
  127.    
  128.    the windowicon will be set to the bitmap, but the black pixels will be full alpha channel
  129.    
  130.    can only be called once after pygame.init() and before somewindow = pygame.display.set_mode()
  131.    
  132.    from:http://www.pygame.org/docs/ref/display.html#pygame.display.set_icon comments
  133.    """
  134.     #create a surface for icon
  135.     icon=pygame.Surface((256,256))
  136.     icon.set_colorkey((255,255,255))#and call that color transparent
  137.     rawicon= pygame.image.load(iconname)#must be 32x32, black is transparent
  138.     for i in range(0,256):
  139.         for j in range(0,256):
  140.             icon.set_at((i,j), rawicon.get_at((i,j)))
  141.     pygame.display.set_icon(icon)#set wind
  142.  
  143.  
  144.  
  145. class Spawner():
  146.     '''used to spawn entities'''
  147.     def __init__(self, *args):
  148.         pass
  149.    
  150.     def spawn(self, subject, *args):
  151.         '''spawn an entity '''
  152.         if subject == 'mob':
  153.             print 'mob made'
  154.             shot = shooter(1, 100)
  155.             AI = ai(DUMB)
  156.            
  157.             W = WIDTH * random.random()
  158.             H = HEIGHT * random.random()
  159.             mob = anything((W, H),'Bob',pathname, shooter=shot, ai= AI)
  160.             mob.shooter.getTarget()
  161.             return mob
  162.        
  163.         else :
  164.             print 'spawn nothing'
  165.  
  166. class Stats():
  167.     '''A class for managing statistics and information
  168.    about any given instance, acting asadvanced dictionary use'''
  169.    
  170.     def __init__(self, owner):
  171.         '''init it all'''
  172.         self.owner = owner
  173.         #get the stats
  174.         self.getBasicStats()
  175.         self.getShooterStats()
  176.        
  177.     def getBasicStats(self):
  178.         '''gets all the basic stats for a creature such as name
  179.        and position upon creation'''
  180.    
  181.         self.basicStats = {
  182.    
  183.             'Name': self.owner.name,
  184.             'Pos': self.owner.pos,
  185.                             }  
  186.              
  187.     def getShooterStats(self):
  188.         '''get the stats from the shooter component'''
  189.        
  190.         if self.owner.shooter:
  191.             print self.owner.name, 'is a shooter'
  192.             self.shooterStats = {
  193.                'Times Fired': self.owner.shooter.timesFired,
  194.                'Times Hit': self.owner.timesHit,
  195.                                }
  196.         else:
  197.             print self.owner.name, 'isn\'t a shooter'
  198.        
  199.     def getAiStats(self):
  200.         '''gets the stats from the AI component'''
  201.        
  202.         if self.owner.ai:
  203.             print self.owner.name, 'is an AI'
  204.             self.aiStats  = {
  205.                 '': '',}
  206.            
  207.         else:
  208.             print self.owner.name, 'isn\'t an AI'
  209. class Vector():
  210.    
  211.  
  212.     def radToDeg(self, rad):
  213.         #rad / (pi/180) = degree
  214.         deg = rad / (3.14/180)
  215.         return deg
  216.        
  217.     def degToRad(self, deg):
  218.         #rad = degree * (pi/180)
  219.         return deg * (3.14/180)
  220.    
  221.     def subtract(self, first,second):
  222.         '''substract second from first'''
  223.         sub = tuple([b-a for a,b, in zip(first,second)])
  224.         return sub
  225.    
  226.     def dot(self, *parts):
  227.        
  228.         list = []
  229.         for part in parts:
  230.             part = V.norm(part)
  231.             list.append(part)
  232.        
  233.         dot =  (list[0][0] * list[1][0]) + (list[0][1]*list[1][1])
  234.         print 'dot: ',dot
  235.         return dot
  236.    
  237.    
  238.     def revNorm(self, vector):
  239.         '''reverses norm(), but doesn't'''
  240.         x = vector[0]
  241.         y = vector[1]
  242.        
  243.         #length
  244.         revNormed = ((x*5),(y*5))
  245.        
  246.         return revNormed
  247.    
  248.     def norm(self, vector):
  249.        
  250.         x = vector[0]
  251.         y = vector[1]
  252.         #normalize a vector by dividing it by its length
  253.         len = V.length(vector)
  254.         try:
  255.             normalized = ((x/len),(y/len))
  256.         except ZeroDivisionError:
  257.             normalized = (0,0)
  258.         #print 'norm: ', normalized
  259.         return normalized
  260.    
  261.     def length(self, vector):
  262.        
  263.         x = vector[0]
  264.         y = vector[1]
  265.        
  266.         length =math.sqrt(( x**2 + y**2))
  267.         #print 'length: ',length
  268.         return length
  269.    
  270.     def distance(self, first, second):
  271.        
  272.         dist= tuple([b-a for a,b in zip(first,second)])
  273.         dist = V.length(dist)
  274.        
  275.         #print 'distance: ', dist
  276.         return dist
  277.  
  278.  
  279. #handle keys
  280. def key_event(event):
  281.    
  282.     ##WORKING ON THIS: TRY TO MAKE THIS A LIST INSTEAD
  283.     ## OF ALL THE DIRECTIONS ONE AFTER ANOTHER
  284.     if event.type == pygame.KEYUP:
  285.         #tuple below is directions
  286.         if event.key in keyDirs.keys():
  287.             #for brick in bricks:
  288.                 #brick.setMove(moving=False, dir =brick.dir)
  289.             circle.go(False)
  290.     elif event.type == pygame.KEYDOWN:
  291.         if event.key in keyDirs.keys():
  292.            
  293.  
  294.             #print 'keys pressed'
  295.             direction= keyDirs[event.key]
  296.             circle.changeDir(direction)
  297.             circle.go(True)
  298.  
  299.  
  300.         elif isKey(event, 'n'):
  301.             reload(GUI2)
  302.             print 'reloaded module GUI'
  303.             pass
  304.  
  305.         elif isKey(event, 'c'):
  306.             circle.shooter.fire(circle.direction,'bullet')
  307.             print 'FIRED {0} TIMES'.format(circle.shooter.timesFired)
  308.             pass
  309.        
  310.         #clear screen, slopilly.
  311.         elif isKey(event,'RETURN'):
  312.             screen.fill((0,0,0))
  313.  
  314.         #elif isKey(event,'z'):
  315.             #print 'circle: ',circle.getPos(), ' bob: ', bob.getPos()
  316.            
  317.         elif isKey(event,'z'):
  318.             if hasattr(GUI2, 'root'):
  319.                 print GUI2.root.TEST
  320.            
  321.         elif isKey(event,'x'):
  322.             '''check if circle is in bob's rect'''
  323.             print 'RECTS for circle: ', circle.rect.x,\
  324.                                         circle.rect.y,
  325.             print 'RECTS for bob: ', bob.rect.x,\
  326.                                      bob.rect.y
  327.              
  328.             if circle.rect.colliderect(bob):
  329.                 print 'COLLISION!!'  
  330.                                        
  331.                            
  332.                                        
  333.            
  334.  
  335.         #change animation
  336.         elif event.key in (pygame.K_0,pygame.K_1,pygame.K_2,
  337.                            pygame.K_3,pygame.K_4,pygame.K_5,
  338.                            pygame.K_6,pygame.K_7,pygame.K_8,
  339.                            pygame.K_9):
  340.            
  341.             keys = {pygame.K_0 :9,
  342.                     pygame.K_1 :0,
  343.                     pygame.K_2 :1,
  344.                     pygame.K_3 :2,
  345.                     pygame.K_4 :3,
  346.                     pygame.K_5 :4,
  347.                     pygame.K_6 :5,
  348.                     pygame.K_7 :6,
  349.                     pygame.K_8 :7,
  350.                     pygame.K_9 :8}
  351.            
  352.             circle.curFrameNum = keys[event.key]
  353.             circle.curFrame = circle.animList[circle.curFrameNum].copy()
  354.             circle.direction = RIGHT
  355.             circle.rotate()
  356.             print 'changed frame'
  357.  
  358.  
  359.         elif isKey(event,'m'):
  360.             func = GUI2.run
  361.             #threading module
  362.             #thread_GUI2 = threading.Thread(group = None, target = func, name='GUI THREAD')
  363.             #thread_GUI2.start()
  364.            
  365.             #no threading
  366.             GUI2.run()
  367.            
  368.             #multiprocessing module
  369.             #thread_GUI2 = multi.Process(target = func, name='GUI THREAD')
  370.             #thread_GUI2.start()
  371.            
  372.             print 'thread ran'
  373.            
  374.         elif isKey(event, 'b'):
  375.             spawner.spawn('mob')
  376.            
  377.            
  378.        
  379.  
  380.  
  381. class anything:
  382.     def __init__(self, (x,y),name, animFolder,
  383.                  direction=RIGHT, moving=False,
  384.                  shooter= None, ai = None):
  385.         '''supposed to be the thing every class is inherited from
  386.         but hey, here we are'''
  387.        
  388.         #create and append appropriate stats for object
  389.         self.initLists()
  390.        
  391.         #change x and y, NEVER pos!
  392.         self.pos = (x,y)
  393.         self.x, self.y = self.pos
  394.         self.name = name
  395.        
  396.         self.animList = self.animLister(animFolder)
  397.         self.curFrameNum = 0
  398.        
  399.         #direction is the direction the frame is facing
  400.         self.direction = V.norm(direction)
  401.         #facing is the direction the frame is currently facing
  402.         self.facing = self.direction
  403.         self.curRotation = 0
  404.        
  405.        
  406.         #frame info
  407.         self.curFrame = self.animList[self.curFrameNum].copy()
  408.         self.drawable = self.curFrame
  409.         self.oldCenter = self.curFrame.copy().get_rect().center
  410.        
  411.         #movement info
  412.         self.moving = moving
  413.         self.speed = 5
  414.        
  415.         #vision
  416.         self.visionRadius = 90
  417.         self.visionDist = 200
  418.        
  419.         #components
  420.         self.shooter = shooter        
  421.         if self.shooter:
  422.             self.shooter.owner = self
  423.            
  424.        
  425.         self.ai = ai
  426.         if self.ai: self.ai.owner = self
  427.        
  428.         self.stats = Stats(self)
  429.         #owner is passed in to construct
  430.         #self.stats.owner = self
  431.        
  432.         #print self.rect.size, 'init size'
  433.        
  434.     def die(self):
  435.         '''remove from alive lists and record frame died on'''
  436.         MEN.remove(self)
  437.         if self.ai:
  438.             self.ai.remove()
  439.        
  440.         print self.name, ' died... RIP'
  441.        
  442.         self.rect = pygame.rect.Rect(0, 0, 0, 0)
  443.        
  444.     def __repr__(self):
  445.         if self.name:
  446.            
  447.             return self.name
  448.         else:
  449.             return self
  450.      
  451.     def initLists(self):
  452.         ''' lists and stats of everything relevant to this instance'''
  453.         ##considering making a stats class to append here though, might make
  454.         ###life a bit easier
  455.         ALLTHINGS.add(self)
  456.         MEN.append(self)
  457.        
  458.         self.timesHit = 0
  459.        
  460.        
  461.     def gotHit(self,damage):
  462.         '''Stuff that happens upon getting hit'''
  463.         #record the hit
  464.         self.timesHit += 1
  465.        
  466.         #take damage
  467.         self.shooter.takeDamage(damage)
  468.        
  469.        
  470.        
  471.         #try :
  472.             #self.curFrameNum +=1
  473.             #self.curFrame = self.animList[self.curFrameNum].copy()
  474.             #self.doRotate(self.curRotation)
  475.         #except IndexError:
  476.             #self.curFrameNum = 0
  477.             #self.curFrame = self.animList[self.curFrameNum].copy()
  478.             #self.doRotate(self.curRotation)
  479.            
  480.     def check(self):
  481.         '''Check to see if level up or dead'''
  482.         if self.shooter.curHp <= 0:
  483.             self.die()
  484.        
  485.        
  486.     def scaleImage(self,imagepath):
  487.         #loads image, scales it, returns scaledimage.
  488.         image = pygame.image.load(imagepath).convert()
  489.         image.set_colorkey(WHITE)
  490.         scaled = pygame.transform.scale(image, (32,32))
  491.        
  492.         imagename = imagepath.split('/')[-1]
  493.         #print '{0}\'s scaled width: {1}'.format(imagename,scaled.get_width())
  494.         return scaled
  495.        
  496.     def animLister(self,folder):
  497.         '''must have jpgs named 1 thru 100
  498.        and this func will go through them in that
  499.        order and add them to a list to animate'''
  500.        
  501.        
  502.         #func to list all jpgs in folder
  503.         #then count em all for len later
  504.         animationList = []
  505.         for filepath in glob.glob(folder+'/*.png'):
  506.             #print filepath
  507.             frame  = self.scaleImage(filepath)
  508.             animationList.append(frame)
  509.              
  510.         return animationList
  511.    
  512.     def drawFrame(self):
  513.        
  514.         #changed from curFrame to drawable
  515.         #and save the rect on 'screen'
  516.         self.rect = screen.blit(self.drawable, (self.x,self.y))
  517.  
  518.        
  519.     def changeDir(self,direction, moving = True):
  520.         # - check pos
  521.         # - rotate part of the way
  522.         # - go
  523.        
  524.         #trying to do it with vectors, if dot is positive its a right turn
  525.         # if negative, it's a left turn.
  526.         direction = V.norm(direction)
  527.         #print 'new direction: ', direction
  528.         self.direction = direction
  529.         self.move()
  530.         #self.drawFrame()
  531.        
  532.     def go(self,move):
  533.         self.moving = move
  534.        
  535.     def move(self):
  536.         self.x, self.y = self.getPos()
  537.         if self.moving:
  538.             #if facing isn't direction | but that that's good enough
  539.             # need to see if either one is roughly that same angle.
  540.             #print self.name,'.facing == direction? ', \
  541.                             #self.facing != self.direction
  542.             #if self.facing != self.direction:
  543.             self.rotate()
  544.            
  545.             #if x or y is out of boundaries do nothing
  546.             if self.x + self.direction[0] * self.speed > WIDTH - self.rect.w or\
  547.                self.y + self.direction[1] * self.speed > HEIGHT - self.rect.h or\
  548.                self.x + self.direction[0] * self.speed < 0 or\
  549.                self.y + self.direction[1] * self.speed < 0  :
  550.                
  551.                 pass
  552.                 #print 'not inside screen'
  553.                
  554.             #else do move
  555.             else:
  556.                
  557.                 self.x += self.direction[0] * self.speed
  558.                 self.y += self.direction[1] * self.speed
  559.                
  560.                 #print 'x', self.x, '<', WIDTH
  561.                 #print 'y', self.y, '<', HEIGHT
  562.                
  563.                 self.pos= (self.x,self.y)
  564.            
  565.     def rotateVector(self,vector,angle):
  566.         #45 degrees = pi/4 radians
  567.         x,y = vector
  568.         rad = V.degToRad(angle)
  569.         xNew = round((math.cos(rad) * x - math.sin(rad) * y),2)
  570.         yNew = round((math.sin(rad) * x + math.cos(rad) * y),2)
  571.         new_vector = xNew,yNew
  572.         #print 'Old vector: ', vector
  573.         #print 'Rotated Vec:', new_vector
  574.        
  575.         return new_vector
  576.  
  577.     def scale(self,vector, distance):
  578.         '''move vector to distance away'''
  579.         x,y = vector
  580.         x *= distance
  581.         y *= distance
  582.         #print 'Scaled Vec: ', (x,y)
  583.         return (x,y)
  584.  
  585.            
  586.     def roundTo(self,x,rounder):
  587.         x = x/rounder
  588.         x = round(x)
  589.         x = x*rounder
  590.         #print(x)
  591.         return x
  592.    
  593.     def rotate(self):  
  594.         '''rotates facing to match direction'''
  595.        
  596.         frame = self.curFrame
  597.         self.oldCenter = frame.get_rect().center
  598.        
  599.         #find the angle between default (RIGHT) and current direction
  600.         # which is the amount the drawable should be rotated currently
  601.         angle = self.calcAngle(RIGHT,self.direction)
  602.         #round the angle to integer if float
  603.         angle = int(round(angle,0))
  604.         #print 'current angle for {0}: '.format(self.name), angle
  605.  
  606.         #make sure it's not over 360, in order to avoid extra rotation.
  607.         self.curRotation = angle
  608.         while self.curRotation > 359:
  609.             self.curRotation -= 360
  610.             #print self.curRotation
  611.            
  612.         #drawing will be rounded
  613.         self.curRotation= self.roundTo(self.curRotation,2)
  614.  
  615.        
  616.         #self.drawable = pygame.transform.rotate(frame, self.curRotation)
  617.         self.doRotate(self.curRotation)
  618.         #self.drawable.get_rect().center = oldCenter
  619.         #print f, d
  620.         #self.facing = self.direction
  621.  
  622.  
  623.     def doRotate(self,angle):
  624.         self.drawable = pygame.transform.rotate(self.curFrame.copy(), angle)
  625.         self.drawable.get_rect().center = self.oldCenter
  626.         #print self.facing, self.direction
  627.         self.facing = self.direction
  628.        
  629.     def calcAngle(self,p1, p2):
  630.         '''return in angle in deg'''
  631.         a1 = math.atan2(p1[1], p1[0])
  632.         a2 = math.atan2(p2[1], p2[0])
  633.         angle = (a1 - a2) % (2 * math.pi)
  634.         return V.radToDeg(angle)
  635.    
  636.        
  637.    
  638.    
  639.     def getPos(self):
  640.         self.pos = (self.x,self.y)
  641.         #print "pos = ", self.pos
  642.         return self.pos
  643.        
  644. class ai:
  645.     def __init__(self, int=DUMB):
  646.         '''judges when to fire and when to move'''
  647.        
  648.         #how smart the AI is out of 3: DUMB, AVG, SMART
  649.         self.int = int
  650.        
  651.         self.wantToMove = False
  652.        
  653.         self.target = circle
  654.        
  655.         ALLTHINGS.add(self)
  656.         AIs.append(self)
  657.        
  658.     def __repr__(self):
  659.         if self.name:
  660.             return self.name
  661.        
  662.         else:
  663.             return self
  664.        
  665.     def canSee(self,target):
  666.         #selfPos:
  667.         sP = self.owner.getPos()
  668.         #D in wolfire
  669.         D = self.owner.direction
  670.         #enemyPos
  671.         eP = self.target.getPos()  
  672.         #V in wolfire
  673.         v = V.subtract(sP,eP)
  674.        
  675.         Dd = V.norm(D)
  676.         Vd = V.norm(v)
  677.        
  678.         #angle between Dd and Vd
  679.        
  680.         #first and seconds values of each multi'd
  681.         ZERO = Dd[0]*Vd[0]
  682.         ONE = Dd[1]*Vd[1]
  683.         #then summed
  684.         SUM = ZERO + ONE
  685.         if 2 > SUM < 1.0 :
  686.             SUM = 1.0
  687.            
  688.         #passed to acosine
  689.         theta = math.acos(SUM)
  690.         theta = V.radToDeg(theta)
  691.        
  692.        
  693.         #so if Theta is < 1/2vision, can see.
  694.         if theta <= self.owner.visionRadius/2 and V.distance(sP, eP) < 200:
  695.             #print 'can see!'
  696.             return True
  697.        
  698.         else :
  699.             #print 'can\'t see'
  700.             return False
  701.        
  702.        
  703.     def drawVision(self):
  704.         '''draw two lines on edges of vision'''
  705.         #print 'woulda drawVision'
  706.         #print self.owner.direction
  707.        
  708.         #take pos and center added together for center pos on screen
  709.         pos = self.owner.getPos()
  710.         pos2 = self.owner.curFrame.get_rect().center
  711.         pos = tuple([a+b for a,b in zip(pos,pos2)])
  712.        
  713.         dist = V.distance(pos,self.target.getPos())
  714.        
  715.         #if dist is further then visionDist, set dist to
  716.         # that so the line doesn't keep drawing forever,
  717.         # in order to better define each persons vision.
  718.         if dist > self.owner.visionDist:
  719.                
  720.             dist = self.owner.visionDist
  721.        
  722.         #angle of left half of vision
  723.         leftLine = self.owner.rotateVector(self.owner.direction,
  724.                                            -self.owner.visionRadius/2)
  725.         #take the vector and scale it 50x
  726.         leftLine = self.owner.scale(leftLine,dist)
  727.        
  728.         rightLine = self.owner.rotateVector(self.owner.direction,
  729.                                            self.owner.visionRadius/2)
  730.         rightLine = self.owner.scale(rightLine,dist)
  731.  
  732.        
  733.         #add pos to leftLine and rightLine so that vectors will be
  734.         # relevant rather than < 1.
  735.         leftLine= tuple([a+b for a,b in zip(leftLine,pos)])
  736.         rightLine= tuple([a+b for a,b in zip(rightLine,pos)])
  737.        
  738.         pygame.draw.line(screen, BLUE, pos, leftLine,2)
  739.         pygame.draw.line(screen, BLUE, pos, rightLine, 2)
  740.        
  741.         #else:
  742.             #pass  
  743.          
  744.     def check(self):  
  745.         #every second of gametime:
  746.         # move or shoot
  747.         if frame_count % FRAMERATE == 0:
  748.             #if target is in view  stop and fire:
  749.             # else move for 1/2s then rotate for 1/2s
  750.             if self.canSee(self.target):
  751.                 self.wantToMove = False
  752.                 self.owner.shooter.fire(self.owner.direction,'bullet')
  753.                  
  754.             elif not self.canSee(self.target):  
  755.                 self.wantToMove = True
  756.         #remainder of eq means less than half a second has passed since last 1s
  757.         elif frame_count % FRAMERATE < FRAMERATE/2 and self.wantToMove:
  758.             self.owner.moving = True
  759.            
  760.         elif frame_count % FRAMERATE >= FRAMERATE/2 and self.wantToMove \
  761.              and not self.canSee(self.target):
  762.             #stop moving in order to rotate
  763.             self.owner.moving = False
  764.  
  765.             #figure out the new direction vector to face in
  766.             dir = self.owner.rotateVector(self.owner.direction, 15)
  767.            
  768.             #set it
  769.             self.owner.direction = V.norm(dir)
  770.             self.drawVision()
  771.             #if self can't see target, rotate, else draw a cone
  772.             if not self.canSee(self.target):
  773.                 #print 'can\'t see'
  774.                 self.owner.rotate()
  775.            
  776.     def remove(self):
  777.        
  778.             AIs.remove(self)
  779.        
  780.    
  781.    
  782.        
  783.        
  784. class shooter:
  785.     def __init__(self, level, maxHp):
  786.         '''handles damage and exp level'''
  787.        
  788.         self.level = level
  789.         self.maxHp = maxHp
  790.         self.curHp = maxHp
  791.        
  792.         self.initLists()
  793.        
  794.     def takeDamage(self, damage):
  795.         ''' sub damage from curHP'''
  796.         self.curHp -= damage
  797.        
  798.        
  799.     def initLists(self,):
  800.         ''' init all the lists and stuff relevant'''
  801.        
  802.         self.timesFired = 0
  803.        
  804.        
  805.     def getTarget(self,):
  806.         '''figure out who the target is'''
  807.         if self.owner == circle:
  808.             self.target = [thing for thing in MEN]
  809.             self.target.remove(circle)
  810.         else: self.target = [circle]
  811.        
  812.     #def __repr__(self):
  813.         #if self.owner.name:
  814.            
  815.             #return self.owner.name, '\'s shooter componet'
  816.         #else:
  817.             #return self
  818.     def  fire(self, direction, variety):
  819.         #spawn and fire projectile in direction
  820.         bull= projectile(self.owner,self.owner.direction, self.owner.shooter.target, 'bullet')
  821.         if not type(self.timesFired ) is int:
  822.             self.timesFired = int(self.timesFired)
  823.         self.timesFired += 1
  824.         #print len(BULLETS)
  825.        
  826.          
  827. #class basicEnemy():
  828.     #def __init__(self, intLvl=1):
  829.         #self.intLvl = intLvl
  830.  
  831. class projectile():
  832.     def __init__(self, source, direction, target, variety):
  833.         '''is any projectile fired'''
  834.         ALLTHINGS.add(self)
  835.        
  836.         #source of proj. likely who shot self
  837.         self.source = source
  838.         #rect of
  839.         self.curFrame = source.curFrame
  840.        
  841.         self.direction = direction
  842.        
  843.         #target is a list
  844.         self.target = target
  845.        
  846.         #whether or not the projectile is alive
  847.         self.active = True
  848.        
  849.         #assing to proper group
  850.         self.variety = variety
  851.        
  852.         if self.variety == 'bullet':
  853.             self.speed = 10
  854.             self.groupList = BULLETS
  855.             self.colors = [RED, BLACK]
  856.            
  857.         elif self.variety == 'shrapnel':
  858.             self.speed = 3
  859.             self.groupList = SHRAPNEL
  860.             self.colors = [BLUE, GREEN]
  861.         self.groupList.append(self)
  862.        
  863.         self.color = BLACK
  864.        
  865.         #get rect of curFrame's center x y
  866.         #self.x,self.y = self.source.getPos()
  867.        
  868.         self.height= 4
  869.        
  870.         #actually fire the projective
  871.         self.fire()
  872.        
  873.  
  874.         #name it based on number of game objects
  875.         self.name()
  876.        
  877.         #init lists
  878.         self.initLists()
  879.        
  880.     def update(self):
  881.         #update color and height
  882.         self.changeColor()
  883.         self.changeSize()
  884.        
  885.         #move and draw
  886.         self.move()
  887.         self.draw()
  888.        
  889.         #make sure targets in self.target is still alive
  890.         #
  891.         # if MEN has changed from the original copy
  892.         if self.oldMEN != MEN:
  893.             print 'MEN is not the same'
  894.             #go through and find the MEN that aren't there
  895.             for object in self.oldMEN:
  896.                 print object.name, 'might get remove'
  897.                 #and remove them from target
  898.                 if object not in MEN:
  899.                     self.target.remove(object)
  900.                
  901.     def changeColor(self):
  902.         #print self.travelled
  903.         if self.travelled % 2 == 0:
  904.             self.color = self.colors[0]
  905.         else : self.color = self.colors[1]
  906.        
  907.     def changeSize(self):
  908.         if self.travelled % 3 == 0:
  909.             self.height *= 2
  910.            
  911.         elif self.travelled % 10 == 0:
  912.             #self.height *= 3
  913.            
  914.             #see Cross product from wolfire blog, reversing x and y
  915.             # with x being made negative and y negative for right turn
  916.             left = -self.direction[1], self.direction[0]
  917.             right = self.direction[1], -self.direction[0]
  918.            
  919.  
  920.            
  921.            
  922.             #draw them
  923.             projectile(self,left,[circle],'shrapnel')
  924.             projectile(self,right,[circle],'shrapnel')
  925.             #print 'broke up'
  926.            
  927.            
  928.         else: self.height = 4
  929.     def initLists(self):
  930.         self.travelled = 0
  931.        
  932.         self.oldMEN = MEN
  933.     def name(self):
  934.         self.name = '{0} No. {1}'.format(self.variety,len(ALLTHINGS))
  935.        
  936.     def fire(self):
  937.         #get rect of curFrame's center x
  938.         if self.variety == 'bullet':
  939.             self.x,self.y = self.curFrame.get_rect().midright
  940.             #spawn at first position out from source
  941.             # add the center of the rect to the center of
  942.             # shooter then move bit a bit
  943.             self.x = self.x + self.source.x #+ self.direction[0]
  944.             self.y = self.y + self.source.y #+ self.direction[1]
  945.         elif self.variety == 'shrapnel':
  946.             self.x,self.y = self.source.getPos()
  947.             #spawn at first position out from source
  948.             # add the center of the rect to the center of
  949.             # shooter then move bit a bit
  950.             self.x = self.x + self.direction[0]
  951.             self.y = self.y + self.direction[1]
  952.         self.draw()
  953.        
  954.     def move(self):
  955.         self.x += self.direction[0] * self.speed
  956.         self.y += self.direction[1] * self.speed
  957.        
  958.         #if self still in play
  959.         if self.active:
  960.             self.travelled +=1
  961.            
  962.             #or if hit another
  963.             # test all rects
  964.             hit_something = False
  965.            
  966.            
  967.             #for t in self.target:
  968.                 #if self.size.collidelist(self.target):
  969.                     #hit_something = t
  970.                     #break
  971.             #print self.target[0].rect.size
  972.             hit_something = self.size.collidelist(self.target)
  973.             #print self.target[hit_something]
  974.                
  975.                
  976.             #remove self if off screen
  977.             if self.x > WIDTH + 1 or self.y > HEIGHT \
  978.                or 0 > self.x or 0 > self.y:
  979.                 self.remove()
  980.                 #print 'removed: ', self.name
  981.                
  982.      
  983.             elif hit_something != -1:
  984.                 print 'BULLET HIT!'
  985.                 self.target[hit_something].gotHit(5)
  986.                 self.remove()
  987.                
  988.             #add 1 movement to count. change color accordingly
  989.            
  990.             elif self.variety == 'shrapnel':
  991.                
  992.                 if self.travelled > 3:
  993.                     if self in SHRAPNEL:
  994.                         self.remove()
  995.                     else : print 'shrapnel not in SHRAPNEL'
  996.     def checkSize(self,):
  997.         self.size = pygame.rect.Rect(self.x - (self.height /2),
  998.                                      self.y - (self.height /2),
  999.                                      self.height,
  1000.                                      self.height)
  1001.         #self.size.center = self.source.curFrame.get_rect().center
  1002.         #self.size.center = self.size.center + (self.x,self.y)
  1003.        
  1004.     def getPos(self):
  1005.         self.pos = (self.x,self.y)
  1006.         #print "pos = ", self.pos
  1007.         return self.pos
  1008.     def draw(self):  
  1009.         self.checkSize()
  1010.         ##draw a rect
  1011.         #pygame.draw.rect(screen, self.color ,
  1012.                          #self.size)
  1013.                          
  1014.         ##draw a circle
  1015.         pygame.draw.circle(screen, self.color ,
  1016.                          (self.size.x,self.size.y), 2)
  1017.    
  1018.     def hit(self):
  1019.         '''remove self from active list -> dead list'''
  1020.         #do damage to target,
  1021.         #animate
  1022.         self.remove()
  1023.        
  1024.     def remove(self):
  1025.         '''remove from pertinent lists and add to stats'''
  1026.         #print 'Gah, I\'m done!, signed, ', self.name, self.variety
  1027.         STATS.append(self)
  1028.         if self.variety == 'bullet':
  1029.             BULLETS.remove(self)
  1030.         elif self.variety == 'shrapnel':
  1031.             SHRAPNEL.remove(self)
  1032.            
  1033.         #kill the self in class
  1034.         self.active = False
  1035.  
  1036.        
  1037.  
  1038.  
  1039.  
  1040.  
  1041. if __name__ == '__main__':
  1042.    
  1043.     # ########INIT######### #
  1044.     pygame.init()
  1045.     pygame.display.set_caption('Line Moving App')
  1046.     seticon('bricks.ico')    
  1047.    
  1048.     screen = pygame.display.set_mode((WIDTH, HEIGHT))
  1049.     #screen.fill(BLUE)
  1050.     screen.set_colorkey((255,255,254))
  1051.    
  1052.     #background = pygame.Surface(screen.get_size())
  1053.     #background = background.convert()
  1054.     #background.fill(WHITE)
  1055.    
  1056.     clock = pygame.time.Clock()
  1057.    
  1058.     pygame.display.flip()
  1059.    
  1060.     basicFont = pygame.font.SysFont(None, 48)  
  1061.    
  1062.     V = Vector()
  1063.    
  1064.     spawner = Spawner()
  1065.    
  1066.     # ############### #
  1067.    
  1068.    
  1069.        
  1070.     pathname = os.path.abspath(os.path.curdir)
  1071.     pathname += '/art/man/'
  1072.     #print pathname
  1073.     shot = shooter(1,100)
  1074.     circle = anything((400,200),'Josh', pathname,shooter=shot)
  1075.     circle.shooter.getTarget()
  1076.     #shot = shooter(1, 100)
  1077.     #AI = ai(DUMB)
  1078.     #bob = anything((350,200),'Bob',pathname, shooter=shot, ai= AI)
  1079.     #bob = spawner.spawn('mob')
  1080.    
  1081.    
  1082.     circle.shooter.getTarget()
  1083.     #bob.shooter.getTarget()
  1084.    
  1085.     # window for stats
  1086.     '''reference new module for stats here'''
  1087.     #window = statsWin.start()
  1088.  
  1089.     running = 1      
  1090.    
  1091.     frame_count = 0
  1092.     frame_rate = 0
  1093.     t0 = time.clock()
  1094.     while running:
  1095.         #window()
  1096.        
  1097.         screen.fill(WHITE)
  1098.         #bob.ai.drawVision()
  1099.         #check for movements, and draw after
  1100.         for object in MEN:
  1101.             object.move()
  1102.             #object.check()
  1103.            
  1104.             #print object.name, 'is drawn', frame_count
  1105.             object.drawFrame()
  1106.              
  1107.        
  1108.            
  1109.         for object in BULLETS:
  1110.             object.update()
  1111.            
  1112.         for object in SHRAPNEL:
  1113.             object.update()
  1114.            
  1115.         #AIs think
  1116.         for object in AIs:
  1117.             object.check()
  1118.             object.drawVision()
  1119.         frame_count += 1
  1120.         if frame_count % 15 == 0:
  1121.             t1 = time.clock()
  1122.             frame_rate = 15 / (t1-t0)
  1123.             t0 = t1
  1124.        
  1125.         for event in pygame.event.get():
  1126.            
  1127.             if event.type == pygame.QUIT:
  1128.                 running = 0
  1129.                
  1130.             elif event.type == pygame.KEYDOWN or event.type== pygame.KEYUP:
  1131.                 key_event(event)
  1132.            
  1133.            
  1134.             elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
  1135.                 #print event.button
  1136.                 (circle.x,circle.y) = event.pos
  1137.                 circle.go(False)
  1138.                
  1139.             elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 4:
  1140.                 bob.x, bob.y = event.pos
  1141.                
  1142.                
  1143.             elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
  1144.                 print event.button
  1145.                 print 'mouse pressed'
  1146.                 if mousePressed: circle.go(False)
  1147.                 #take pos as vector:
  1148.                 mousePos = (x,y) = event.pos            
  1149.                 circlePos = (circle.x,circle.y)
  1150.                 print mousePos, circlePos
  1151.                
  1152.                 #in relation to circle, directions the vector away from them.
  1153.                
  1154.                 #subtract current selfx from x and same for selfy and y
  1155.                 direction=  tuple([a - b for a, b in zip(mousePos, circlePos)])
  1156.                 print direction
  1157.                 home = [a /200 for a in direction]
  1158.                 print home
  1159.                
  1160.                 #normalize home
  1161.                 normed = V.norm(home)
  1162.                
  1163.                 #new direction is normed
  1164.                
  1165.                 circle.changeDir(normed)
  1166.                 circle.go(True)
  1167.                 mousePressed = True
  1168.                
  1169.                
  1170.                            
  1171.                    
  1172.                    
  1173.        
  1174.         the_text = basicFont.render('Frame = {0},  rate = {1:.2f} fps'
  1175.                           .format(frame_count, frame_rate), True, (0,0,0))
  1176.         screen.blit(the_text, (10, 10))
  1177.        
  1178.         for object in MEN:
  1179.             object.check()
  1180.                
  1181.         pygame.display.flip()
  1182.        
  1183.        
  1184.         #tkinter stuff below
  1185.        
  1186.        
  1187.        
  1188.        
  1189.         # #####
  1190.         clock.tick(FRAMERATE)
  1191.  
Advertisement
Add Comment
Please, Sign In to add comment