class TankPlayer(Player): ''' classdocs ''' def __init__(self, x,y,width,height,vx,vy): Player.__init__(self,x,y,width,height,vx,vy) self.sprite = sprite_class("./sprites/tank.bmp",526,64,8,1) self.sprite.play(True) self.sprite.set_animation_delay(100) self.sprite.set_animation_frame(1) self.sprite.set_image_color_key(255, 0, 255) self.sprite.scale_sprite(1) self.dimensions.x = self.sprite.get_width() self.dimensions.y = self.sprite.get_height() self.colBoxAnchorOffset = Vector2(0,0) #since we have no art, this can be 0,0 self.collisionBox = CollisionManager.buildCollisionBox(self.position.x + self.colBoxAnchorOffset.x, self.position.y + self.colBoxAnchorOffset.y, self.dimensions.x,self.dimensions.y, self) self.equipedGun = MachineGun(Vector2(self.position.x + self.dimensions.x/2, self.position.y + self.dimensions.y/2), Vector2(1,1)) self.facing = Vector2(0,0) self.gunOrigin = Vector2(0,0) self.color = Color.cyan
def __init__(self): """ Initialize the Graph """ self.nodes = [] # Set of nodes self.obstacles = [] # Set of obstacles - used for collision detection # Initialize the size of the graph based on the world size self.gridWidth = int(Constants.WORLD_WIDTH / Constants.GRID_SIZE) self.gridHeight = int(Constants.WORLD_HEIGHT / Constants.GRID_SIZE) # Create grid of nodes for i in range(self.gridHeight): row = [] for j in range(self.gridWidth): node = Node( i, j, Vector2(Constants.GRID_SIZE * j, Constants.GRID_SIZE * i), Vector2(Constants.GRID_SIZE, Constants.GRID_SIZE)) row.append(node) self.nodes.append(row) ## Connect to Neighbors for i in range(self.gridHeight): for j in range(self.gridWidth): # Add the top row of neighbors if i - 1 >= 0: # Add the upper left if j - 1 >= 0: self.nodes[i][j].neighbors += [ self.nodes[i - 1][j - 1] ] # Add the upper center self.nodes[i][j].neighbors += [self.nodes[i - 1][j]] # Add the upper right if j + 1 < self.gridWidth: self.nodes[i][j].neighbors += [ self.nodes[i - 1][j + 1] ] # Add the center row of neighbors # Add the left center if j - 1 >= 0: self.nodes[i][j].neighbors += [self.nodes[i][j - 1]] # Add the right center if j + 1 < self.gridWidth: self.nodes[i][j].neighbors += [self.nodes[i][j + 1]] # Add the bottom row of neighbors if i + 1 < self.gridHeight: # Add the lower left if j - 1 >= 0: self.nodes[i][j].neighbors += [ self.nodes[i + 1][j - 1] ] # Add the lower center self.nodes[i][j].neighbors += [self.nodes[i + 1][j]] # Add the lower right if j + 1 < self.gridWidth: self.nodes[i][j].neighbors += [ self.nodes[i + 1][j + 1] ]
def __init__(self, x, y, width, height, vx, vy): Player.__init__(self, x, y, width, height, vx, vy) self.sprite = sprite_class("./sprites/spearGuy.png", 832, 1344, 13, 21) self.sprite.play(True) self.sprite.set_animation_delay(100) #self.sprite.set_animation_range(40,80) self.sprite.create_animation("walkUp", 105, 113, 100) self.sprite.create_animation("walkLeft", 118, 126, 100) self.sprite.create_animation("walkDown", 131, 139, 100) self.sprite.create_animation("walkRight", 144, 152, 100) self.sprite.create_animation("idle", 130, 130, 500) self.sprite.set_animation_frame(1) self.sprite.set_image_color_key(255, 0, 255) self.sprite.scale_sprite(1) self.dimensions.x = self.sprite.get_width() self.dimensions.y = self.sprite.get_height() self.colBoxAnchorOffset = Vector2( 0, 0) #since we have no art, this can be 0,0 self.collisionBox = CollisionManager.buildCollisionBox( self.position.x + self.colBoxAnchorOffset.x, self.position.y + self.colBoxAnchorOffset.y, self.dimensions.x, self.dimensions.y, self) self.equipedGun = MachineGun( Vector2(self.position.x + self.dimensions.x / 2, self.position.y + self.dimensions.y / 2), Vector2(1, 1)) self.facing = Vector2(0, 0) self.gunOrigin = Vector2(0, 0) self.color = Color.cyan
def funnel_point_edge( self, pt ): i = 0 for ps in self.path_steps: if pt.xy() == ps.edge_in[0] or pt.xy() == ps.edge_in[1]: return (Vector2.Vector2( *ps.edge_in[0] ),Vector2.Vector2( *ps.edge_in[1] )),i i += 1 return None,None
def __init__(self, x, y, mass): self.position = Vector2(x, y) self.velocity = Vector2(0, 0) self.acceleration = Vector2(0, 0) self.mass = mass self.r = mass * 10 self.c = None
def __init__(self, accValue=100, maxSpeed=200, decValue=100): self.positionVector = Vector2() self.velocityVector = Vector2() self.accelerationVector = Vector2() self.accelerationValue = accValue self.maximumSpeed = maxSpeed self.decelerationValue = decValue
def corners(self, Mcs: Matrix2.Matrix2, camPosition: Vector2.Vector2) -> typing.List[Vector2.Vector2]: ''' Computes the corner of the window in the world coordinates ''' worldTR = Mcs.inv(diag = True) * Vector2.Vector2(1, 1) + camPosition worldLL = Mcs.inv(diag = True) * Vector2.Vector2(-1, -1) + camPosition return worldTR, worldLL
def getCornersRange(self,p, r): v1 = Vector2.Vector2(p[0],p[1]) points = [] for p2 in self.getCorners(): v2 = Vector2.Vector2(p2[0],p2[1]) if v2.distance(v1) <= r: points.append(p2) return points
def render(self, Mcp: Matrix2.Matrix2, Mps: Matrix2.Matrix2, Mcs: Matrix2.Matrix2, camPosition: Vector2.Vector2) -> None: ''' Renders the grid on screen ''' Mcs_inv = Mcs.inv(diag=True) worldLL = Mcs.inv(diag=True) * screenLL + camPosition screenA = Mcs * worldA startX = (Mcs * (Vector2.Vector2(math.ceil(worldLL.x), worldLL.y) - camPosition)).x # metti a posto ghisbiro startY = ( Mcs * (Vector2.Vector2(worldLL.x, math.ceil(worldLL.y)) - camPosition)).y xA, yA = screenA.x, screenA.y # this guys are x and y units in the screen reference currentPos: float = startX currentRealPos: float = math.ceil(worldLL.x) while currentPos <= 1: if self.verbose: Text.renderToScreen(currentPos + .01, -.99, f'{currentRealPos}') OpenGL.GL.glBegin(OpenGL.GL.GL_LINES) OpenGL.GL.glColor3d(self.GRID_COLOR[0], self.GRID_COLOR[1], self.GRID_COLOR[2]) OpenGL.GL.glVertex3d(currentPos, -1, .2) OpenGL.GL.glVertex3d(currentPos, 1, .2) OpenGL.GL.glEnd() currentPos += xA currentRealPos += 1 currentPos = startY currentRealPos: float = math.ceil(worldLL.y) while currentPos <= 1: if self.verbose: Text.renderToScreen(-.99, currentPos + .01, f'{currentRealPos}') OpenGL.GL.glBegin(OpenGL.GL.GL_LINES) OpenGL.GL.glColor3d(self.GRID_COLOR[0], self.GRID_COLOR[1], self.GRID_COLOR[2]) OpenGL.GL.glVertex3d(-1, currentPos, .2) OpenGL.GL.glVertex3d(1, currentPos, .2) OpenGL.GL.glEnd() currentPos += yA currentRealPos += 1
def renderNextShape(self, surface): """Renders the next shape inside of a box to the right side of the grid.""" wh = Vector2(self.width, self.height) * BLOCKSIZE swh = Vector2(*SCREENSIZE) posTopLeft = (swh - wh) / 2 surf = self.drawShapeInBox(self.nextShape) surface.blit(surf, round(posTopLeft + Vector2(wh[0] + BLOCKSIZE, BLOCKSIZE)))
def moveShape(self, x, y): """Moves self to x, y if we are allowed to.""" # If we are allowed to move to this position, if self.canMove(x, y): # Change our position to the new position self.location += Vector2(x, y) # For each of our blocks, update their position for block in self.blocks: block.location += Vector2(x, y)
def intersection(self, edge_sig): e0, e1 = Vector2.edge_from_sig(edge_sig) ip = None if len(self.funnel_points) > 0: ip = Vector2.segment_intersect(self.start, self.funnel_points[0], e0, e1) elif len(self.path_steps) > 0: ip = Vector2.segment_intersect(self.start, self.end, e0, e1) return ip
def intersection( self, edge_sig ): e0,e1 = Vector2.edge_from_sig( edge_sig ) ip = None if len(self.funnel_points) > 0: ip = Vector2.segment_intersect( self.start, self.funnel_points[0], e0, e1 ) elif len( self.path_steps ) > 0: ip = Vector2.segment_intersect( self.start, self.end, e0, e1 ) return ip
def __init__(self, position: Vector2 = nullVector2, dir: Vector2 = Vector2(-1, 1)) -> None: Entity.__init__(self, position, Vector2(1, 1), 'O', 'Ball') self.dir = dir self.speed = 1 self.maxspeed = 1.5 self.grabbed = False self.thrumode = False
def __init__(self, grid, shapeId, xy): self.grid = grid self.shapeId = shapeId self.location = Vector2(*xy) self.startLoc = Vector2(*xy) self.blocks = [ Block(pos + self.startLoc, shapeId.color) for pos in self.shapeId.blockPositions ] self.dead = False
def right_endpoint_in( self, pt ): e0 = Vector2.Vector2(*self.edge_in[0]) e1 = Vector2.Vector2(*self.edge_in[1]) ws = winding_sign( e0.sub( pt ), e1.sub( pt ) ) #assert ws != 0, "Right endpoint call on colinear line %s, %s" % (pt,self.edge_in) if ws == 1: # goes right to left return e0 else: return e1
def getMinTranslationVector(self, other): differences = [ Vector2(self.left - other.right, 0), # displacement to the left Vector2(self.right - other.left, 0), # right Vector2(0, self.top - other.bottom), # top Vector2(0, self.bottom - other.top) # bottom ] # sort list in place (no returned list); # requires key function that transforms object in comparable data differences.sort(key=Vector2.getLength) return differences[0]
def calculateAimingVector(self): mousePos = Vector2(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]) midPoint = Vector2(self.position.x + self.dimensions.x / 2, self.position.y + self.dimensions.y / 2) vector = Vector2(mousePos.x - midPoint.x, mousePos.y - midPoint.y) if (vector.x != 0 or vector.y != 0): size = math.sqrt(vector.x**2 + vector.y**2) self.facing.x = vector.x / size self.facing.y = vector.y / size
def next_waypoint( self, mid=False, displacement=0.0, train=False ): if self.index == -1: # no more path if train: return None,None,None else: return None if self.index == len( self.path_steps ): # last one, return end point self.index = -1 if train: return self.end,self.end,None return self.end # get next edge p1,p2 = self.path_steps[self.index].edge_in self.index += 1 e1 = Vector2.Vector2( *p1 ) e2 = Vector2.Vector2( *p2 ) if mid: # return midpoint path, for visualization return e1.add( e2.sub( e1 ).scale( 0.5 ) ) # set fp to funnel point on next edge if self.findex == len(self.funnel_points): nextf = self.end else: nextf = self.funnel_points[self.findex] if nextf.xy() == e1.xy() or nextf.xy() == e2.xy(): # at the funnel point edge, return and advance fp = nextf self.findex += 1 else: # otherwise get the intersection with the edge if self.findex > 0: lastf = self.funnel_points[self.findex-1] else: lastf = self.start fp = Vector2.intersection( lastf, nextf, e1, e2 ) # need midpoint for direction of displacement mp = e1.add( e2.sub( e1 ).scale( 0.5 ) ) if train: return fp,mp,(e1,e2) if displacement == 0: return fp disp = mp.sub( fp ).normalize().scale( displacement ) return fp.add( disp )
def __init__(self, x, y, width, height, vx, vy): Player.__init__(self, x, y, width, height, vx, vy) self.colBoxAnchorOffset = Vector2( 0, 0) #since we have no art, this can be 0,0 self.collisionBox = CollisionManager.buildCollisionBox( self.position.x + self.colBoxAnchorOffset.x, self.position.y + self.colBoxAnchorOffset.y, width, height, self) self.equipedGun = MachineGun( Vector2(self.position.x + self.dimensions.x / 2, self.position.y + self.dimensions.y / 2), Vector2(1, 1)) self.facing = Vector2(0, 0) self.gunOrigin = Vector2(0, 0) self.color = Color.cyan
def renderHeldShape(self, surface): """Renders the held shape inside of a box to the left side of the grid.""" # Get the width and height of ourselves and the screen wh = Vector2(self.width, self.height) * BLOCKSIZE swh = Vector2(*SCREENSIZE) # Get the position of the top left corner of our grid image posTopLeft = (swh - wh) / 2 # Get a surface of our shape in a box surf = self.drawShapeInBox(self.heldShape) # Copy the shape in a box to the right position. # Position is to the right of the grid by one block and down by a block surface.blit(surf, round(posTopLeft + Vector2(-BLOCKSIZE * 5, BLOCKSIZE)))
def handleInput(self, event): if event.type == pygame.MOUSEBUTTONUP: x, y = event.pos if self.clickable and self.active and self.is_inside( Vector2.Vector2(x, y)): pygame.mouse.set_cursor(*pygame.cursors.arrow) self.clickEvent() elif event.type == pygame.MOUSEMOTION: x, y = event.pos if self.active and self.clickable and self.is_inside( Vector2.Vector2(x, y)): self.hovering = True else: self.hovering = False
def contains_line( self, start, end ): for i in range(len(self.path_steps)-1,0,-1): ps = self.path_steps[i] # see if this is the edge that start is on if start.xy() in ps.edge_in: # made it, must be true return True #print "...contains check on %s" % (ps.edge_in,) if Vector2.segment_intersect( start, end,\ Vector2.Vector2(*ps.edge_in[0]),\ Vector2.Vector2(*ps.edge_in[1]) ) is None: return False # never found start, false return False
def __init__(self,screen ): pygame.sprite.Sprite.__init__(self) self.image,self.rect = load_image('tank.png',-1) self.shoot_sound = load_sound('shoot.wav') self.lives = 3 #test position self.pos = Vector2(100,100) self.screen = screen self.element_width = self.element_height = 32 self.render_area = ((0,0),(32,32)) #the flag to swap the tank rendering in the same direction self.render_swap_flag = True self.direction = Vector2(1,0) self.speed = 2 self.bullet = None
def drawTest(self, Mcs: Matrix2.Matrix2, camPosition: Vector2.Vector2) -> typing.List[Vector2.Vector2]: ''' Computes the corner of the window in the world coordinates ''' worldTR = Mcs.inv(diag=True) * Vector2.Vector2(1, 1) + camPosition worldLL = Mcs.inv(diag=True) * Vector2.Vector2(-1, -1) + camPosition if (self.minX >= worldTR.x or self.maxX <= worldLL.x or self.minY >= worldTR.y or self.maxY <= worldLL.y): return 'failed' else: return self.toScreen(self.x, self.y, Mcs, camPosition)
def draw(self, board: Board, dir: Vector2 = None) -> list: pos = Vector2(0, 0) pos.y = math.floor(self.position.y) pos.x = math.ceil(self.position.x) size = math.ceil(self.size) border = math.ceil(board.size) scanner = pos.y for h in range(size.y): if (0 <= scanner < board.size.y): line = self.sprite[scanner-pos.y] if (pos.x < border.x and (pos+size).x > 0): # Draw # x1 : index of str in line to start x1 = max(0, -pos.x) # x2 : index of str in line to end before x2 = min(size.x, (border-pos).x) # dx1 : index of str in board[y] to start dx1 = max(0, pos.x) # dx2 : index of str in board[y] to end before dx2 = min(border.x, (pos+size).x) board.board[scanner] = board.board[scanner][:dx1] + \ line[x1:x2] + board.board[scanner][dx2:] else: # dont draw pass scanner += 1
def __init__(self, screen): #be sure to call the base initializer before adding to Group pygame.sprite.Sprite.__init__(self) self.screen = screen self.image, self.rect = load_image('enemytank.png', -1) self.pos = Vector2(100, 100) self.direction = Vector2(1, 0) self.speed = 3 self.move_direction = 0 self.element_width = 32 self.element_height = 32 self.render_area = ((0, 0), (self.element_width, self.element_height)) self.render_swap_flag = True
def __init__(self, boundary): # Set the boundary rectangle. self.boundary = boundary # Set the radius and velocity. self.radius = random.randint(50, 125) self.velocity = Vector2.Vector2(random.randint(10, 12), random.randint(10, 12)) # The bad circle is supposed to be black, so.... self.color = Colors.Black # Randomly invert the velocity. if random.randint(0, 1) == 0: self.velocity.x *= -1 if random.randint(0, 1) == 1: self.velocity.y *= -1 # Set the center of the circle to be somewhere within the confines of the screen. self.x = random.randint(0, boundary.right()) self.y = random.randint(0, boundary.bottom()) # Set the entity to be active. self.active = True # Set the entity to be touchable. self.touchable = True # Set the on touch event to None as default. self.onTouch = None # Return a freshly initialized instance of the base class. super().__init__(self.x, self.y, self.radius)
def __init__(self, position: Vector2.Vector2 = Vector2.Vector2(.0, .0), deltaX: float = 10): self.position = position # in world coordinates self.deltaX = deltaX # width of the camera self.deltaY = deltaX # height of the camera
def __init__(self): self.pos = vec2.Vec2(0, 0) self.vec = 0 self.size = 2 self.speed = 6 self.color = 7 self.direction = 0
def __init__(self, position: Vector2.Vector2 = Vector2.Vector2(), radius: float = 2): super().__init__(position, 50, radius) self.POL_COLOR = [.27, .93, .84]
def total_cost(self): # centroid based # return self.cost + self.est_cost # edge based if self.edge_in is None: return self.cost + self.est_cost else: return self.cost + self.target.centroid.sub(Vector2.mid(*self.edge_in)).magnitude()
def next_waypoint(self, mid=False, displacement=0.0, train=False): if self.index == -1: # no more path if train: return None, None, None else: return None if self.index == len(self.path_steps): # last one, return end point self.index = -1 if train: return self.end, self.end, None return self.end # get next edge p1, p2 = self.path_steps[self.index].edge_in self.index += 1 e1 = Vector2.Vector2(*p1) e2 = Vector2.Vector2(*p2) if mid: # return midpoint path, for visualization return e1.add(e2.sub(e1).scale(0.5)) # set fp to funnel point on next edge if self.findex == len(self.funnel_points): nextf = self.end else: nextf = self.funnel_points[self.findex] if nextf.xy() == e1.xy() or nextf.xy() == e2.xy(): # at the funnel point edge, return and advance fp = nextf self.findex += 1 else: # otherwise get the intersection with the edge if self.findex > 0: lastf = self.funnel_points[self.findex - 1] else: lastf = self.start fp = Vector2.intersection(lastf, nextf, e1, e2) # need midpoint for direction of displacement mp = e1.add(e2.sub(e1).scale(0.5)) if train: return fp, mp, (e1, e2) if displacement == 0: return fp disp = mp.sub(fp).normalize().scale(displacement) return fp.add(disp)
def contains_line(self, start, end): for i in range(len(self.path_steps) - 1, 0, -1): ps = self.path_steps[i] # see if this is the edge that start is on if start.xy() in ps.edge_in: # made it, must be true return True # print "...contains check on %s" % (ps.edge_in,) if ( Vector2.segment_intersect(start, end, Vector2.Vector2(*ps.edge_in[0]), Vector2.Vector2(*ps.edge_in[1])) is None ): return False # never found start, false return False
def edge_edge_distance(self, edge_out): if self.edge_in: start = Vector2.mid(*self.edge_in) else: start = self.node.centroid return Vector2.mid(*edge_out).sub(start).magnitude()
def cost_to(self, neighbor, edge_in): return self.cost + Vector2.mid(*edge_in).sub(self.node.centroid).magnitude()
def length(self): pts = [self.start] pts.extend(self.funnel_points) pts.append(self.end) return sum(Vector2.map_pairs(pts, fn=lambda v1, v2: v2.sub(v1).magnitude()))