Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame as pygame
- #from pygame.locals import *
- import random
- import os.path
- import glob
- import math
- import time
- import Tkinter as tk
- #import statsWin
- import GUI2
- #import thread
- #import threading
- import multiprocessing as multi
- #constants
- WIDTH = 800
- HEIGHT = 600
- FRAMERATE = 30
- #directions
- UP = (0, -1)
- DOWN = (0, 1)
- LEFT = (-1, 0)
- RIGHT = (1, 0)
- TLEFT = (-1,-1)
- TRIGHT = (1,-1)
- BLEFT = (-1,1)
- BRIGHT = (1,1)
- DIRECTIONS = [UP,DOWN,LEFT,RIGHT,TLEFT,TRIGHT,BLEFT,BRIGHT]
- STOP = (0,0)
- #colors
- BLACK = (0,0,0)
- WHITE = (255,255,255)
- RED = (255,0,0)
- GREEN = (0,255,0)
- BLUE = (0,0,255)
- #keyboard directions and their equivalents
- keyDirs = {
- pygame.K_DOWN : DOWN,
- pygame.K_UP : UP,
- pygame.K_LEFT: LEFT,
- pygame.K_RIGHT: RIGHT,
- pygame.K_s : DOWN,
- pygame.K_w : UP,
- pygame.K_a: LEFT,
- pygame.K_d: RIGHT,
- pygame.K_KP2: DOWN,
- pygame.K_KP8: UP,
- pygame.K_KP4: LEFT,
- pygame.K_KP6: RIGHT,
- pygame.K_KP7: TLEFT,
- pygame.K_KP9: TRIGHT,
- pygame.K_KP1: BLEFT,
- pygame.K_KP3: BRIGHT,
- }
- #rotations
- leftTurns= {
- UP:LEFT,
- LEFT:DOWN,
- DOWN:RIGHT,
- RIGHT:UP}
- rightTurns = {
- UP:RIGHT,
- RIGHT:DOWN,
- DOWN:LEFT,
- LEFT:UP}
- acrossTurns = {UP:DOWN,
- DOWN:UP,
- LEFT:RIGHT,
- RIGHT:LEFT}
- #ai levels
- DUMB = 0
- AVG = 1
- SMART = 2
- #-#lists#-#
- ALLTHINGS = set()
- #all live chars
- MEN = []
- # ...and their AIs
- AIs = []
- #all live bullets
- BULLETS = []
- SHRAPNEL = []
- #all dead things
- STATS = []
- mousePressed = False
- def isKey(event, k):
- '''short for event.key == pygame.K-KEY'''
- #getattr wo
- methodToCall = getattr(pygame, 'K_{0}'.format(k))
- if event.key == methodToCall: return True
- #set game icon
- def seticon(iconname):
- """
- give an iconname, a bitmap sized 32x32 pixels, black (0,0,0) will be alpha channel
- the windowicon will be set to the bitmap, but the black pixels will be full alpha channel
- can only be called once after pygame.init() and before somewindow = pygame.display.set_mode()
- from:http://www.pygame.org/docs/ref/display.html#pygame.display.set_icon comments
- """
- #create a surface for icon
- icon=pygame.Surface((256,256))
- icon.set_colorkey((255,255,255))#and call that color transparent
- rawicon= pygame.image.load(iconname)#must be 32x32, black is transparent
- for i in range(0,256):
- for j in range(0,256):
- icon.set_at((i,j), rawicon.get_at((i,j)))
- pygame.display.set_icon(icon)#set wind
- class Spawner():
- '''used to spawn entities'''
- def __init__(self, *args):
- pass
- def spawn(self, subject, *args):
- '''spawn an entity '''
- if subject == 'mob':
- print 'mob made'
- shot = shooter(1, 100)
- AI = ai(DUMB)
- W = WIDTH * random.random()
- H = HEIGHT * random.random()
- mob = anything((W, H),'Bob',pathname, shooter=shot, ai= AI)
- mob.shooter.getTarget()
- return mob
- else :
- print 'spawn nothing'
- class Stats():
- '''A class for managing statistics and information
- about any given instance, acting asadvanced dictionary use'''
- def __init__(self, owner):
- '''init it all'''
- self.owner = owner
- #get the stats
- self.getBasicStats()
- self.getShooterStats()
- def getBasicStats(self):
- '''gets all the basic stats for a creature such as name
- and position upon creation'''
- self.basicStats = {
- 'Name': self.owner.name,
- 'Pos': self.owner.pos,
- }
- def getShooterStats(self):
- '''get the stats from the shooter component'''
- if self.owner.shooter:
- print self.owner.name, 'is a shooter'
- self.shooterStats = {
- 'Times Fired': self.owner.shooter.timesFired,
- 'Times Hit': self.owner.timesHit,
- }
- else:
- print self.owner.name, 'isn\'t a shooter'
- def getAiStats(self):
- '''gets the stats from the AI component'''
- if self.owner.ai:
- print self.owner.name, 'is an AI'
- self.aiStats = {
- '': '',}
- else:
- print self.owner.name, 'isn\'t an AI'
- class Vector():
- def radToDeg(self, rad):
- #rad / (pi/180) = degree
- deg = rad / (3.14/180)
- return deg
- def degToRad(self, deg):
- #rad = degree * (pi/180)
- return deg * (3.14/180)
- def subtract(self, first,second):
- '''substract second from first'''
- sub = tuple([b-a for a,b, in zip(first,second)])
- return sub
- def dot(self, *parts):
- list = []
- for part in parts:
- part = V.norm(part)
- list.append(part)
- dot = (list[0][0] * list[1][0]) + (list[0][1]*list[1][1])
- print 'dot: ',dot
- return dot
- def revNorm(self, vector):
- '''reverses norm(), but doesn't'''
- x = vector[0]
- y = vector[1]
- #length
- revNormed = ((x*5),(y*5))
- return revNormed
- def norm(self, vector):
- x = vector[0]
- y = vector[1]
- #normalize a vector by dividing it by its length
- len = V.length(vector)
- try:
- normalized = ((x/len),(y/len))
- except ZeroDivisionError:
- normalized = (0,0)
- #print 'norm: ', normalized
- return normalized
- def length(self, vector):
- x = vector[0]
- y = vector[1]
- length =math.sqrt(( x**2 + y**2))
- #print 'length: ',length
- return length
- def distance(self, first, second):
- dist= tuple([b-a for a,b in zip(first,second)])
- dist = V.length(dist)
- #print 'distance: ', dist
- return dist
- #handle keys
- def key_event(event):
- ##WORKING ON THIS: TRY TO MAKE THIS A LIST INSTEAD
- ## OF ALL THE DIRECTIONS ONE AFTER ANOTHER
- if event.type == pygame.KEYUP:
- #tuple below is directions
- if event.key in keyDirs.keys():
- #for brick in bricks:
- #brick.setMove(moving=False, dir =brick.dir)
- circle.go(False)
- elif event.type == pygame.KEYDOWN:
- if event.key in keyDirs.keys():
- #print 'keys pressed'
- direction= keyDirs[event.key]
- circle.changeDir(direction)
- circle.go(True)
- elif isKey(event, 'n'):
- reload(GUI2)
- print 'reloaded module GUI'
- pass
- elif isKey(event, 'c'):
- circle.shooter.fire(circle.direction,'bullet')
- print 'FIRED {0} TIMES'.format(circle.shooter.timesFired)
- pass
- #clear screen, slopilly.
- elif isKey(event,'RETURN'):
- screen.fill((0,0,0))
- #elif isKey(event,'z'):
- #print 'circle: ',circle.getPos(), ' bob: ', bob.getPos()
- elif isKey(event,'z'):
- if hasattr(GUI2, 'root'):
- print GUI2.root.TEST
- elif isKey(event,'x'):
- '''check if circle is in bob's rect'''
- print 'RECTS for circle: ', circle.rect.x,\
- circle.rect.y,
- print 'RECTS for bob: ', bob.rect.x,\
- bob.rect.y
- if circle.rect.colliderect(bob):
- print 'COLLISION!!'
- #change animation
- elif event.key in (pygame.K_0,pygame.K_1,pygame.K_2,
- pygame.K_3,pygame.K_4,pygame.K_5,
- pygame.K_6,pygame.K_7,pygame.K_8,
- pygame.K_9):
- keys = {pygame.K_0 :9,
- pygame.K_1 :0,
- pygame.K_2 :1,
- pygame.K_3 :2,
- pygame.K_4 :3,
- pygame.K_5 :4,
- pygame.K_6 :5,
- pygame.K_7 :6,
- pygame.K_8 :7,
- pygame.K_9 :8}
- circle.curFrameNum = keys[event.key]
- circle.curFrame = circle.animList[circle.curFrameNum].copy()
- circle.direction = RIGHT
- circle.rotate()
- print 'changed frame'
- elif isKey(event,'m'):
- func = GUI2.run
- #threading module
- #thread_GUI2 = threading.Thread(group = None, target = func, name='GUI THREAD')
- #thread_GUI2.start()
- #no threading
- GUI2.run()
- #multiprocessing module
- #thread_GUI2 = multi.Process(target = func, name='GUI THREAD')
- #thread_GUI2.start()
- print 'thread ran'
- elif isKey(event, 'b'):
- spawner.spawn('mob')
- class anything:
- def __init__(self, (x,y),name, animFolder,
- direction=RIGHT, moving=False,
- shooter= None, ai = None):
- '''supposed to be the thing every class is inherited from
- but hey, here we are'''
- #create and append appropriate stats for object
- self.initLists()
- #change x and y, NEVER pos!
- self.pos = (x,y)
- self.x, self.y = self.pos
- self.name = name
- self.animList = self.animLister(animFolder)
- self.curFrameNum = 0
- #direction is the direction the frame is facing
- self.direction = V.norm(direction)
- #facing is the direction the frame is currently facing
- self.facing = self.direction
- self.curRotation = 0
- #frame info
- self.curFrame = self.animList[self.curFrameNum].copy()
- self.drawable = self.curFrame
- self.oldCenter = self.curFrame.copy().get_rect().center
- #movement info
- self.moving = moving
- self.speed = 5
- #vision
- self.visionRadius = 90
- self.visionDist = 200
- #components
- self.shooter = shooter
- if self.shooter:
- self.shooter.owner = self
- self.ai = ai
- if self.ai: self.ai.owner = self
- self.stats = Stats(self)
- #owner is passed in to construct
- #self.stats.owner = self
- #print self.rect.size, 'init size'
- def die(self):
- '''remove from alive lists and record frame died on'''
- MEN.remove(self)
- if self.ai:
- self.ai.remove()
- print self.name, ' died... RIP'
- self.rect = pygame.rect.Rect(0, 0, 0, 0)
- def __repr__(self):
- if self.name:
- return self.name
- else:
- return self
- def initLists(self):
- ''' lists and stats of everything relevant to this instance'''
- ##considering making a stats class to append here though, might make
- ###life a bit easier
- ALLTHINGS.add(self)
- MEN.append(self)
- self.timesHit = 0
- def gotHit(self,damage):
- '''Stuff that happens upon getting hit'''
- #record the hit
- self.timesHit += 1
- #take damage
- self.shooter.takeDamage(damage)
- #try :
- #self.curFrameNum +=1
- #self.curFrame = self.animList[self.curFrameNum].copy()
- #self.doRotate(self.curRotation)
- #except IndexError:
- #self.curFrameNum = 0
- #self.curFrame = self.animList[self.curFrameNum].copy()
- #self.doRotate(self.curRotation)
- def check(self):
- '''Check to see if level up or dead'''
- if self.shooter.curHp <= 0:
- self.die()
- def scaleImage(self,imagepath):
- #loads image, scales it, returns scaledimage.
- image = pygame.image.load(imagepath).convert()
- image.set_colorkey(WHITE)
- scaled = pygame.transform.scale(image, (32,32))
- imagename = imagepath.split('/')[-1]
- #print '{0}\'s scaled width: {1}'.format(imagename,scaled.get_width())
- return scaled
- def animLister(self,folder):
- '''must have jpgs named 1 thru 100
- and this func will go through them in that
- order and add them to a list to animate'''
- #func to list all jpgs in folder
- #then count em all for len later
- animationList = []
- for filepath in glob.glob(folder+'/*.png'):
- #print filepath
- frame = self.scaleImage(filepath)
- animationList.append(frame)
- return animationList
- def drawFrame(self):
- #changed from curFrame to drawable
- #and save the rect on 'screen'
- self.rect = screen.blit(self.drawable, (self.x,self.y))
- def changeDir(self,direction, moving = True):
- # - check pos
- # - rotate part of the way
- # - go
- #trying to do it with vectors, if dot is positive its a right turn
- # if negative, it's a left turn.
- direction = V.norm(direction)
- #print 'new direction: ', direction
- self.direction = direction
- self.move()
- #self.drawFrame()
- def go(self,move):
- self.moving = move
- def move(self):
- self.x, self.y = self.getPos()
- if self.moving:
- #if facing isn't direction | but that that's good enough
- # need to see if either one is roughly that same angle.
- #print self.name,'.facing == direction? ', \
- #self.facing != self.direction
- #if self.facing != self.direction:
- self.rotate()
- #if x or y is out of boundaries do nothing
- if self.x + self.direction[0] * self.speed > WIDTH - self.rect.w or\
- self.y + self.direction[1] * self.speed > HEIGHT - self.rect.h or\
- self.x + self.direction[0] * self.speed < 0 or\
- self.y + self.direction[1] * self.speed < 0 :
- pass
- #print 'not inside screen'
- #else do move
- else:
- self.x += self.direction[0] * self.speed
- self.y += self.direction[1] * self.speed
- #print 'x', self.x, '<', WIDTH
- #print 'y', self.y, '<', HEIGHT
- self.pos= (self.x,self.y)
- def rotateVector(self,vector,angle):
- #45 degrees = pi/4 radians
- x,y = vector
- rad = V.degToRad(angle)
- xNew = round((math.cos(rad) * x - math.sin(rad) * y),2)
- yNew = round((math.sin(rad) * x + math.cos(rad) * y),2)
- new_vector = xNew,yNew
- #print 'Old vector: ', vector
- #print 'Rotated Vec:', new_vector
- return new_vector
- def scale(self,vector, distance):
- '''move vector to distance away'''
- x,y = vector
- x *= distance
- y *= distance
- #print 'Scaled Vec: ', (x,y)
- return (x,y)
- def roundTo(self,x,rounder):
- x = x/rounder
- x = round(x)
- x = x*rounder
- #print(x)
- return x
- def rotate(self):
- '''rotates facing to match direction'''
- frame = self.curFrame
- self.oldCenter = frame.get_rect().center
- #find the angle between default (RIGHT) and current direction
- # which is the amount the drawable should be rotated currently
- angle = self.calcAngle(RIGHT,self.direction)
- #round the angle to integer if float
- angle = int(round(angle,0))
- #print 'current angle for {0}: '.format(self.name), angle
- #make sure it's not over 360, in order to avoid extra rotation.
- self.curRotation = angle
- while self.curRotation > 359:
- self.curRotation -= 360
- #print self.curRotation
- #drawing will be rounded
- self.curRotation= self.roundTo(self.curRotation,2)
- #self.drawable = pygame.transform.rotate(frame, self.curRotation)
- self.doRotate(self.curRotation)
- #self.drawable.get_rect().center = oldCenter
- #print f, d
- #self.facing = self.direction
- def doRotate(self,angle):
- self.drawable = pygame.transform.rotate(self.curFrame.copy(), angle)
- self.drawable.get_rect().center = self.oldCenter
- #print self.facing, self.direction
- self.facing = self.direction
- def calcAngle(self,p1, p2):
- '''return in angle in deg'''
- a1 = math.atan2(p1[1], p1[0])
- a2 = math.atan2(p2[1], p2[0])
- angle = (a1 - a2) % (2 * math.pi)
- return V.radToDeg(angle)
- def getPos(self):
- self.pos = (self.x,self.y)
- #print "pos = ", self.pos
- return self.pos
- class ai:
- def __init__(self, int=DUMB):
- '''judges when to fire and when to move'''
- #how smart the AI is out of 3: DUMB, AVG, SMART
- self.int = int
- self.wantToMove = False
- self.target = circle
- ALLTHINGS.add(self)
- AIs.append(self)
- def __repr__(self):
- if self.name:
- return self.name
- else:
- return self
- def canSee(self,target):
- #selfPos:
- sP = self.owner.getPos()
- #D in wolfire
- D = self.owner.direction
- #enemyPos
- eP = self.target.getPos()
- #V in wolfire
- v = V.subtract(sP,eP)
- Dd = V.norm(D)
- Vd = V.norm(v)
- #angle between Dd and Vd
- #first and seconds values of each multi'd
- ZERO = Dd[0]*Vd[0]
- ONE = Dd[1]*Vd[1]
- #then summed
- SUM = ZERO + ONE
- if 2 > SUM < 1.0 :
- SUM = 1.0
- #passed to acosine
- theta = math.acos(SUM)
- theta = V.radToDeg(theta)
- #so if Theta is < 1/2vision, can see.
- if theta <= self.owner.visionRadius/2 and V.distance(sP, eP) < 200:
- #print 'can see!'
- return True
- else :
- #print 'can\'t see'
- return False
- def drawVision(self):
- '''draw two lines on edges of vision'''
- #print 'woulda drawVision'
- #print self.owner.direction
- #take pos and center added together for center pos on screen
- pos = self.owner.getPos()
- pos2 = self.owner.curFrame.get_rect().center
- pos = tuple([a+b for a,b in zip(pos,pos2)])
- dist = V.distance(pos,self.target.getPos())
- #if dist is further then visionDist, set dist to
- # that so the line doesn't keep drawing forever,
- # in order to better define each persons vision.
- if dist > self.owner.visionDist:
- dist = self.owner.visionDist
- #angle of left half of vision
- leftLine = self.owner.rotateVector(self.owner.direction,
- -self.owner.visionRadius/2)
- #take the vector and scale it 50x
- leftLine = self.owner.scale(leftLine,dist)
- rightLine = self.owner.rotateVector(self.owner.direction,
- self.owner.visionRadius/2)
- rightLine = self.owner.scale(rightLine,dist)
- #add pos to leftLine and rightLine so that vectors will be
- # relevant rather than < 1.
- leftLine= tuple([a+b for a,b in zip(leftLine,pos)])
- rightLine= tuple([a+b for a,b in zip(rightLine,pos)])
- pygame.draw.line(screen, BLUE, pos, leftLine,2)
- pygame.draw.line(screen, BLUE, pos, rightLine, 2)
- #else:
- #pass
- def check(self):
- #every second of gametime:
- # move or shoot
- if frame_count % FRAMERATE == 0:
- #if target is in view stop and fire:
- # else move for 1/2s then rotate for 1/2s
- if self.canSee(self.target):
- self.wantToMove = False
- self.owner.shooter.fire(self.owner.direction,'bullet')
- elif not self.canSee(self.target):
- self.wantToMove = True
- #remainder of eq means less than half a second has passed since last 1s
- elif frame_count % FRAMERATE < FRAMERATE/2 and self.wantToMove:
- self.owner.moving = True
- elif frame_count % FRAMERATE >= FRAMERATE/2 and self.wantToMove \
- and not self.canSee(self.target):
- #stop moving in order to rotate
- self.owner.moving = False
- #figure out the new direction vector to face in
- dir = self.owner.rotateVector(self.owner.direction, 15)
- #set it
- self.owner.direction = V.norm(dir)
- self.drawVision()
- #if self can't see target, rotate, else draw a cone
- if not self.canSee(self.target):
- #print 'can\'t see'
- self.owner.rotate()
- def remove(self):
- AIs.remove(self)
- class shooter:
- def __init__(self, level, maxHp):
- '''handles damage and exp level'''
- self.level = level
- self.maxHp = maxHp
- self.curHp = maxHp
- self.initLists()
- def takeDamage(self, damage):
- ''' sub damage from curHP'''
- self.curHp -= damage
- def initLists(self,):
- ''' init all the lists and stuff relevant'''
- self.timesFired = 0
- def getTarget(self,):
- '''figure out who the target is'''
- if self.owner == circle:
- self.target = [thing for thing in MEN]
- self.target.remove(circle)
- else: self.target = [circle]
- #def __repr__(self):
- #if self.owner.name:
- #return self.owner.name, '\'s shooter componet'
- #else:
- #return self
- def fire(self, direction, variety):
- #spawn and fire projectile in direction
- bull= projectile(self.owner,self.owner.direction, self.owner.shooter.target, 'bullet')
- if not type(self.timesFired ) is int:
- self.timesFired = int(self.timesFired)
- self.timesFired += 1
- #print len(BULLETS)
- #class basicEnemy():
- #def __init__(self, intLvl=1):
- #self.intLvl = intLvl
- class projectile():
- def __init__(self, source, direction, target, variety):
- '''is any projectile fired'''
- ALLTHINGS.add(self)
- #source of proj. likely who shot self
- self.source = source
- #rect of
- self.curFrame = source.curFrame
- self.direction = direction
- #target is a list
- self.target = target
- #whether or not the projectile is alive
- self.active = True
- #assing to proper group
- self.variety = variety
- if self.variety == 'bullet':
- self.speed = 10
- self.groupList = BULLETS
- self.colors = [RED, BLACK]
- elif self.variety == 'shrapnel':
- self.speed = 3
- self.groupList = SHRAPNEL
- self.colors = [BLUE, GREEN]
- self.groupList.append(self)
- self.color = BLACK
- #get rect of curFrame's center x y
- #self.x,self.y = self.source.getPos()
- self.height= 4
- #actually fire the projective
- self.fire()
- #name it based on number of game objects
- self.name()
- #init lists
- self.initLists()
- def update(self):
- #update color and height
- self.changeColor()
- self.changeSize()
- #move and draw
- self.move()
- self.draw()
- #make sure targets in self.target is still alive
- #
- # if MEN has changed from the original copy
- if self.oldMEN != MEN:
- print 'MEN is not the same'
- #go through and find the MEN that aren't there
- for object in self.oldMEN:
- print object.name, 'might get remove'
- #and remove them from target
- if object not in MEN:
- self.target.remove(object)
- def changeColor(self):
- #print self.travelled
- if self.travelled % 2 == 0:
- self.color = self.colors[0]
- else : self.color = self.colors[1]
- def changeSize(self):
- if self.travelled % 3 == 0:
- self.height *= 2
- elif self.travelled % 10 == 0:
- #self.height *= 3
- #see Cross product from wolfire blog, reversing x and y
- # with x being made negative and y negative for right turn
- left = -self.direction[1], self.direction[0]
- right = self.direction[1], -self.direction[0]
- #draw them
- projectile(self,left,[circle],'shrapnel')
- projectile(self,right,[circle],'shrapnel')
- #print 'broke up'
- else: self.height = 4
- def initLists(self):
- self.travelled = 0
- self.oldMEN = MEN
- def name(self):
- self.name = '{0} No. {1}'.format(self.variety,len(ALLTHINGS))
- def fire(self):
- #get rect of curFrame's center x
- if self.variety == 'bullet':
- self.x,self.y = self.curFrame.get_rect().midright
- #spawn at first position out from source
- # add the center of the rect to the center of
- # shooter then move bit a bit
- self.x = self.x + self.source.x #+ self.direction[0]
- self.y = self.y + self.source.y #+ self.direction[1]
- elif self.variety == 'shrapnel':
- self.x,self.y = self.source.getPos()
- #spawn at first position out from source
- # add the center of the rect to the center of
- # shooter then move bit a bit
- self.x = self.x + self.direction[0]
- self.y = self.y + self.direction[1]
- self.draw()
- def move(self):
- self.x += self.direction[0] * self.speed
- self.y += self.direction[1] * self.speed
- #if self still in play
- if self.active:
- self.travelled +=1
- #or if hit another
- # test all rects
- hit_something = False
- #for t in self.target:
- #if self.size.collidelist(self.target):
- #hit_something = t
- #break
- #print self.target[0].rect.size
- hit_something = self.size.collidelist(self.target)
- #print self.target[hit_something]
- #remove self if off screen
- if self.x > WIDTH + 1 or self.y > HEIGHT \
- or 0 > self.x or 0 > self.y:
- self.remove()
- #print 'removed: ', self.name
- elif hit_something != -1:
- print 'BULLET HIT!'
- self.target[hit_something].gotHit(5)
- self.remove()
- #add 1 movement to count. change color accordingly
- elif self.variety == 'shrapnel':
- if self.travelled > 3:
- if self in SHRAPNEL:
- self.remove()
- else : print 'shrapnel not in SHRAPNEL'
- def checkSize(self,):
- self.size = pygame.rect.Rect(self.x - (self.height /2),
- self.y - (self.height /2),
- self.height,
- self.height)
- #self.size.center = self.source.curFrame.get_rect().center
- #self.size.center = self.size.center + (self.x,self.y)
- def getPos(self):
- self.pos = (self.x,self.y)
- #print "pos = ", self.pos
- return self.pos
- def draw(self):
- self.checkSize()
- ##draw a rect
- #pygame.draw.rect(screen, self.color ,
- #self.size)
- ##draw a circle
- pygame.draw.circle(screen, self.color ,
- (self.size.x,self.size.y), 2)
- def hit(self):
- '''remove self from active list -> dead list'''
- #do damage to target,
- #animate
- self.remove()
- def remove(self):
- '''remove from pertinent lists and add to stats'''
- #print 'Gah, I\'m done!, signed, ', self.name, self.variety
- STATS.append(self)
- if self.variety == 'bullet':
- BULLETS.remove(self)
- elif self.variety == 'shrapnel':
- SHRAPNEL.remove(self)
- #kill the self in class
- self.active = False
- if __name__ == '__main__':
- # ########INIT######### #
- pygame.init()
- pygame.display.set_caption('Line Moving App')
- seticon('bricks.ico')
- screen = pygame.display.set_mode((WIDTH, HEIGHT))
- #screen.fill(BLUE)
- screen.set_colorkey((255,255,254))
- #background = pygame.Surface(screen.get_size())
- #background = background.convert()
- #background.fill(WHITE)
- clock = pygame.time.Clock()
- pygame.display.flip()
- basicFont = pygame.font.SysFont(None, 48)
- V = Vector()
- spawner = Spawner()
- # ############### #
- pathname = os.path.abspath(os.path.curdir)
- pathname += '/art/man/'
- #print pathname
- shot = shooter(1,100)
- circle = anything((400,200),'Josh', pathname,shooter=shot)
- circle.shooter.getTarget()
- #shot = shooter(1, 100)
- #AI = ai(DUMB)
- #bob = anything((350,200),'Bob',pathname, shooter=shot, ai= AI)
- #bob = spawner.spawn('mob')
- circle.shooter.getTarget()
- #bob.shooter.getTarget()
- # window for stats
- '''reference new module for stats here'''
- #window = statsWin.start()
- running = 1
- frame_count = 0
- frame_rate = 0
- t0 = time.clock()
- while running:
- #window()
- screen.fill(WHITE)
- #bob.ai.drawVision()
- #check for movements, and draw after
- for object in MEN:
- object.move()
- #object.check()
- #print object.name, 'is drawn', frame_count
- object.drawFrame()
- for object in BULLETS:
- object.update()
- for object in SHRAPNEL:
- object.update()
- #AIs think
- for object in AIs:
- object.check()
- object.drawVision()
- frame_count += 1
- if frame_count % 15 == 0:
- t1 = time.clock()
- frame_rate = 15 / (t1-t0)
- t0 = t1
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- running = 0
- elif event.type == pygame.KEYDOWN or event.type== pygame.KEYUP:
- key_event(event)
- elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
- #print event.button
- (circle.x,circle.y) = event.pos
- circle.go(False)
- elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 4:
- bob.x, bob.y = event.pos
- elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
- print event.button
- print 'mouse pressed'
- if mousePressed: circle.go(False)
- #take pos as vector:
- mousePos = (x,y) = event.pos
- circlePos = (circle.x,circle.y)
- print mousePos, circlePos
- #in relation to circle, directions the vector away from them.
- #subtract current selfx from x and same for selfy and y
- direction= tuple([a - b for a, b in zip(mousePos, circlePos)])
- print direction
- home = [a /200 for a in direction]
- print home
- #normalize home
- normed = V.norm(home)
- #new direction is normed
- circle.changeDir(normed)
- circle.go(True)
- mousePressed = True
- the_text = basicFont.render('Frame = {0}, rate = {1:.2f} fps'
- .format(frame_count, frame_rate), True, (0,0,0))
- screen.blit(the_text, (10, 10))
- for object in MEN:
- object.check()
- pygame.display.flip()
- #tkinter stuff below
- # #####
- clock.tick(FRAMERATE)
Advertisement
Add Comment
Please, Sign In to add comment