def mouseMotion(self, buttons, pos, rel): self.pos = pos # dragbox logic if buttons[0] == 1: if self.dragbox_draw == False: self.dragbox_draw = True self.dragbox_origin = self.dragbox_pos = vec2d(pos) elif self.dragbox_draw == True: self.dragbox_pos = vec2d(pos) # append boxed units to selection if LSHIFT is held down # if LSHIFT not held down, create new selection if not self.add_waypoints: self.selected = [] # if agent is in range of the dragbox for a in self.agents: if a not in self.selected: r = int(a.r*0.7) if self.dragbox_origin[0]-r <= a.pos[0] <= self.dragbox_pos[0]+r or \ self.dragbox_origin[0]+r >= a.pos[0] >= self.dragbox_pos[0]-r: if self.dragbox_origin[1]-r <= a.pos[1] <= self.dragbox_pos[1]+r or \ self.dragbox_origin[1]+r >= a.pos[1] >= self.dragbox_pos[1]-r: self.selected.append(a) # drag waypoint if buttons[2] == 1 and not self.add_waypoints: for a in self.selected: a.waypoints = [vec2d(pos)]
def mouseUp(self, button, pos): # if LSHIFT: # left mouse button click appends to selected list # right mouse button click appends to waypoint list if self.add_waypoints == True: if button == 1: for a in self.agents: if a not in self.selected and a.pos.get_distance(vec2d(pos)) <= 20: self.selected.append(a) self.dragbox_draw = False elif button == 3: for a in self.selected: a.waypoints.append(vec2d(pos)) # if not LSHIFT: # left mouse button click on an agent, overrides selected list and creates new selection # right mouse button click overrides waypoint list and creates new waypoint elif button == 1: if self.dragbox_draw == False: for a in self.agents: if a.pos.get_distance(vec2d(pos)) <= 20: self.selected = [a] self.dragbox_draw = False elif button == 3: for a in self.selected: a.waypoints = [vec2d(pos)]
def compute_coordinates(self): """computes beginning and end points""" self.source_pos = vec2d(self.n1.x) self.target_pos = vec2d(self.n2.x) #compute intersection points if self.source_pos != self.target_pos: if self.displace: delta = (self.target_pos - self.source_pos).perpendicular().normalized() self.source_pos += delta*5 self.target_pos += delta*5 circ = Circle(Point2(self.n1.x[0], self.n1.x[1]), float(self.n1.radius)) p1 = Point2(self.source_pos[0], self.source_pos[1]) p2 = Point2(self.target_pos[0], self.target_pos[1]) line = Line2(p1, p2) inters = line.intersect( circ ) if (p2 - inters.p1).magnitude() > (p2 - inters.p2).magnitude(): #use p2 self.source_pos[0] = inters.p2.x self.source_pos[1] = inters.p2.y else: #use p1 self.source_pos[0] = inters.p1.x self.source_pos[1] = inters.p1.y circ = Circle(Point2(self.n2.x[0], self.n2.x[1]), float(self.n2.radius)) inters = line.intersect( circ ) if (p1 - inters.p1).magnitude() > (p1 - inters.p2).magnitude(): #use p2 self.target_pos[0] = inters.p2.x self.target_pos[1] = inters.p2.y else: #use p1 self.target_pos[0] = inters.p1.x self.target_pos[1] = inters.p1.y
def test_init_player(self): player1 = Player(vec2d(100, 200), 1, 0, 3) player2 = Player(vec2d(100, 300), 1, 1, 3) self.assertEqual(player1.position[0], 100, "player 1 x is wrong") self.assertEqual(player1.position[1], 200, "player 1 y is wrong") self.assertEqual(player2.position[0], 100, "player 2 x is wrong") self.assertEqual(player2.position[1], 300, "player 2 y is wrong")
def line_circle_intersection( arc, circle_pos, circle_radius, inset=True): circ = Circle(Point2(circle_pos[0], circle_pos[1]), float(circle_radius)) p1 = Point2(arc.source_pos[0], arc.source_pos[1]) p2 = Point2(arc.target_pos[0], arc.target_pos[1]) if p1 != p2: line = Line2(p1, p2) inters = line.intersect( circ ) if (abs((p2 - inters.p1).magnitude() - (p2 - inters.p2).magnitude()) > abs((p1 - inters.p1).magnitude() - (p1 - inters.p2).magnitude())): p = p2 else: p = p1 if (p - inters.p1).magnitude() > (p - inters.p2).magnitude(): return vec2d( inters.p2.x, inters.p2.y ) #use p2 return vec2d( inters.p1.x, inters.p1.y ) #use p1 else: # circle to ellipse intersection if arc.r_a != arc.r_b: delta = sqrt(arc.r_b**2*(arc.r_a**4-arc.r_a**2*arc.r_b**2+arc.r_b**2*circle_radius**2)) y = ((circle_pos[1]-circle_radius)*arc.r_a**2+delta-arc.r_b**2*circle_pos[1])/(arc.r_a**2-arc.r_b**2) if inset: x = circle_pos[0]-sqrt(circle_radius**2-(y-circle_pos[1])**2) else: x = circle_pos[0]+sqrt(circle_radius**2-(y-circle_pos[1])**2) return vec2d(x, y) return circle_pos+(circle_radius,0) #dummy
def run(self): """main method. do the simulation""" #initialize the particle system self.init_nodes() self.do_bfs() self.do_count() self.keep_running = True while self.keep_running: self.c +=1 #simulate until net movement is very low, but #at least for 100 time steps #also simulate if user is dragging a node nm = self.net_movement() if nm > -0.5 or self.c < 100 or self.dragging: #if physics is enabled then do simulation if self.physics: self.accumulate_force() self.verlet() self.handle_input() #handle all user input #handle node dragging if not self.dragging == None: pos = pygame.mouse.get_pos() self.dragging.x = vec2d(pos) self.dragging.oldx = vec2d(pos) #draw everything self.draw() pygame.quit()
def __init__(self): self.w, self.h = 800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=((255,255,255))) self.a=Agent() self.a.pos=vec2d(400, 300) self.a.target=vec2d(300,300)
def test_init_point(self): point1 = Point(vec2d(100, 200), 1, 0) point2 = Point(vec2d(100, 300), 1, 1) self.assertEqual(point1.position[0], 100, "point 1 x is wrong") self.assertEqual(point1.position[1], 200, "point 1 y is wrong") self.assertEqual(point2.position[0], 100, "point 2 x is wrong") self.assertEqual(point2.position[1], 300, "point 2 y is wrong")
def __init__(self): self.pos = vec2d(0,0) self.vel = vec2d(0,0) self.action = 0 #0 = standing, 1 = running, 2 = ducking, 3 = jumping #(also to implement: 4 = flying, 5 = swimming) self.dir = 1 self.maxvel = 3 #player's maximum running velocity self.right = 0 #check to see if player needs to accelerate self.left = 0 self.rightdown = 0 #check to see if the right key is down self.leftdown = 0 self.acceleration = 1 #the acceleration of the player self.deaccelerate = 0 #check to see if the player needs to accelerate self.deacceleration = .2 #the deacceleration of the player self.jumpvel = -10 #jump power self.jumpmaxtime = 5 #max time to hold the jump button self.jumptime = 0 #used to iterate from 1 to maxtime self.life = 100
def __init__(self): # set pygame vars self.w, self.h = 1024, 768 PygameHelper.__init__(self, size=(self.w, self.h), fill=((255,255,255))) self.font=pygame.font.SysFont('Helvetica', 16, bold=False, italic=True) # mouse cursor self.pos = (0,0) # selected agents list self.selected = [] # object lists self.agents = [] self.statics = [] # control group toggle/dictionary self.lctrl = False self.ctrl_groups = {} # LSHIFT toggle self.add_waypoints = False # dragbox_draw toggle self.dragbox_draw = False # dragbox coordinates self.dragbox_origin = vec2d(0,0) self.dragbox_pos = vec2d(0,0)
def run(self, physics=False): while 1: self.c +=1 #simulate until net movement is very low, but #at least for 100 time steps #also simulate if user is dragging a node nm = self.netMovement() if nm > -0.5 or self.c < 100 or self.dragging: #if physics is enabled then do simulation if physics: self.accumulate_force() self.verlet() cont = self.handle_input() #handle all user input if not cont: return #handle node dragging if not self.dragging == None: pos = pygame.mouse.get_pos() self.dragging.x = vec2d(pos) self.dragging.oldx = vec2d(pos) #draw everything self.draw()
def __init__(self, width, height): self.w, self.h = width, height PygameHelper.__init__(self, size=(self.w, self.h), fill=((255,255,255))) self.unit_pos = vec2d(width/2,height/2) self.target_pos = vec2d(width/2,height/2) self.unit_img = pygame.image.load("unit1.png") self.target_img = pygame.image.load("target1.png")
def __init__(self): self.pos = vec2d(0,0) self.vel = vec2d(0,0) self.life = 100 self.maxvel = 4 self.acceleration = 1 self.deaccelerate = 0 self.jump = 4
def __init__(self, pos): self.pos = vec2d(pos) self.vel = vec2d(3, 0) self.radius = 2 self.life = 40 self.side = 0 self.live = True
def verlet(self): for n in self.graph.nodes: temp = vec2d(n.x.x, n.x.y) #store old position #n.x += ((1.0 - self.friction)*n.weight*(n.x - n.oldx)) + n.a*self.dt*self.dt n.x += (((1.0 - self.friction)*(n.x - n.oldx)) + n.a + vec2d(-10,0))*self.dt*self.dt / n.weight n.oldx = temp for n in self.graph.nodes: #reset accelerations for next iteration n.a = 0.0
def __init__(self, radius=10): self.pos = vec2d(0, 0) self.vel = vec2d(3, 0) self.vel.rotate(uniform(0, 359)) self.radius = radius self.mass = radius**2 self.side = 0 self.life = self.radius
def handle_input(self): """handle all user input and interactivity""" for event in pygame.event.get(): if event.type == QUIT: self.quit() elif event.type == KEYDOWN: if event.key == K_ESCAPE: self.quit() elif event.key == K_r: self.init_nodes() self.do_bfs() self.do_count() elif event.key == K_d: #delete closest node d = self.findclosest(pygame.mouse.get_pos()) toRem = [] for s in self.springs: if s.n1 == d or s.n2 == d: toRem.append(s) for t in toRem: self.springs.remove(t) self.nodes.remove(d) self.do_bfs() self.do_count() elif event.key == K_p: self.physics = not self.physics elif event.key == K_n: for z in self.nodes: z.x = vec2d(uniform(self.w/2-10,self.w/2+10), uniform(self.h/2-10,self.h/2+10)) z.oldx = z.x elif event.type == MOUSEBUTTONUP: if event.button == 1: self.dragging = None else: now = vec2d(event.pos) then = vec2d(self.selected) if now.get_distance(then) < 10: #just make a new node here (at now) self.nodes.append(node(now)) self.do_bfs() self.do_count() else: #make new line btw last node and this node nowNode=self.findclosest(now) thenNode=self.findclosest(then) self.springs.append(spring(nowNode, thenNode)) self.do_bfs() self.do_count() self.selected = None elif event.type == MOUSEBUTTONDOWN: if event.button == 1: self.dragging = self.findclosest(event.pos) else: self.selected = event.pos
def handle_input(self): for event in pygame.event.get(): if event.type == QUIT: self.quit() elif event.type == KEYDOWN: if event.key == K_ESCAPE: #self.quit() return False elif event.key == K_r: self.graph = Graph(self.world) #elif event.key == K_d: ##delete closest node #d = self.findclosest(pygame.mouse.get_pos()) #toRem = [] #for s in self.graph.springs: #if s.n1 == d or s.n2 == d: #toRem.append(s) #for t in toRem: #self.graph.springs.remove(t) #self.graph.nodes.remove(d) #self.doBFS() #self.doCount() elif event.key == K_p: self.physics = not self.physics elif event.key == K_n: for z in self.graph.nodes: z.x = vec2d(uniform(self.w/2-10,self.w/2+10), uniform(self.h/2-10,self.h/2+10)) z.oldx = z.x elif event.type == MOUSEBUTTONUP: if event.button == 1: self.dragging = None else: now = vec2d(event.pos) then = vec2d(self.selected) if now.get_distance(then) < 10: #just make a new node here (at now) self.graph.nodes.append(node(now)) self.graph.doBFS() self.graph.doCount() else: #make new line btw last node and this node nowNode=self.findclosest(now) thenNode=self.findclosest(then) self.graph.springs.append(spring(nowNode, thenNode)) self.graph.doBFS() self.graph.doCount() self.selected = None elif event.type == MOUSEBUTTONDOWN: if event.button == 1: self.dragging = self.findclosest(event.pos) else: self.selected = event.pos return True
def __init__(self, pos, target, dmg, size, shape='line'): self.pos = vec2d(pos) self.vel = 0 self.dir = vec2d(0,0) self.color = (255,255,255) self.target = target self.dmg = dmg self.size = size self.shape = shape self.contact = False
def mouseUp(self, button, pos): # pygame.draw.circle(self.screen, (0,0,0), pos, 20) if button == 3: self.selected.target = vec2d(pos) if button == 2: self.selected.target = vec2d(pos) elif button == 1: for a in self.agents: if a.pos.get_distance(vec2d(pos)) < 20: self.selected = a
def DrawOnCur(self,pos): if s.Keys!=0: if s.Keys[K_EQUALS]: self.ZoomRang+=vec2d(2,1) if s.Keys[K_MINUS]: self.ZoomRang-=vec2d(2,1) Pos=vec2d(pos-self.ZoomRang/2) pygame.draw.rect(self.screen,self.Colour,((Pos),(self.ZoomRang)),1) Mouse=pygame.mouse.get_pressed() if Mouse[0]: self.Draw(pos,Mouse[0])
def intersect_bezier3_ellipse(self, curve_points, ec, rx, ry=None): """Find points of intersection between a cubic bezier curve and an ellipse""" p1, p2, p3, p4 = curve_points if ry is None: ry = rx # Calculate coefficients of cubic polynomial a = p1 * -1 b = p2 * 3 c = p3 * -3 d = a + b + c + p4 c3 = vec2d(d.x, d.y) a = p1 * 3 b = p2 * -6 c = p3 * 3 d = a + b + c c2 = vec2d(d.x, d.y) a = p1 * -3 b = p2 * 3 c = a + b c1 = vec2d(c.x, c.y) c0 = vec2d(p1.x, p1.y) rxrx = rx * rx ryry = ry * ry poly = [ c3.x * c3.x * ryry + c3.y * c3.y * rxrx, 2 * (c3.x * c2.x * ryry + c3.y * c2.y * rxrx), 2 * (c3.x * c1.x * ryry + c3.y * c1.y * rxrx) + c2.x * c2.x * ryry + c2.y * c2.y * rxrx, 2 * c3.x * ryry * (c0.x - ec.x) + 2 * c3.y * rxrx * (c0.y - ec.y) + 2 * (c2.x * c1.x * ryry + c2.y * c1.y * rxrx), 2 * c2.x * ryry * (c0.x - ec.x) + 2 * c2.y * rxrx * (c0.y - ec.y) + c1.x * c1.x * ryry + c1.y * c1.y * rxrx, 2 * c1.x * ryry * (c0.x - ec.x) + 2 * c1.y * rxrx * (c0.y - ec.y), c0.x * c0.x * ryry - 2 * c0.y * ec.y * rxrx - 2 * c0.x * ec.x * ryry + c0.y * c0.y * rxrx + ec.x * ec.x * ryry + ec.y * ec.y * rxrx - rxrx * ryry, ] # print "poly is: %s" % poly[::-1] roots = self.get_roots_in_interval(poly[::-1]) # print "roots are: %s" % roots result = [] for t in roots: result.append(c3 * t ** 3 + c2 * t ** 2 + c1 * t + c0) # print "results are: %s" % result return result
def __init__(self): self.w, self.h = 800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=((255, 255, 255))) self.agents = [] for i in range(10): a = Agent() a.pos = vec2d(uniform(0, self.w), uniform(0, self.h)) a.target = vec2d(uniform(0, self.w), uniform(0, self.h)) self.agents.append(a) self.selected = self.agents[0]
def __init__(self, screen, unitType, initPosition, initDirection, speed, targetList): Sprite.__init__(self) self.isDead = False self.screen = screen self.speed = vec2d(speed) self.pos = vec2d(initPosition) self.direction = vec2d(initDirection).normalized() self.base_image = pygame.image.load(UNITTYPES[unitType]["img"]).convert_alpha() self.image = self.base_image self.size = self.image.get_size() self.rect = pygame.Rect(initPosition, self.size) self.flow = numpy.array([0, 0]) self.targetList = copy.deepcopy(targetList) self.currTarget = self.targetList[0]
def update(self, others, gravity, magnets, box, merge): if self.speed.length < 255: self.color[0] = self.speed.length else: self.color[0] = 255 for point in others: if point is not self and point.alive: dir = point.pos - self.pos if dir.length < (self.size + point.size): impact_energy = point.speed if impact_energy.length > 0: impact_energy.length = int(impact_energy.length * (point.size / self.size) * 0.6) impact_speed = dir impact_speed.length = 0 - (((self.size + point.size) - dir.length) / 2) self.pos += impact_speed self.speed += impact_speed self.speed += impact_energy #self.speed = vec2d(int((self.speed[0] * 4) / 5), int((self.speed[1] * 4) / 5)) if merge: self.size = int(sqrt(point.size * point.size + self.size * self.size)) point.alive = False elif magnets: if dir.length < 20 * self.size: dir.length = int((dir.length / 20 ) * (self.size / point.size) * 0.02) print(self.size , "ima leng : ", dir.length) point.speed -= dir if gravity: self.speed += vec2d(0, 2) if box: if self.pos[1] > self.h - self.size: self.speed = vec2d(self.speed[0], - int((self.speed[1] * 4) / 5) ) self.pos[1] = self.h - self.size elif self.pos[1] < 0 + self.size: self.speed = vec2d(self.speed[0], - int((self.speed[1] * 4) / 5) ) self.pos[1] = 0 + self.size if self.pos[0] > self.w - self.size: self.pos[0] = self.w - self.size self.speed = vec2d(- int((self.speed[0] * 3) / 5), self.speed[1]) elif self.pos[0] < 0 + self.size: self.pos[0] = 0 + self.size self.speed = vec2d(- int((self.speed[0] * 3) / 5), self.speed[1]) self.pos += self.speed
def SetCoeffs(self): n=0 for i in self.CirAtr: if i.Group==2: self.CX[n]=1/(vec2d(i.pos-self.Xdot.pos).get_length()) self.CY[n]=0 elif i.Group==3: self.CY[n]=1/(vec2d(i.pos-self.Ydot.pos).get_length()) self.CX[n]=0 elif i.Group<2: self.CY[n]=0 self.CX[n]=0 n+=1 self.CoefNormalize()
def __init__(self): self.w, self.h = 800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=(255, 255, 255)) self.pos = vec2d(400,300) self.target = vec2d(300,300) self.img = pygame.image.load("tilesets/derek/HeroBase.png") #self.screen.blit(img, (-2, -2)) self.drawcolor = (0, 0, 0) self.x = 0
def __init__(self): self.pos = vec2d(0, 0) self.vel = vec2d(0, 0) self.acc = vec2d(0, 0) self.rect = pygame.Rect((self.pos), (5, 5)) self.move = vec2d(0, 0) self.create_rate = 3000 # create particles every no. milliseconds self.clock = pygame.time.Clock() self.tracker = 0 self.dt = 0 self.absorbed = False # Whether the player has been absorbed or not self.life = 100
def intersect_bezier3_ellipse(self, curve_points, ec, rx, ry=None): """Find points of intersection between a cubic bezier curve and an ellipse""" p1, p2, p3, p4 = curve_points if ry is None: ry = rx # Calculate coefficients of cubic polynomial a = p1 * -1 b = p2 * 3 c = p3 * -3 d = a + b + c + p4 c3 = vec2d(d.x, d.y) a = p1 * 3 b = p2 * -6 c = p3 * 3 d = a + b + c c2 = vec2d(d.x, d.y) a = p1 * -3 b = p2 * 3 c = a + b c1 = vec2d(c.x, c.y) c0 = vec2d(p1.x, p1.y) rxrx = rx*rx ryry = ry*ry poly = [ c3.x*c3.x*ryry + c3.y*c3.y*rxrx, 2*(c3.x*c2.x*ryry + c3.y*c2.y*rxrx), 2*(c3.x*c1.x*ryry + c3.y*c1.y*rxrx) + c2.x*c2.x*ryry + c2.y*c2.y*rxrx, 2*c3.x*ryry*(c0.x - ec.x) + 2*c3.y*rxrx*(c0.y - ec.y) + 2*(c2.x*c1.x*ryry + c2.y*c1.y*rxrx), 2*c2.x*ryry*(c0.x - ec.x) + 2*c2.y*rxrx*(c0.y - ec.y) + c1.x*c1.x*ryry + c1.y*c1.y*rxrx, 2*c1.x*ryry*(c0.x - ec.x) + 2*c1.y*rxrx*(c0.y - ec.y), c0.x*c0.x*ryry - 2*c0.y*ec.y*rxrx - 2*c0.x*ec.x*ryry + c0.y*c0.y*rxrx + ec.x*ec.x*ryry + ec.y*ec.y*rxrx - rxrx*ryry ] #print "poly is: %s" % poly[::-1] roots = self.get_roots_in_interval(poly[::-1]) #print "roots are: %s" % roots result = [] for t in roots: result.append(c3 * t ** 3 + c2 * t ** 2 + c1 * t + c0) #print "results are: %s" % result return result
def __init__(self): self.w, self.h = 256, 194 #size = 1000, 194 #pygame.display.set_mode(size)#(reslolution=(self.w,self.h), flags=pygame.RESIZABLE, depth=0) PygameHelper.__init__(self, size=(self.w, self.h), fill=((255,255,255))) #self.bgpos = 0, -269 self.bg= background() self.me= player() self.gravity= vec2d(0, 1) self.runitr = 0 #load the mario image standing= pygame.image.load('big_standing1.png').convert() standing.set_colorkey((255,242,0)) self.standing = standing running1= pygame.image.load('big_running1.png').convert() running1.set_colorkey((255,242,0)) self.running1 = running1 running2= pygame.image.load('big_running2.png').convert() running2.set_colorkey((255,242,0)) self.running2 = running2 jumping= pygame.image.load('big_jumping1.png').convert() jumping.set_colorkey((255,242,0)) self.jumping = jumping
def update(self, update_type=0): """Draw the image this tile represents""" vpad = vec2d(self.ep_size, self.ep_size) self.image = pygame.Surface((self.width + vpad.x * 2, self.height + vpad.y * 2)) # Either draw the background blue, or don't if self.transparency: self.image.fill(transparent) else: self.image.fill(blue) # Draw the circle pygame.draw.circle(self.image, white, (self.radius + vpad.x, self.radius + vpad.y), self.radius, 1) # Draw circle conntrol points for p in self.CPDict.values(): q = p.position - self.position + vpad pygame.draw.circle(self.image, red, (int(q.x), int(q.y)), self.ep_size) # Set transparency self.image.set_colorkey(transparent) # Finally call update on all child CPSprites, to align their positions for p in self.CPDict.values(): p.update()
def draw_binding(surface, circle_pos, points): #compute angle of every line from circle center to each point if len(points) < 2: return #print "circle center:", circle_pos radius = (circle_pos - points[0]).get_length() #print "radius:", radius angles = [-((p - circle_pos).get_rad_angle()) for p in points] #print "angles:", angles #convert all angles to positive max_span = 2 * math.pi for i, angle in enumerate(angles): #test which is the best starting angle relative = [] for angle2 in angles: if angle2 >= angle: relative.append(angle2 - angle) else: relative.append(2 * math.pi + angle2 - angle) span = max(relative) if span < max_span: max_span = span start_angle = angle final_angle = span + angle pygame.draw.arc( surface, (0, 0, 0), Rect(circle_pos - (radius, radius), vec2d(radius, radius) * 2), start_angle, final_angle)
def __init__(self, position, parent): pygame.sprite.Sprite.__init__(self) if BezLinkedLine.init: BezLinkedLine.bezier = Bezier() BezLinkedLine.init = False self.transparency = True self.position = position # The BezCurve that this sprite is a child to self.parent = parent # Line defined by two control points, one is moveable, the other is fixed # to the bezier curve that this line is a child to self.CPGroup = pygame.sprite.Group() self.CPDict = {} # Movable control point sp = CPSprite(self.position, self, label="move") self.CPGroup.add(sp) self.CPDict["move"] = sp # UnMovable control point sp = CPSprite(self.position + vec2d(50,50), self, label="unmove") self.CPGroup.add(sp) self.CPDict["unmove"] = sp self.update_endpoint("move", self.position) self.calc_rect() self.update()
def __init__(self): self.pos= vec2d(0,0) self.target= vec2d(0,0) self.drawid=0 self.type=0 self.status=1 self.time=0 self.textid=0 self.name="" self.ConOut=0 self.ConDraw=0 self.Outs=[] self.OutAm=1 self.Start=0 self.Params={} self.Container=0
def build_vtemp(self, cps, t): """""" Vtemp = [] vt2 = [] for x in range(len(cps)): vt = [] vt22 = [] for y in range(len(cps)): vt.append(vec2d(0,0)) vt22.append(0) vt2.append(vt22) Vtemp.append(vt) # Copy control points for n, cp in enumerate(cps): Vtemp[0][n].x = cp.x vt2[0][n] = 2 Vtemp[0][n].y = cp.y # Triangle computation # Uses forward/back substitution on the triangular matrix for i in range(1, len(cps)): for j in range(len(cps) - i): Vtemp[i][j].x = (1.0 - t) * Vtemp[i-1][j].x + t * Vtemp[i-1][j+1].x Vtemp[i][j].y = (1.0 - t) * Vtemp[i-1][j].y + t * Vtemp[i-1][j+1].y vt2[i][j] = 1 return Vtemp
def update(self, update_type=0): """""" vpad = vec2d(self.ep_size, self.ep_size) self.image = pygame.Surface((self.width + vpad.x * 2, self.height + vpad.y * 2)) # Either draw the background blue, or don't if self.transparency: self.image.fill(transparent) else: self.image.fill(blue) # Draw a line between control handles pygame.draw.line(self.image, green, self.CPDict["move"].position - self.position + vpad, self.CPDict["unmove"].position - self.position + vpad) # Draw control handles for p in self.CPDict.values(): q = p.position - self.position + vpad pygame.draw.circle(self.image, red, (int(q.x), int(q.y)), self.ep_size) # Set transparency self.image.set_colorkey(transparent) # Finally call update on all child CPSprites, to align their positions for p in self.CPDict.values(): p.update()
def calc_rect(self): """Calculate the current rect of this tile""" # Rect must completely bound all of the control points # Since a bezier curve is completely bounded by the convex hull of its # control points we can simply find the smallest rect which contains them all cps = self.CPDict xvals = [] for x in self.eps: xvals.append(cps[x].position.x) yvals = [] for y in self.eps: yvals.append(cps[y].position.y) minx = min(xvals) miny = min(yvals) maxx = max(xvals) maxy = max(yvals) # Rect position takes into account the offset self.width = maxx-minx self.height = maxy-miny self.position = vec2d(minx, miny) self.rect = (self.position.x - self.ep_size, self.position.y - self.ep_size, self.width + self.ep_size, self.height + self.ep_size) return self.rect
def __init__(self, screen, game, tower, target, aoe=False, aoefactor=0.50, effect=None): """Launch another projectile. screen: The screen on which the projectile is drawn and located. game: This is the game object that holds information about the game world. tower: This is the tower object firing the projectile_image target: This is the target of the projectile. aoe (optional): defaults to False aoefactor (optional): defaults to 0.50, and defines how much of the damage should be dealt in the area of effect. effect (optional): defaults to None projectile_image: is found within the tower object (tower.projectile_image). """ Sprite.__init__(self) self.screen = screen self.game = game self.tower = tower self.target = target self.speed = self.tower.projectile_speed self.pos = vec2d((self.tower.pos[0] + (self.tower.width / 2), self.tower.pos[1] + (self.tower.height / 2))) self.aoe = aoe self.aoefactor = aoefactor if type(effect) != type([]) and type(effect) != type(None): self.effects = [effect] elif type(effect) == type([]): self.effects = effect else: self.effects = [] self.base_image = self.tower.projectile_image self._compute_direction() self.image = pygame.transform.rotate(self.base_image, -self.direction.angle) self.width = self.base_image.get_width() self.height = self.base_image.get_height() self.rect = Rect(self.pos[0], self.pos[1], self.width, self.height) #self.radius = used further down for aoe collision detection self.age = 0 self.duration = 1 * 2000 self.game.projectiles.add(self)
def findclosest(self, p): ld = self.w + self.h li = None v = vec2d(p) for n in self.nodes: d = v.get_distance(n.x) if d < ld: ld = d li = n return li
def verlet(self): """integrate one single time step to get new positions from old positions based on acceleration of each node.""" for n in self.nodes: temp = vec2d(n.x.x, n.x.y) #store old position n.x += (1.0 - self.friction) * n.x - ( 1.0 - self.friction) * n.oldx + n.a * self.dt * self.dt n.oldx = temp for n in self.nodes: #reset accelerations for next iteration n.a = 0.0
def calc_rect(self): """""" self.width = self.radius * 2 self.height = self.radius * 2 # Get position from the move CPSprite self.position = self.CPDict["move"].position - vec2d(self.radius, self.radius) self.rect = (self.position.x - self.ep_size, self.position.y - self.ep_size, self.width + self.ep_size, self.height + self.ep_size) return self.rect
def mouse_move(self, position, collisionlist): """Tool updated, current cursor position is newpos""" if len(self.dragsprite) > 0: # Move current control point # Get dragsprite's parent, and label parentsprite = self.dragsprite.sprite.parent label = self.dragsprite.sprite.label # Call update_endpoint method of parent with label as argument # This will update the parent sprite and all its children parentsprite.update_endpoint(label, vec2d(position)) return True
def compute_points(controlpoints, nsteps=30): """ Input 4 control points as wxRealPoints and convert to vec2d instances. compute the nsteps points on the resulting curve and return them as a list of wxPoints """ controlvectors = [] for p in controlpoints: controlvectors.append(vec2d(p.x, p.y)) pointvectors = calculate_bezier(controlvectors, nsteps) curvepoints = [] for v in pointvectors: curvepoints.append(wx.Point(v[0], v[1])) return curvepoints
def compute_coordinates(self): """computes beginning and end points""" self.source_pos = vec2d(self.n1.x) self.target_pos = vec2d(self.n2.x) #compute intersection points if self.source_pos != self.target_pos: if self.displace: delta = (self.target_pos - self.source_pos).perpendicular().normalized() self.source_pos += delta * 5 self.target_pos += delta * 5 circ = Circle(Point2(self.n1.x[0], self.n1.x[1]), float(self.n1.radius)) p1 = Point2(self.source_pos[0], self.source_pos[1]) p2 = Point2(self.target_pos[0], self.target_pos[1]) line = Line2(p1, p2) inters = line.intersect(circ) if (p2 - inters.p1).magnitude() > (p2 - inters.p2).magnitude(): #use p2 self.source_pos[0] = inters.p2.x self.source_pos[1] = inters.p2.y else: #use p1 self.source_pos[0] = inters.p1.x self.source_pos[1] = inters.p1.y circ = Circle(Point2(self.n2.x[0], self.n2.x[1]), float(self.n2.radius)) inters = line.intersect(circ) if (p1 - inters.p1).magnitude() > (p1 - inters.p2).magnitude(): #use p2 self.target_pos[0] = inters.p2.x self.target_pos[1] = inters.p2.y else: #use p1 self.target_pos[0] = inters.p1.x self.target_pos[1] = inters.p1.y
def __init__(self, radius, position, intersect_link=None, parent=None): pygame.sprite.Sprite.__init__(self) if Circle.init: Circle.bezier = Bezier() Circle.intersection = Intersection() Circle.init = False self.transparency = True # The Shape that this Shape is a child to self.parent = parent # Position of this graphic self.position = position # Circles defined by radius self.radius = radius # CPGroup, sprite group containing all control points for quick access self.CPGroup = pygame.sprite.Group() # CPDict, dict containing keyed control points for easy access to modify self.CPDict = {} sp = CPSprite(self.position + vec2d(self.radius, self.radius), self, label="move") self.CPGroup.add(sp) self.CPDict["move"] = sp # Add CP for middle of shape to move it sp = CPSprite(self.position + vec2d(self.radius * 2, self.radius), self, label="radius") self.CPGroup.add(sp) self.CPDict["radius"] = sp # Set ilink property to this shape's intersection_link neighbour self.ilink = intersect_link # If this shape has an intersect_link, need to update intersection self.update_intersect() self.calc_rect() self.update()
def update_endpoint(self, endpoint, newposition): """""" if endpoint is "move": # Move the entire shape to center on new position # Get old position of the center control point oldpos = self.CPDict["move"].position # Calculate vector from the old to the new movepos = oldpos - newposition # Apply this movement vector to the rest of the control points for p in self.CPDict.values(): p.position -= movepos # This will automatically update the position of the entire shape # when we do a calc_rect self.calc_rect() self.update() return vec2d(0,0)
def __init__(self, control_points, position): pygame.sprite.Sprite.__init__(self) if BezCurve.init: BezCurve.bezier = Bezier() BezCurve.init = False self.transparency = True self.children = [] self.time = pygame.time.get_ticks() # Position of this graphic self.position = position # Length of the bezier curve self.length = 0 self.dot_pos = 0 self.speed = 0.1 self.movement = 1 self.eps = ["e0","e1","e2","e3"] # 4 Control points defining the curve # Also needs a control point to move the shape # but probably better to build this into a different item # e.g. move_control_point, which is always at the center # of the shape # CPGroup, sprite group containing all control points for quick access self.CPGroup = pygame.sprite.Group() # CPDict, dict containing keyed control points for easy access to modify self.CPDict = {} for cp, key in zip(control_points, self.eps): sp = CPSprite(cp + self.position, self, label=key) self.CPGroup.add(sp) self.CPDict[key] = sp # Calculate the sprite's rect self.calc_rect() # Add CP for middle of shape to move it sp = CPSprite(self.position + vec2d(self.width / 2, self.height / 2), self, label="move") self.CPGroup.add(sp) self.CPDict["move"] = sp # Must modify control points in two ways: # Update control_points value # Update CPDict value self.update()
def convert_to_bezier_form(self, P, cps): """Given a point and control points for a bezcurve, generate 5th degree Bezier-format equation whose solution finds the point on the curve nearest the user-defined point""" # Precomputed "z" values for cubics z = [[1.0, 0.6, 0.3, 0.1], [0.4, 0.6, 0.6, 0.4], [0.1, 0.3, 0.6, 1.0]] # Determine the "c" values, these are vectors created by subtracting # point P from each of the control points c = [] for cp in cps: c.append(cp - P) # Determine the "d" values, these are vectors created by subtracting # each control point from the next (and multiplying by 3?) d = [] for i in range(len(cps)-1): d.append((cps[i+1] - cps[i]) * 3.0) # Create table of c/d values, table of the dot products of the # values from c and d cdtable = [] for row in range(len(cps)-1): temp = [] for col in range(len(cps)): temp.append(d[row].dot(c[col])) cdtable.append(temp) # A little unsure about this part, the C-code was unclear! # Apply the "z" values to the dot products, on the skew diagonal # Also set up the x-values, making these "points" - What does this mean? w = [] n = len(cps) - 1 m = len(cps) - 2 # Bezier is uniform parameterised for i in range(6): w.append(vec2d(i/5.0, 0.0)) for k in range(n+m+1): lb = max(0, k - m) ub = min(k, n) for i in range(lb, ub+1): j = k - i w[i+j].y += cdtable[j][i] * z[j][i] return w
def calc_rect(self): """Calculate the rect of this shape""" # Line has two endpoints, one is determined by the user # the other is determined by finding the closest point to it # on the parent's bezier curve p1 = self.CPDict["move"].position p2 = self.CPDict["unmove"].position # Rect must encompass both points, find max and min for x and y maxx = max(p1.x, p2.x) minx = min(p1.x, p2.x) maxy = max(p1.y, p2.y) miny = min(p1.y, p2.y) self.width = maxx-minx self.height = maxy-miny self.position = vec2d(minx, miny) self.rect = (self.position.x - self.ep_size, self.position.y - self.ep_size, self.width + self.ep_size, self.height + self.ep_size) return self.rect
def update_endpoint(self, endpoint, newposition): """""" if endpoint in self.eps: # Move the specified endpoint and recalculate all self.CPDict[endpoint].position = newposition self.calc_rect() self.CPDict["move"].position = self.position + vec2d(self.width/2, self.height/2) self.update() elif endpoint is "move": # Move the entire shape to center on new position # Get old position of the center control point oldpos = self.CPDict["move"].position # Calculate vector from the old to the new movepos = oldpos - newposition # Apply this movement vector to the rest of the control points for p in self.CPDict.values(): p.position = p.position - movepos # This will automatically update the position of the entire shape # when we do a calc_rect self.calc_rect() self.update()
def update(self, update_type=0): """""" vpad = vec2d(self.ep_size, self.ep_size) self.image = pygame.Surface((self.width + vpad.x * 2, self.height + vpad.y * 2)) # Either draw the background blue, or don't if self.transparency: self.image.fill(transparent) else: self.image.fill(blue) # Draw spot to represent this point pygame.draw.circle(self.image, red, vpad, self.ep_size) # Set transparency self.image.set_colorkey(transparent) # Finally call update on all child CPSprites, to align their positions for p in self.CPDict.values(): p.update()
def init_nodes(self): """initialize all the nodes and springs""" self.nodes = [] self.springs = [] num_nodes = len(self.node_labels) node_dict = {} #put nodes in max distance order to initial activity for n in self.node_labels: if len(self.insets[n]) == 0: #initial activity x_pos = self.w / 2 - 15 y_pos = self.h / 2 elif len(self.outsets[n]) == 0: #final activity x_pos = self.w / 2 + 15 y_pos = self.h / 2 else: # rest of nodes x_pos = uniform(self.w / 2 - 10, self.w / 2 + 10) y_pos = uniform(self.h / 2 - 10, self.h / 2 + 10) z = node(vec2d(x_pos, y_pos), n) node_dict[n] = z self.nodes.append(z) arcs = set() for s_act, outsets in self.outsets.iteritems(): for outset in outsets: for t_act in outset: arcs.add((s_act, t_act)) for s_act, t_act in arcs: s = spring(node_dict[s_act], node_dict[t_act], (t_act, s_act) in arcs) self.springs.append(s) # for i in range(num_nodes): # for j in range(num_nodes): # if i != j and uniform(0,1) < 0.1 and self.dnc(i,j): # s = spring(self.nodes[i], self.nodes[j]) # self.springs.append(s) self.c = 0
def MainLoop(self): """This is the Main Loop of the Game""" # Initiate the clock self.clock = pygame.time.Clock() self.box_size = 200 # Settings for FPS counter self.fps_refresh = FPS_REFRESH self.fps_elapsed = 0 # The currently selected point self.selected = None # Array to contain endpoint positions selected during the start of a draw operation self.start_positions = [] # Stores the last recorded drag operation position for world movement self.last_rmbpos = (0,0) # Current tool mode self.lmb_tool = ControlMover() self.rmb_tool = ScreenMover() self.sprites = pygame.sprite.LayeredUpdates() curve_points = [vec2d(0,0),vec2d(40,40),vec2d(200,100),vec2d(240,240)] bc = BezCurve(curve_points, vec2d(200,200)) self.sprites.add(bc, layer=1) bll = BezLinkedLine(vec2d(50,50), parent=bc) self.sprites.add(bll, layer=1) bc.link_child(bll) for c in curve_points: c += vec2d(200,200) circle_pos = vec2d(320,280) circle_rad = 40 cir = Circle(circle_rad, circle_pos, intersect_link=bc, parent=bc) self.sprites.add(cir, layer=1) bc.link_child(cir) circle_pos = vec2d(500,50) circle_rad = 60 cir2 = Circle(circle_rad, circle_pos, intersect_link=bc) self.sprites.add(cir2, layer=1) while True: self.clock.tick(0) # If there's a quit event, don't bother parsing the event queue if pygame.event.peek(pygame.QUIT): pygame.display.quit() sys.exit() # Clear the stack of dirty tiles self.dirty = [] clear = False for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.display.quit() sys.exit() if event.key == pygame.K_t: # Activate "debug" mode self.debug = not self.debug for s in self.sprites: s.transparency = not self.debug print "debug toggled, new state: %s" % self.debug if event.type == pygame.MOUSEBUTTONDOWN: # LMB if event.button == 1: self.lmb_tool.mouse_down(event.pos, self.sprites) # RMB if event.button == 3: self.rmb_tool.mouse_down(event.pos, self.sprites) if event.type == pygame.MOUSEBUTTONUP: # LMB if event.button == 1: self.lmb_tool.mouse_up(event.pos, self.sprites) # RMB if event.button == 3: self.rmb_tool.mouse_up(event.pos, self.sprites) if event.type == pygame.MOUSEMOTION: # LMB is pressed, update all the time to keep highlight working ## if event.buttons[0] == 1: self.lmb_tool.mouse_move(event.pos, self.sprites) # RMB is pressed, only update while RMB pressed if event.buttons[2] == 1: self.rmb_tool.mouse_move(event.pos, self.sprites) if self.lmb_tool.has_aoe_changed(): # Update the screen to reflect changes made by tools aoe = self.lmb_tool.get_last_aoe() + self.lmb_tool.get_aoe() self.update_world(aoe, self.lmb_tool.get_highlight()) self.lmb_tool.set_aoe_changed(False) self.lmb_tool.clear_aoe() #if self.rmb_tool.active(): if True: # Repaint the entire screen until something better is implemented self.paint_world() self.refresh_screen = 1 if self.lmb_tool.active(): # Repaint the entire screen until something better is implemented self.paint_world() self.refresh_screen = 1 # Write some useful info on the top bar self.fps_elapsed += self.clock.get_time() if self.fps_elapsed >= self.fps_refresh: self.fps_elapsed = 0 #pygame.display.set_caption("FPS: %i" % (self.clock.get_fps())) # Refresh the screen if necessary, or just draw the updated bits if self.refresh_screen: self.screen.fill(darkgreen) rectlist = self.sprites.draw(self.screen) if self.debug: for s in self.sprites.sprites(): s.CPGroup.draw(self.screen) pygame.display.update() self.refresh_screen = False else: for a in self.dirty: self.screen.fill(darkgreen, a) rectlist = self.sprites.draw(self.screen) if self.debug: for s in self.sprites.sprites(): s.CPGroup.draw(self.screen) pygame.display.update(self.dirty)
def update(self): if self.pause == False: c = self.charactors[ self.selected] # Only update the selected charactor # Tick over the charactors' timer c.dt = c.clock.tick() # Calculate charactor accelaration c.acc = self.max_acc * c.move # set accelaration along movement axis # Add in 'gravitational' accelaration for m in self.magnets: if m.side == self.selected: r = m.pos - c.pos r2 = r.x**2 + r.y**2 unit_normal = r / sqrt(r2) grav_acc = (self.grav_const * (m.mass / r2)) * unit_normal c.vel += grav_acc if r2 <= m.radius**2: c.absorbed = True c.tracker = 0 self.create_no = 10 c.life += -1 else: c.absorbed = False # Calculate charactor velocity c.vel += c.acc if c.vel.length > self.max_vel: # limit maximum velocity c.vel.length = self.max_vel new_pos = c.pos + c.vel # position after update # Collision with boundaries if new_pos.x >= self.right_limit[ self.selected] or new_pos.x <= self.left_limit[ self.selected]: c.vel.x = -c.vel.x if new_pos.y >= self.h or new_pos.y <= 0: c.vel.y = -c.vel.y # Calculate charactor posistion c.pos += c.vel c.rect.center = c.pos # Bounce magnets off the walls for m in self.magnets: new_pos = m.pos + m.vel if new_pos.x + m.radius >= self.right_limit[ m.side] or new_pos.x - m.radius <= self.left_limit[ m.side]: m.vel.x = -m.vel.x if new_pos.y + m.radius >= self.h or new_pos.y - m.radius <= 0: m.vel.y = -m.vel.y m.pos += m.vel # Create a bunch of particles each time step c.tracker += c.dt if c.tracker > c.create_rate: c.tracker = 0 angle = 0 position = c.pos.inttup() vel = c.vel / 1.5 velocity = vel.inttup() if c.life < 98: c.life += 3 if c.absorbed == False: for p in range(self.create_no): p = Particle(position) angle += 360 / (self.create_no) p.vel.rotate(angle) p.vel += vec2d(velocity) self.particles.append(p) # Limit particle life for p in self.particles: p.life += -1 p.pos += p.vel # Kill particles if they cross over the centre if p.pos.x < self.w / 2: if p.pos.x + p.vel.x >= self.w / 2: p.life = 0 elif p.pos.x > self.w / 2: if p.pos.x + p.vel.x <= self.w / 2: p.life = 0 # Add gravity effect for particles within a distance of a magnet. for m in self.magnets: if m.side == self.selected: r = m.pos - p.pos r2 = r.x**2 + r.y**2 # if r2 < self.grav_radius: unit_normal = r / sqrt(r2) grav_acc = (m.mass / r2) * unit_normal p.vel += grav_acc # Reduce score and stop particle production when player is absorbed if r2 <= m.radius**2: p.life = 0 m.life += -1 self.score += 1 + randint(0, 9) / 10.0 if self.create_no < 20: self.create_no += 1 if m.life == 0: self.score += 10 + randint(0, 9) / 10.0 angle = 0 + randint(0, 179) for t in range(3): position = m.pos.inttup() t = Tinie(position) t.vel.angle = angle t.side = self.selected angle += 180 self.tinies.append(t) # Resolve tinies velocity, if they exist if len(self.tinies) > 0: for t in self.tinies: if t.pos.y + t.vel.y >= self.h: t.vel.y = -t.vel.y if t.pos.y + t.vel.y <= 0: t.vel.y = -t.vel.y if t.pos.x + t.vel.x >= self.w: t.vel.x = -t.vel.x if t.pos.x + t.vel.x <= 0: t.vel.x = -t.vel.x if t.pos.x <= self.w / 2 and t.pos.x + t.vel.x > self.w / 2: t.vel.x = -t.vel.x if t.pos.x > self.w / 2 and t.pos.x + t.vel.x <= self.w / 2: t.vel.x = -t.vel.x t.pos += t.vel t.life += -1 # Turn tinies into magnets if self.tinies[0].life < 1: self.tinies = self.tinies[1:] for t in self.tinies: if t.life < 1: m = Magnet(choice([5, 10, 15, 20])) position = t.pos.inttup() velocity = t.vel.inttup() m.pos = vec2d(position) if m.pos.x > self.w / 2: m.side = 1 if self.w / 2 <= m.pos.x <= (self.w / 2 + m.radius): m.pos.x = self.w / 2 + m.radius elif (self.w / 2 - m.radius) < m.pos.x <= self.w / 2: m.pos.x = self.w / 2 - m.radius elif m.pos.x < m.radius: m.pos.x = m.radius elif m.pos.x > self.w - m.radius: m.pos.x = self.w - m.radius elif m.pos.y < m.radius: m.pos.y = m.radius elif m.pos.y > self.h - m.radius: m.pos.y = self.h - m.radius self.magnets.append(m) # Update particle and magnet list self.particles = [p for p in self.particles if p.life > 0] self.magnets = [m for m in self.magnets if m.life > 0] self.tinies = [t for t in self.tinies if t.life > 0] # Update score surface powerText = ('Power generated:') scoreText = (str(self.score) + ' kWh') self.power_surf = self.score_font.render(powerText, True, (88, 88, 88)) self.score_surf = self.score_font.render(scoreText, True, (180, 180, 180)) # Update life surface self.pulA_surf = self.score_font.render('Pulsar A:', True, (85, 20, 63)) self.pulB_surf = self.score_font.render('Pulsar B:', True, (0, 47, 113)) self.scoA_surf = self.score_font.render( str(self.charactors[0].life) + '%', True, (180, 180, 180)) self.scoB_surf = self.score_font.render( str(self.charactors[1].life) + '%', True, (180, 180, 180)) if c.life < 1: pygame.mixer.fadeout(2000) pygame.time.wait(2000) self.running = False self.saveScore() h = Highscore().mainLoop(40)
def _compute_direction(self): aim = self.target.rect self.direction = vec2d(aim[0] - self.pos[0], aim[1] - self.pos[1]).normalized()
def update(self, time_passed): if self.target.is_alive(): ##for creep in self.game.creeps: ##Collision = pygame.sprite.collide_circle(creep, self) #Collision detection with the tower's range ##if Collision: ##creep._decrease_health(self.tower.damage) ##self.kill() Collision = pygame.sprite.collide_circle( self.target, self) #Collision detection if Collision: if self.aoe: self.radius = self.aoe #self.radius is used by collide_circle below. Above, the collide_circle assumed a radius encompassing the projectile for enemy in self.game.creeps: if pygame.sprite.collide_circle( enemy, self) and enemy.id != self.target.id: enemy._decrease_health(self.tower.damage * self.aoefactor, attacker=self) if self.effects: if enemy.health > 0: for effect in self.effects: EffectDict[effect](enemy, self) enemy.effects[-1].CausedByAoE = True self.target._decrease_health(self.tower.damage, attacker=self) if self.effects: if self.target.health > 0: for effect in self.effects: EffectDict[effect](self.target, self) self.kill() else: self._compute_direction() self.target_mid = vec2d( (self.target.rect[0] - (self.target.width / 2)), (self.target.rect[1] - (self.target.width / 2))) self.mid_point = vec2d( (self.target.rect[0] - (self.target.width / 2)), (self.target.rect[1] - (self.target.width / 2))) remaining_distance = abs(self.target_mid - self.mid_point) if remaining_distance > self.speed * time_passed: displacement = vec2d( self.direction.x * self.speed * time_passed, self.direction.y * self.speed * time_passed) else: displacement = vec2d( self.direction.x * remaining_distance[0], self.direction.y * remaining_distance[1]) self.pos += displacement self.rect = Rect(self.pos[0], self.pos[1], self.width, self.height) self.image = pygame.transform.rotate(self.base_image, -self.direction.angle) self.age += time_passed if self.age > self.duration: self.kill() else: self.kill()
def mouseUp(self, button, pos): #pygame.draw.circle(self.screen, (0, 0, 0), pos, 20) #pygame.draw.circle(self.screen, (0, 0, 0), (pos[0], pos[1] + 20) , 20) self.target = vec2d( pos)
def __init__(self): print ("Initialisiere das Spiel...") self.w, self.h = 800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=(255, 255, 255)) self.size = [800,600] self.screen = pygame.display.set_mode(self.size) self.SpielerVec = vec2d(20, 20) #X Koordinate des Spielers (von links nach rechts)self.SpielerY = 20 Y Koordinate des Spielers (von oben nach unten) self.pos = vec2d(20,20) self.target = vec2d(20,20) self.drawcolor = (0, 0, 0) self.map = [0]*1000 def createList (self): #Generiert random Zahlen um die Map Random zu Generieren for i in range (0,1000): self.map[i] = random.randint(0,2) print(self.map) createList(self) if self.map[0] == 0: self.map[0] = 1 self.red = [255, 0, 0] self.blue = [0, 0, 255] self.myfont = pygame.font.SysFont("monospace", 20) self.Leveldesign = pygame.font.SysFont("monospace", 40) self.Ausdauerimg = pygame.image.load ("tilesets/EigeneBilder/Ausdauer.png") self.Verteidigungimg = pygame.image.load ("tilesets/EigeneBilder/Verteidigung.png") self.Staerkeimg = pygame.image.load ("tilesets/EigeneBilder/Staerke3.png") self.Geschicklichkeitimg = pygame.image.load ("tilesets/EigeneBilder/Geschicklichkeit.png") self.Magicimg = pygame.image.load ("tilesets/EigeneBilder/Magic.png") self.Attackimg1 = pygame.image.load ("tilesets/fegon/Attackboost.png") self.Attackimg2 = pygame.image.load ("tilesets/EigeneBilder/sword2.png") self.ItemSlots = pygame.image.load ("tilesets/EigeneBilder/itemslots.png") self.img1 = pygame.image.load("tilesets/derek/HeroBase.png") self.img2 = pygame.image.load("tilesets/derek/Dirt.png") self.img3 = pygame.image.load("tilesets/fegon/Wall.png") self.imgGolem = pygame.image.load("tilesets/fegon/Golem.png") self.imgVampire = pygame.image.load("tilesets/fegon/Vampire.png") self.imgGoblin = pygame.image.load("tilesets/fegon/Goblin.png") self.imgDragon = pygame.image.load("tilesets/fegon/Dragon.png") self.Mob1Liste = [0]*11 self.Mob2Liste = [0]*11 self.Mob3Liste = [0]*11 self.Mob4Liste = [0]*11 self.Mob5Liste = [0]*11 self.Mob6Liste = [0]*11 self.Mob7Liste = [0]*11 self.Mob8Liste = [0]*11 self.Mob1inventory1 = [0] * 13 self.Mob1inventory2 = [0] * 13 self.Mob2inventory1 = [0] * 13 self.Mob2inventory2 = [0] * 13 self.Mob3inventory1 = [0] * 13 self.Mob3inventory2 = [0] * 13 self.Mob4inventory1 = [0] * 13 self.Mob4inventory2 = [0] * 13 self.Mob5inventory1 = [0] * 13 self.Mob5inventory2 = [0] * 13 self.Mob6inventory1 = [0] * 13 self.Mob6inventory2 = [0] * 13 self.Mob7inventory1 = [0] * 13 self.Mob7inventory2 = [0] * 13 self.Mob8inventory1 = [0] * 13 self.Mob8inventory1 = [0] * 13 self.anzahlMobs = 5 self.Mob1Liste[0] = random.randint (1,8) self.Mob1Liste[1] = random.randint(1, 4) self.Mob1Liste[2] = self.Mob1Liste[0]* self.Mob1Liste[0]*self.Mob1Liste[1] self.Mob1Liste[3] = self.Mob1Liste[2] self.Mob1Liste[4] = random.randint(1, self.Mob1Liste[0]) * self.Mob1Liste[0] + random.randint (0,5) self.Mob1Liste[5] = 0 self.Mob1Liste[6] = random.randint(1, self.Mob1Liste[0]) * self.Mob1Liste[0] + random.randint (0,5) self.Mob1Liste[7] = random.randint(1, self.Mob1Liste[0]) * self.Mob1Liste[0] + random.randint (0,5) self.Mob1Liste[8] = random.randint(1, self.Mob1Liste[0]) * self.Mob1Liste[0] + random.randint (0,5) self.Mob1Liste[9] = random.randint(1, self.Mob1Liste[0]) * self.Mob1Liste[0] + random.randint (0,5) self.Mob1pos = vec2d(random.randint(1,28), random.randint(1, 28)) while self.map [(self.Mob1pos[1]-1)* 28 + self.Mob1pos[0] - 1] <= 0 or self.map [(self.Mob1pos[1]-1)* 28 + self.Mob1pos[0] - 1] > 10: # or self.Mob1pos == 0: self.Mob1pos = vec2d(random.randint (1, 28), random.randint(1, 28)) self.map[(self.Mob1pos[1]-1)*28+self.Mob1pos[0] - 1] = 10 + self.Mob1Liste[1] self.Mob2Liste[0] = random.randint (1,8) self.Mob2Liste[1] = random.randint(1, 4) self.Mob2Liste[2] = self.Mob2Liste[0]* self.Mob2Liste[0]*self.Mob2Liste[1] self.Mob2Liste[3] = self.Mob2Liste[2] self.Mob2Liste[4] = random.randint(1, self.Mob2Liste[0]) * self.Mob2Liste[0] + random.randint (0,5) self.Mob2Liste[5] = 0 self.Mob2Liste[6] = random.randint(1, self.Mob2Liste[0]) * self.Mob2Liste[0] + random.randint (0,5) self.Mob2Liste[7] = random.randint(1, self.Mob2Liste[0]) * self.Mob2Liste[0] + random.randint (0,5) self.Mob2Liste[8] = random.randint(1, self.Mob2Liste[0]) * self.Mob2Liste[0] + random.randint (0,5) self.Mob2Liste[9] = random.randint(1, self.Mob2Liste[0]) * self.Mob2Liste[0] + random.randint (0,5) self.Mob2pos = vec2d(random.randint(1, 28), random.randint(1, 28)) while self.map [(self.Mob2pos[1]-1) *28 + self.Mob2pos[0] - 1] <= 0 or self.map [(self.Mob2pos[1]-1) *28 + self.Mob2pos[0] - 1] > 10: # or self.Mob2pos == 0: self.Mob2pos = vec2d(random.randint(1, 28), random.randint(1, 28)) self.map[(self.Mob2pos[1]-1)*28 + self.Mob2pos[0] - 1] = 10 + self.Mob2Liste[1] self.Mob3Liste[0] = random.randint (1,8) self.Mob3Liste[1] = random.randint (1, 4) self.Mob3Liste[2] = self.Mob3Liste[0]* self.Mob3Liste[0]*self.Mob1Liste[1] self.Mob3Liste[3] = self.Mob3Liste[2] self.Mob3Liste[4] = random.randint(1, self.Mob3Liste[0]) * self.Mob3Liste[0] + random.randint (0,5) self.Mob3Liste[5] = 0 self.Mob3Liste[6] = random.randint(1, self.Mob3Liste[0]) * self.Mob3Liste[0] + random.randint (0,5) self.Mob3Liste[7] = random.randint(1, self.Mob3Liste[0]) * self.Mob3Liste[0] + random.randint (0,5) self.Mob3Liste[8] = random.randint(1, self.Mob3Liste[0]) * self.Mob3Liste[0] + random.randint (0,5) self.Mob3Liste[9] = random.randint(1, self.Mob3Liste[0]) * self.Mob3Liste[0] + random.randint (0,5) self.Mob3pos = vec2d(random.randint(1, 28), random.randint(1, 28)) while self.map[(self.Mob3pos[1]-1) *28+ self.Mob3pos[0] - 1] <= 0 or self.map[(self.Mob3pos[1]-1) *28+ self.Mob3pos[0] - 1] > 10: # or self.Mob3pos == 0: self.Mob3pos = vec2d(random.randint(1, 28), random.randint(1, 28)) self.map[(self.Mob3pos[1]-1)*28 + self.Mob3pos[0] - 1] = 10 + self.Mob3Liste[1] self.Mob4Liste[0] = random.randint (1,8) self.Mob4Liste[1] = random.randint(1, 4) self.Mob4Liste[2] = self.Mob4Liste[0]* self.Mob4Liste[0]*self.Mob4Liste[1] self.Mob4Liste[3] = self.Mob4Liste[2] self.Mob4Liste[4] = random.randint(1, self.Mob4Liste[0]) * self.Mob4Liste[0] + random.randint (0,5) self.Mob4Liste[5] = 0 self.Mob4Liste[6] = random.randint(1, self.Mob4Liste[0]) * self.Mob4Liste[0] + random.randint (0,5) self.Mob4Liste[7] = random.randint(1, self.Mob4Liste[0]) * self.Mob4Liste[0] + random.randint (0,5) self.Mob4Liste[8] = random.randint(1, self.Mob4Liste[0]) * self.Mob4Liste[0] + random.randint (0,5) self.Mob4Liste[9] = random.randint(1, self.Mob4Liste[0]) * self.Mob4Liste[0] + random.randint (0,5) self.Mob4pos = vec2d(random.randint (1, 28), random.randint(1, 28)) while self.map [(self.Mob4pos[1]-1) *28+ self.Mob4pos[0] - 1] <= 0 or self.map [(self.Mob4pos[1]-1) *28+ self.Mob4pos[0] - 1] > 10: # or self.Mob4pos == 0: self.Mob4pos = vec2d(random.randint (1, 28), random.randint(1, 28)) self.map[(self.Mob4pos[1]-1)*28 + self.Mob4pos[0] - 1] = 10 + self.Mob4Liste[1] self.Mob5Liste[0] = random.randint (1,8) self.Mob5Liste[1] = random.randint(1, 4) self.Mob5Liste[2] = self.Mob5Liste[0]* self.Mob5Liste[0]*self.Mob5Liste[1] self.Mob5Liste[3] = self.Mob5Liste[2] self.Mob5Liste[4] = random.randint(1, self.Mob5Liste[0]) * self.Mob5Liste[0] + random.randint (0,5) self.Mob5Liste[5] = 0 self.Mob5Liste[6] = random.randint(1, self.Mob5Liste[0]) * self.Mob5Liste[0] + random.randint (0,5) self.Mob5Liste[7] = random.randint(1, self.Mob5Liste[0]) * self.Mob5Liste[0] + random.randint (0,5) self.Mob5Liste[8] = random.randint(1, self.Mob5Liste[0]) * self.Mob5Liste[0] + random.randint (0,5) self.Mob5Liste[9] = random.randint(1, self.Mob5Liste[0]) * self.Mob5Liste[0] + random.randint (0,5) self.Mob5pos = vec2d(random.randint (1, 28), random.randint(1, 28)) while self.map [(self.Mob5pos[1]-1) *28+ self.Mob5pos[0] - 1] <= 0 or self.map [(self.Mob5pos[1]-1) *28+ self.Mob5pos[0] - 1] > 10: # or self.Mob4pos == 0: self.Mob5pos = vec2d(random.randint (1, 28), random.randint(1, 28)) self.map[(self.Mob5pos[1]-1)*28 + self.Mob5pos[0] - 1] = 10 + self.Mob5Liste[1] self.Mob6Liste[0] = random.randint (1,8) self.Mob6Liste[1] = random.randint(1, 4) self.Mob6Liste[2] = self.Mob6Liste[0]* self.Mob6Liste[0]*self.Mob6Liste[1] self.Mob6Liste[3] = self.Mob6Liste[2] self.Mob6Liste[4] = random.randint(1, self.Mob6Liste[0]) * self.Mob6Liste[0] + random.randint (0,5) self.Mob6Liste[5] = random.randint(1, self.Mob6Liste[0]) * self.Mob6Liste[0] + random.randint (0,5) self.Mob6Liste[6] = random.randint(1, self.Mob6Liste[0]) * self.Mob6Liste[0] + random.randint (0,5) self.Mob6Liste[7] = random.randint(1, self.Mob6Liste[0]) * self.Mob6Liste[0] + random.randint (0,5) self.Mob6pos = vec2d(random.randint (1, 28), random.randint(1, 28)) while self.map [(self.Mob6pos[1]-1) *28+ self.Mob6pos[0] - 1] <= 0 or self.map [(self.Mob6pos[1]-1) *28+ self.Mob6pos[0] - 1] <= 0 > 10: # or self.Mob4pos == 0: self.Mob6pos = vec2d(random.randint (1, 28), random.randint(1, 28)) self.map[(self.Mob6pos[1]-1)*28 + self.Mob6pos[0] - 1] = 10 + self.Mob6Liste[1] self.Mob7Liste[0] = random.randint (1,8) self.Mob7Liste[1] = random.randint(1, 4) self.Mob7Liste[2] = self.Mob7Liste[0]* self.Mob7Liste[0]*self.Mob7Liste[1] self.Mob7Liste[3] = self.Mob7Liste[2] self.Mob7Liste[4] = random.randint(1, self.Mob7Liste[0]) * self.Mob7Liste[0] + random.randint (0,5) self.Mob7Liste[5] = 0 self.Mob7Liste[6] = random.randint(1, self.Mob7Liste[0]) * self.Mob7Liste[0] + random.randint (0,5) self.Mob7Liste[7] = random.randint(1, self.Mob7Liste[0]) * self.Mob7Liste[0] + random.randint (0,5) self.Mob7Liste[8] = random.randint(1, self.Mob7Liste[0]) * self.Mob7Liste[0] + random.randint (0,5) self.Mob7Liste[9] = random.randint(1, self.Mob7Liste[0]) * self.Mob7Liste[0] + random.randint (0,5) self.Mob7pos = vec2d(random.randint (1, 28), random.randint(1, 28)) while self.map [(self.Mob7pos[1]-1) *28+ self.Mob7pos[0] - 1] <= 0 or self.map [(self.Mob7pos[1]-1) *28+ self.Mob7pos[0] - 1] > 10: # or self.Mob4pos == 0: self.Mob7pos = vec2d(random.randint (1, 28), random.randint(1, 28)) self.map[(self.Mob7pos[1]-1)*28 + self.Mob7pos[0] - 1] = 10 + self.Mob7Liste[1] self.Mob8Liste[0] = random.randint (1,8) self.Mob8Liste[1] = random.randint(1, 4) self.Mob8Liste[2] = self.Mob8Liste[0]* self.Mob8Liste[0]*self.Mob8Liste[1] self.Mob8Liste[3] = self.Mob8Liste[2] self.Mob8Liste[4] = random.randint(1, self.Mob8Liste[0]) * self.Mob8Liste[0] + random.randint (0,5) self.Mob8Liste[5] = 0 self.Mob8Liste[6] = random.randint(1, self.Mob8Liste[0]) * self.Mob8Liste[0] + random.randint (0,5) self.Mob8Liste[7] = random.randint(1, self.Mob8Liste[0]) * self.Mob8Liste[0] + random.randint (0,5) self.Mob8Liste[8] = random.randint(1, self.Mob8Liste[0]) * self.Mob8Liste[0] + random.randint (0,5) self.Mob8Liste[9] = random.randint(1, self.Mob8Liste[0]) * self.Mob8Liste[0] + random.randint (0,5) self.Mob8pos = vec2d(random.randint (1, 28), random.randint(1, 28)) while self.map [(self.Mob8pos[1]-1) *28+ self.Mob8pos[0] - 1] <= 0 or self.map [(self.Mob8pos[1]-1) *28+ self.Mob8pos[0] - 1] > 10: # or self.Mob4pos == 0: self.Mob8pos = vec2d(random.randint (1, 28), random.randint(1, 28)) self.map[(self.Mob8pos[1]-1)*28 + self.Mob8pos[0] - 1] = 10 + self.Mob8Liste[1] print (self.Mob1pos) print (self.Mob2pos) print (self.Mob3pos) print (self.Mob4pos) print (self.Mob5pos) print (self.Mob6pos) print (self.Mob7pos) print (self.Mob8pos) print (self.Mob1Liste) print (self.Mob2Liste) print (self.Mob3Liste) print (self.Mob4Liste) print (self.Mob5Liste) print (self.Mob6Liste) print (self.Mob7Liste) print (self.Mob8Liste) print (self.map) self.MobimFocus = 0 self.SpielerListe = [0] * 30 self.SpielerListe[0] = 1 self.SpielerListe[1] = 1 self.SpielerListe[2] = "Hero" self.SpielerListe[3] = 0 self.SpielerListe[4] = 10 self.SpielerListe[5] = 10 self.SpielerListe[6] = 5 self.SpielerListe[7] = 5 self.SpielerListe[8] = 5 self.SpielerListe[9] = 5 self.SpielerListe[10] = 5 self.SpielerListe[11] = 5 self.SpielerListe[12] = 10 self.SpielerListe[13] = 10 self.Spielerinventory1 = 15 * [0] self.Spielerinventory2 = 15 * [0] self.Spielerinventory3 = 15 * [0] self.Spielerinventory4 = 15 * [0] self.Spielerinventory5 = 15 * [0] self.Spielerinventory6 = 15 * [0] self.Spielerinventory7 = 15 * [0] self.Spielerinventory8 = 15 * [0] self.Spielerinventory9 = 15 * [0] self.Spielerinventory10 = 15 * [0] print ("Initialisierung abgeschlossen")
def draw(self): """draw all springs and nodes""" white = (255, 255, 255) black = (0, 0, 0) self.screen.fill(white) arc_dict = {} rect = pygame.Rect((0, 0), (30, self.w)) legend = 'p-toggle physics ' if self.physics: legend += 'off' else: legend += 'on' legend += ' || <Esc>-quit || n-randomize positions || d-delete node' self.font_mgr.Draw(self.screen, 'arial', 12, legend, rect, black, 'left', 'top', True) for s in self.springs: arc_dict[(s.n1.label, s.n2.label)] = s s.compute_coordinates() s.draw(self.screen) for n in self.nodes: #pygame.draw.circle(self.screen, white, n.x.inttup(), n.radius, 0) pygame.draw.circle(self.screen, black, n.x.inttup(), n.radius, 1) rect = pygame.Rect( (n.x - vec2d(n.radius / 2, n.radius / 2)).inttup(), (n.radius, n.radius)) self.font_mgr.Draw(self.screen, 'arial', 24, n.label, rect, black, 'center', 'center', True) for s_act, outsets in self.outsets.iteritems(): radius = 30 #level = defaultdict(int) sorted_outsets = sorted(outsets, key=len) last_single = True for outset in sorted_outsets: #max_level = max([level[t_act] for t_act in outset]) points = [] if last_single and len(outset) > 1: radius += 10 for t_act in outset: #level[t_act] += 1 arc = arc_dict[(s_act, t_act)] circle_center = arc.n1.x #inter = line_circle_intersection( arc, circle_center, radius+max_level*10.0 ) inter = line_circle_intersection(arc, circle_center, radius, inset=False) points.append(inter) pygame.draw.circle(self.screen, black, inter.inttup(), 5, 0) #pygame.gfxdraw.aacircle(self.screen, inter.inttup(), 5, black) draw_binding(self.screen, circle_center, points) if len(outset) > 1: last_single = False radius += 10 for t_act, insets in self.insets.iteritems(): radius = 35 #level = defaultdict(int) sorted_insets = sorted(insets, key=len) last_single = True for inset in sorted_insets: #max_level = max([level[s_act] for s_act in inset]) points = [] if last_single and len(inset) > 1: radius += 10 for s_act in inset: #level[s_act] += 1 arc = arc_dict[(s_act, t_act)] circle_center = arc.n2.x #inter = line_circle_intersection( arc, arc.n2.x, radius+max_level*10.0 ) inter = line_circle_intersection(arc, circle_center, radius, inset=True) points.append(inter) pygame.draw.circle(self.screen, black, inter.inttup(), 5, 0) draw_binding(self.screen, circle_center, points) if len(inset) > 1: last_single = False radius += 10 #draw insets and outsets pygame.display.flip()
def update(self, update_type=0): """""" vpad = vec2d(self.ep_size, self.ep_size) self.image = pygame.Surface((self.width + vpad.x * 2, self.height + vpad.y * 2)) # Either draw the background blue, or don't if self.transparency: self.image.fill(transparent) else: self.image.fill(blue) # Draw control lines for endpoints pygame.draw.line(self.image, green, self.CPDict[self.eps[0]].position - self.position + vpad, self.CPDict[self.eps[1]].position - self.position + vpad) pygame.draw.line(self.image, green, self.CPDict[self.eps[2]].position - self.position + vpad, self.CPDict[self.eps[3]].position - self.position + vpad) # Draw control handles for p in self.CPDict.values(): q = p.position - self.position + vpad pygame.draw.circle(self.image, red, (int(q.x), int(q.y)), self.ep_size) control_points = [] for p in self.eps: control_points.append(self.CPDict[p].position - self.position + vpad) # Draw the bezier curve itself cps, tangents = self.bezier.calculate_bezier(control_points, 30) pygame.draw.lines(self.image, white, False, cps, 1) for p in cps: pygame.draw.circle(self.image, red, p, 1) # Draw a dot which moves along the curve l = (pygame.time.get_ticks() - self.time) * self.speed self.time = pygame.time.get_ticks() self.length = self.bezier.get_length(cps) self.dot_pos += l * self.movement if self.dot_pos > self.length: self.dot_pos = self.length - (self.dot_pos - self.length) self.movement = -1 elif self.dot_pos < 0: self.dot_pos = self.dot_pos * -1 self.movement = 1 # Draw a spot at some arbitrary length p = self.bezier.get_point_at_length(cps, self.dot_pos) pygame.draw.circle(self.image, yellow, p, 3) # Set transparency self.image.set_colorkey(transparent) # Finally call update on all child CPSprites, to align their positions for p in self.CPDict.values(): p.update() # And then call update on all child shapes to update their positions # based on the position of this shape for p in self.children: p.update_endpoint("move", None)