def collide(creep1, creep2): if creep1.id != creep2.id: if pygame.sprite.collide_mask(creep1, creep2): if creep1.type != creep2.type and creep1.health <= creep2.health: creep1.rotate(-30, 30) creep1.health -= 1 creep2.health -= 0.5 if creep1.health <= 0: True creep1.kill() elif creep1.elapsed_time > randint(100, 500): if pygame.sprite.collide_circle_ratio(4)(creep1, creep2): if creep1.type != creep2.type: if creep1.health > creep2.health: creep2.curspeed = uniform(creep2.curspeed * 1.2, creep2.curspeed * 1.3) creep1.curspeed = uniform(creep1.curspeed * 1.1, creep1.curspeed * 1.2) if creep1.curspeed > creep1.speedmax: creep1.curspeed = creep1.speedmax if creep2.curspeed > creep2.speedmax: creep2.curspeed = creep2.speedmax vec = vec2d(creep2.rect.x - creep1.rect.x, creep2.rect.y - creep1.rect.y) if creep1.health > creep2.health: creep1.rotate(creep1.direction.get_angle_between(vec) + randint(-10, 10)) else: creep1.rotate(creep1.direction.get_angle_between(vec) - 180 + randint(-10, 10)) else: if ( pygame.sprite.collide_circle_ratio(10)(creep1, creep2) and creep1.health >= creep2.health and (creep1.type == creep2.type and creep1.elapsed_time >= 300) ): vec = vec2d(creep2.rect.x - creep1.rect.x, creep2.rect.y - creep1.rect.y) creep1.rotate(creep1.direction.get_angle_between(vec) + randint(-20, 20))
def __init__(self, size, number): Entity.__init__(self) self.size = size self.number = number self.walk_sheet = SpriteSheet("./img/sprite_male.png", block=64, start=(0, 512), size=(9, 4)) self.idle_sheet = SpriteSheet("./img/sprite_male.png", block=64, start=(0, 0), size=(1, 4)) self.animate = Animate("mob {}".format(self.number)) self.animate.load_animations("walk", ["up", "left", "down", "right"], self.walk_sheet.image_list) self.animate.load_animations("idle", ["up", "left", "down", "right"], self.idle_sheet.image_list) self.image = self.animate.update(0) self.rect = pygame.Rect(random.randint(0, 400), random.randint(0, 400), 64, 64) self.pos = vec2d(self.rect.center) self.direction = [0, 0, 0, 0] self.dir = vec2d(0, 0) self.target = vec2d(0, 0) self.straight = vec2d(1, 0) direction = random.randint(-0, 3) self.direction[direction] = 1 self.speed = 2
def run_md( dt, N_steps, T, L ): #questa sarà la funzione che girerà. dt è il passo temporale. T è temperatura, initial_pos sono le posizioni iniziali. N_partcl = 25 initial_pos = np.array([ v2d.vec2d(i + 10, j + 10) * sigma * 1.1 for i in range(int(np.sqrt(N_partcl))) for j in range(int(np.sqrt(N_partcl))) ]) positions = np.full([N_steps, N_partcl], fill_value=v2d.vec2d(0, 0)) positions[ 0, :] = initial_pos #questa dicitura indica di prendere la prima colonna e considerarne tutti gli elementi. x = initial_pos vel = init_vel(T, N_partcl) forces = compute_forces(initial_pos, L) for i in range(N_steps): #aggiornare posizioni x = update_positions(x, vel, forces, dt, L) #aggiornare forze con nuove posizioni new_forces = compute_forces( x, L) #lo chiamo newforces per evitare sovrascrizioni #calcolare velocità vel = update_velocities(vel, forces, new_forces, dt) #aggiorno array di posizione positions[i, :] = x return positions
def __init__(self, surface, pos=vec2d(0, 0), size=vec2d(200, 50), text="", textcolor=(0, 0, 0), padding=0, bgcolor=(255, 255, 255)): print "In textEntry init method" self.surface = surface self.pos = pos self.size = size self.text = text self.textcolor = textcolor self.padding = padding self.clicked = False self.rect = Rect(self.pos.x, self.pos.y, self.size.x, self.size.y) self.lastKey = "" self.delay = 1 #creates a text label to place in the middle of the rectangle self.font = pygame.font.SysFont("Times New Roman", 25) self.textOverlay = self.font.render(self.text, 1, self.textcolor) self.textSize = vec2d(self.font.size(self.text)) self.textRect = Rect(self.pos.x, self.pos.y, self.textSize.x, self.textSize.y)
def move(self, dt): moving = True if self.direction[0]: #up self.dir = vec2d(0, -5) self.dir.length = self.speed self.animate.switch("walk", "up") self.image = self.animate.update(dt) elif self.direction[1]: #left self.dir = vec2d(-5, 0) self.dir.length = self.speed self.animate.switch("walk", "left") self.image = self.animate.update(dt) elif self.direction[2]: #down self.dir = vec2d(0, 5) self.dir.length = self.speed self.animate.switch("walk", "down") self.image = self.animate.update(dt) elif self.direction[3]: #right self.dir = vec2d(5, 0) self.dir.length = self.speed self.animate.switch("walk", "right") self.image = self.animate.update(dt) else: moving = False self.animate.switch("idle") self.animate.new = True self.image = self.animate.update(dt) if moving: self.pos += self.dir self.rect.center = self.pos.inttup()
def __init__(self, fnames, pos): game.Game.__init__(self) strips = cyclic_list([]) y = 0 for i, fname in enumerate(fnames): if "colorkey" in fname: colorkey = -1 else: colorkey = None #pos = (50*i, y) # get the width out of the filename. parts = fname.split(".") try: width = int(parts[-2].split('-')[-1]) except: width = 50 strips.append(Strip(fname, width, colorkey, pos=pos, loop=-1)) self.pos = pos self.strips = strips self.strip = self.strips[0] self.direction = vec2d(0, 0) self.speed = 2 self.accel = 1 self.world = vec2d(0, 0)
def check(self, player): mtop = mleft = mbottom = mright = False collided = pygame.sprite.spritecollide(player, self.walls, False) if collided != []: for brick in collided: if not mtop: mtop = brick.rect.collidepoint(player.rect.midtop) if not mleft: mleft = brick.rect.collidepoint(player.rect.midleft) if not mbottom: mbottom = brick.rect.collidepoint(player.rect.midbottom) if not mright: mright = brick.rect.collidepoint(player.rect.midright) if mtop: if player.direction["up"]: wall_vector = vec2d(10,0) player.dir = player.dir.projection(wall_vector) if mleft: if player.direction["left"]: wall_vector = vec2d(0,10) player.dir = player.dir.projection(wall_vector) if mbottom: if player.direction["down"]: wall_vector = vec2d(10,0) player.dir = player.dir.projection(wall_vector) if mright: if player.direction["right"]: wall_vector = vec2d(0,10) player.dir = player.dir.projection(wall_vector)
def move(self, dt): moving = True if self.direction[0]: #up self.dir = vec2d(0,-5) self.dir.length = self.speed self.animate.switch("walk", "up") self.image = self.animate.update(dt) elif self.direction[1]: #left self.dir = vec2d(-5,0) self.dir.length = self.speed self.animate.switch("walk", "left") self.image = self.animate.update(dt) elif self.direction[2]: #down self.dir = vec2d(0,5) self.dir.length = self.speed self.animate.switch("walk", "down") self.image = self.animate.update(dt) elif self.direction[3]: #right self.dir = vec2d(5,0) self.dir.length = self.speed self.animate.switch("walk", "right") self.image = self.animate.update(dt) else: moving = False self.animate.switch("idle") self.animate.new = True self.image = self.animate.update(dt) if moving: self.pos += self.dir self.rect.center = self.pos.inttup()
def main(): # sets up pygame pygame.init() pygame.display.set_caption("Pysics") screen = pygame.display.set_mode((500, 590)) clock = pygame.time.Clock() world = pysicsWorld.world(screen) lastdraw = 0 circle = pysicsObj.object(screen, world, "player", 10, "circle") circle.pos = vec2d(320, 240) circle.size = 5 circle.mass = 1 for i in range(50): circle = pysicsObj.object(screen, world, "circle" + str(i), 10, "circle") circle.pos = vec2d(random.randint(0, screen.get_width()), random.randint(0, screen.get_height())) circle.vel = vec2d(screen.get_size()) / 2 - circle.pos circle2 = pysicsObj.object(screen, world, "circle2", 10, "circle") circle2.pos = vec2d(320, 0) circle2.vel = vec2d(0, 0) circle2.size = 5 circle2.mass = 1 # game loop while 1: # cap the framerate at 60 frames per second elapsed_time = clock.tick(60) lastdraw += elapsed_time circle = world.objects[0] # handle user input for e in pygame.event.get(): if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): pygame.quit() return # move the player with the arrow keys key = pygame.key.get_pressed() if key[K_LEFT]: circle.applyforce(vec2d(-100, 0)) if key[K_RIGHT]: circle.applyforce(vec2d(100, 0)) if key[K_UP]: circle.applyforce(vec2d(0, -200)) if key[K_DOWN]: circle.applyforce(vec2d(0, 100)) if not key[K_DOWN] and not key[K_LEFT] and not key[K_RIGHT] and not key[K_UP]: circle.vel = 0 circle2.acc = vec2d(0, 10) # draw everything world.update(elapsed_time) if lastdraw > 15: world.draw() lastdraw = 0 pygame.display.flip()
def __init__(self, screen, game, creep_images, explosion_images, field, init_position, init_direction, speed): """Create a new Creep. init_position: A vec2d or a pair specifying the initial position of the creep on the screen. """ Sprite.__init__(self) self.screen = screen self.game = game self.speed = speed self.field = field # base_image holds original image, positioned to angle 0. # image will be rotated self.base_image_0 = creep_images[0] self.base_image_45 = creep_images[1] self.image = self.base_image_0 self.explosion_images = explosion_images # vector specifying creep's position on screen self.pos = vec2d(init_position) self.prev_pos = vec2d(self.pos) # the direction is a normalized vector self.direction = vec2d(init_direction).normalized() self.state = Creep.ALIVE self.health = 15
def __init__(self, finestra, posicio = 'centre'): self.finestra = finestra if posicio == 'centre': self.posicio = vec2d(finestra.get_rect().center) self.direccio = vec2d(0,-1) self.cap = self.Cap(self.posicio) self.cap.set_direccio(self.direccio)
def mouseUp(self, button, pos): if pos[1] < 400: if button == 3: if type(self.selected) is Drone: self.selected.droneaction(self, pos) elif type(self.selected) is MainBase or \ type(self.selected) is Outpost: self.selected.target = vec2d(pos[0] + self.hud.pos[0], pos[1] + self.hud.pos[1]) elif button == 1: found = 0 for drone in self.drones: if drone.pos.get_distance(vec2d(pos[0] + self.hud.pos[0], pos[1] + self.hud.pos[1])) < 20: self.selected = drone found = 1; if found == 0: for building in self.buildings: if building.pos.get_distance(vec2d(pos[0] + self.hud.pos[0], pos[1] + self.hud.pos[1])) < building.size: self.selected = building # ------------------- Hud control ------------------------ else: curpos = vec2d(pos) if button == 1: self.selected.detectact(self, curpos)
def __init__( self, surface, pos=vec2d(0, 0), size=vec2d(200, 50), text="", textcolor=(0, 0, 0), padding=0, bgcolor=(255, 255, 255), ): print "In textEntry init method" self.surface = surface self.pos = pos self.size = size self.text = text self.textcolor = textcolor self.padding = padding self.clicked = False self.rect = Rect(self.pos.x, self.pos.y, self.size.x, self.size.y) self.lastKey = "" self.delay = 1 # creates a text label to place in the middle of the rectangle self.font = pygame.font.SysFont("Times New Roman", 25) self.textOverlay = self.font.render(self.text, 1, self.textcolor) self.textSize = vec2d(self.font.size(self.text)) self.textRect = Rect(self.pos.x, self.pos.y, self.textSize.x, self.textSize.y)
def line_intersect_circle(Q, r, segment): """ Verifies if a line crosses a circle. :param Q: :param r: :param segment: :return: true if the segment passes inside the circle, false otherwise. """ P1 = vec2d(segment[0]) V = vec2d(segment[1]) - vec2d(P1) a = V.dot([V.x, V.y]) l = P1 - Q b = 2 * V.dot([l.x, l.y]) c = P1.dot(P1) + Q.dot(Q) - 2 * P1.dot(Q) - r ** 2 disc = b ** 2 - 4 * a * c if disc < 0: return False, None sqrt_disc = math.sqrt(disc) t1 = (-b + sqrt_disc) / (2 * a) t2 = (-b - sqrt_disc) / (2 * a) if not (0 <= t1 <= 1 or 0 <= t2 <= 1): return False, None t = max(0, min(1, - b / (2 * a))) return True, P1 + t * V
def __init__(self, surface, pos=vec2d(0, 0), btntype="", imgnames=[], text="", textcolor=(0,0,0), textimg=0,padding=0, attached=""): print "In button init method" self.surface = surface self.pos = pos self.btntype = btntype self.imgnames = imgnames self.text = text self.textcolor = textcolor self.textimg = textimg self.padding = padding self.attached = attached self.state = Button.UNCLICKED self.toggle = 0 #load images self.imgs = [] for name in self.imgnames: img = pygame.image.load(name).convert_alpha() #img = img.set_colorkey((255,255,255)) #it would be nice to make the images transparent, #but it throws an error not worth fighting self.imgs.append(img) self.imgwidth, self.imgheight = self.imgs[self.toggle].get_size() self.rect = Rect(self.pos.x, self.pos.y, self.imgwidth, self.imgheight) print "Image dimensions are: " + str(self.imgwidth) + ", " + str(self.imgheight) #creates a text label to place in the middle of the button font = pygame.font.SysFont("Times New Roman", 25) self.textOverlay = font.render(self.text,1,self.textcolor) self.textSize = vec2d(font.size(self.text)) self.textRect = Rect(self.pos.x+self.imgwidth/2-self.textSize.x/2,self.pos.y+self.imgheight/2-self.textSize.y/2,0,0)
def __init__(self, x, y, init_direction, color=None, size=None, dna=None, age=0): pygame.sprite.Sprite.__init__(self) self.size = randrange(4, 15), randrange(4, 15) self.color = (randint(0, 255), randint(0, 255), randint(0, 255)) self.dna = ''.join(choice(string.ascii_uppercase) for _ in range(4)) if size: self.size = size if color: self.color = color if dna: self.dna = dna self.stamina = randrange(500, 1650) self.age = age self.life_span = randrange(1000, 2500) self.speed = uniform(.001, .6) self.ori_speed = self.speed self.eating = 10 self.dna_score = self.fitness(self.dna) self.birth_recup = 20 self.counter = 0 self.image = pygame.Surface([self.size[0], self.size[1]]) self.image.fill(self.color) self.rect = self.image.get_rect() self.rect.x, self.rect.y = vec2d((x, y)) self.direction = vec2d(init_direction).normalized()
def detectact(self, target, curpos): if curpos.get_distance(vec2d(646, 456)) <= 15: new_drone = self.buy_drone() if new_drone: target.drones.append(new_drone) if curpos.get_distance(vec2d(696, 456)) <= 15: self.buy_battery()
def __init__(self, screen, img_filename, init_position, init_direction, speed): """Skapar ett nytt kryp. @param screen: Ytan där krypet ska målas. @param image_filname: Image file för krypet. @param init_position: Startposition. @param init_direction: Startriktning. @param speed: Hastighet i pixels/ms """ pygame.sprite.Sprite.__init__(self) if Creep.explosion_sound is None: # Ladda bara ljudet EN gång, en statisk variabel Creep.explosion_sound = pygame.mixer.Sound(os.path.join('sound','bomb_explosion.wav')) self.explosion_sound = Creep.explosion_sound self.explosion_sound.set_volume(0.2) self.health = 5 self.state = Creep.ALIVE self.screen = screen self.speed = speed self.explosion_image = pygame.image.load(os.path.join('images','boom.png')).convert_alpha() self.explosion_timer = 0 # Originalbilden self.base_image = pygame.image.load(img_filename).convert_alpha() # Bilden som skall roteras osv self.image = self.base_image # Rect behövs för den kolissionshanteringen self.rect = self.image.get_rect() # Start-position. En vektor self.pos = vec2d(init_position) # Start-riktning. En normaliserad vektor self.direction = vec2d(init_direction).normalized()
def __init__(self, screen, field, game, image, init_pos, init_direction): """ screen: obrazovka na ktoru sa bude vykraslovat field: rect v ktorom sa odohrava hra game: objekt hry image: ibrazok pre loptu init_direction = smer lopty na zaciatku """ Sprite.__init__(self) self.screen = screen self.field = field self.game = game self.image = image self.pos = vec2d(init_pos) self.direction = vec2d(init_direction).normalized() self.speed = 0.35 self.rect = self.image.get_rect() self.rect.center = self.pos
def get_interfaces(self, x,y): sides = {} sides["left"] = [vec2d(x, y+z) for z in self.interfaces] sides["right"] = [vec2d(self.dis+x, y+z) for z in self.interfaces] sides["top"] = [vec2d(x+z, y) for z in self.interfaces] sides["bottom"] = [vec2d(x+z, y+self.dis) for z in self.interfaces] return sides
def __init__(self, screen, field, init_position, init_direction, speed, img_file, dead_img_file): Sprite.__init__(self) self.name = 'Creep' self.base_image = img_file self.image = self.base_image self.image_dead = dead_img_file self.screen = screen self.field = field self.pos = vec2d(init_position) self.direction = vec2d(init_direction).normalized() self.speed = speed self.state = self.ALIVE self.attack_power = 10 self.deffence_power = 5 self.life = 100 self.max_life = 100 self.image_w, self.image_h = self.image.get_size() self.reborn_time = 0 self._time_moving = 0 self._time_moving_max = random.randint(5000, 10000) self.bullets = []
def on_update(dt): # going to store the old position, for collision purposes old_pos = vec2d(cell.x, cell.y) # move the cell towards it's velocity cell.x += cell.velocity[0] * dt cell.y += cell.velocity[1] * dt # check for collisions against wall # if one is found, get new position, to allow "sliding" # against them radius = cell_image.width / 2 * 0.8 i = 0 if cell.velocity != (0, 0): while i < len(lines): p1 = vec2d(lines[i], lines[i + 1]) p2 = vec2d(lines[i + 2], lines[i + 3]) line = p2 - p1 normal = line.perpendicular_normal() vec = (cell.x, cell.y) + radius * normal intersects = line_intersect(old_pos, vec, p1, p2) if not intersects is None: new_pos = calc_new_pos(old_pos, vec, p1, p2) new_pos -= radius * normal cell.x = new_pos.x cell.y = new_pos.y elif circle_point_intersect(cell.position, radius, p1): direction = cell.position - p1 length = direction.length move_by_distance = radius - length new_pos = cell.position + direction.normalized() * move_by_distance cell.x = new_pos.x cell.y = new_pos.y i += 4
def draw(self, screen, focus, alpha): screen_pos = vec2d(int(self.pos[0] * CELL_SIZE + 15 - focus[0]), int(self.pos[1] * CELL_SIZE + 15 - focus[1])) sprite_size = self.sprite.get_size() screen_iso_pos = vec2d(screen_pos[0] - screen_pos[1], int((screen_pos[0] + screen_pos[1])/2)) screen.blit(self.sprite, (int(screen_iso_pos[0] - sprite_size[0] // 2), int(screen_iso_pos[1] - sprite_size[1] // 2)), special_flags=pygame.BLEND_MULT)
def __init__(self): main = MainBase() main.pos = vec2d(300, 300) main.target = vec2d(main.pos[0] + 10, main.pos[1]) out = Outpost() out.pos = vec2d(200, 200) out.target = vec2d(out.pos[0] + 10, out.pos[1]) self.buildings = [main, out]
def test_drone_update(self): drone = Drone() drone.pos = vec2d(100, 100) target = vec2d(200, 200) drone.target.append(target) drone.update() self.assertEqual(drone.pos, (103, 103)) self.assertEqual(drone.power, 255-0.1)
def __init__(self, pid, x, y, direction, damage, power): self.pid = pid self.pos = vec2d(x, y) self.init_pos = vec2d(x, y) self.direction = direction self.damage = damage self.gone = False self.destroy_after = power
def __init__(self, surface, image, pos=vec2d(0,0), speed=vec2d(1,0), gravity=1): self.surface = surface self.surfaceSize = vec2d(self.surface.get_size()) self.image = pygame.image.load(image) self.pos = pos self.speed = speed self.gravity = gravity self.size = vec2d(self.image.get_size()) self.rect = Rect(self.pos.x, self.pos.y, self.size.x, self.size.y)
def get_fang_pos(self): base_angle = self.head.direction.angle radius = self.head.radius * 0.5 top = vec2d(radius, 0) top.angle = base_angle - self.pos_angle bottom = vec2d(radius, 0) bottom.angle = base_angle + self.pos_angle self.top_pos = self.pos + top self.bot_pos = self.pos + bottom
def __init__( self, screen, creep_image,init_position, init_direction, speed, **kv): """ Create a new Creep. screen: The screen on which the creep lives (must be a pygame Surface object, such as pygame.display) creep_image: Image (surface) object for the creep field: A Rect specifying the 'playing field' boundaries. The Creep will bounce off the 'walls' of this field. init_position: A vec2d or a pair specifying the initial position of the creep on the screen. init_direction: A vec2d or a pair specifying the initial direction of the creep. Must have an angle that is a multiple of 45 degres. speed: Creep speed, in pixels/millisecond (px/ms) **kw: passing parameters """ Sprite.__init__(self) self.screen = screen self.speed = speed self.field = screen.get_rect() # base_image holds the original image, positioned to # angle 0. # image will be rotated. # self.base_image = creep_image self.image = self.base_image self.image_w, self.image_h = self.image.get_size() # A vector specifying the creep's position on the screen # self.pos = vec2d(init_position) # The direction is a normalized vector # self.direction = vec2d(init_direction).normalized() # self.exploding = 0 # for k,v in kv.items(): self.__dict__[k] = v
def mouse_click_event(self, pos): if self.btntype == "Close": if self._point_is_inside(vec2d(pos)): self.state = Button.CLICKED elif self.btntype == "Toggle": if self._point_is_inside(vec2d(pos)): self.state = not self.state self.toggle = not self.toggle game.buttons[0].state = not Game.buttons[0].state
def __init__(self): self.ico_pic = pygame.image.load("sprites/generator_ico.png") self.up_ico = pygame.image.load("sprites/icons/up_ico.png") self.image = Animation() self.image.setup("outpost") self.size = 35 self.level = 0 self.target = vec2d(0, 0) self.fire_target = vec2d(0, 0)
def __init__(self, surface, image, pos=vec2d(0, 0), speed=vec2d(1, 0), gravity=1): self.surface = surface self.surfaceSize = vec2d(self.surface.get_size()) self.image = pygame.image.load(image) self.pos = pos self.speed = speed self.gravity = gravity self.size = vec2d(self.image.get_size()) self.rect = Rect(self.pos.x, self.pos.y, self.size.x, self.size.y)
def __init__(self, body_image, init_position, init_direction, screen, displacement): pygame.sprite.Sprite.__init__(self) self.body_img = pygame.image.load(body_image).convert_alpha() self.image=self.body_img self.pos=vec2d(init_position) self.direction=vec2d(init_direction).normalized() self.displacement=displacement self.screen=screen self.calorie=randint(400,500)
def movedrone(target, pos): if target.selected.single_t == 0: dtarget = vec2d(pos[0] + target.hud.pos[0], pos[1] + target.hud.pos[1]) target.selected.target.append(dtarget) else: targets = [] dtarget = vec2d(pos[0] + target.hud.pos[0], pos[1] + target.hud.pos[1]) targets.append(dtarget) target.selected.target = targets
def __init__(self, screen, creep_image, explosion_images, field, init_position, init_direction, speed): """ Create a new Creep. screen: The screen on which the creep lives (must be a pygame Surface object, such as pygame.display) creep_image: Image (surface) object for the creep explosion_images: A list of image objects for the explosion animation. field: A Rect specifying the 'playing field' boundaries. The Creep will bounce off the 'walls' of this field. init_position: A vec2d or a pair specifying the initial position of the creep on the screen. init_direction: A vec2d or a pair specifying the initial direction of the creep. Must have an angle that is a multiple of 45 degres. speed: Creep speed, in pixels/millisecond (px/ms) """ Sprite.__init__(self) self.screen = screen self.speed = speed self.field = field # base_image holds the original image, positioned to # angle 0. # image will be rotated. # self.base_image = creep_image self.image = self.base_image self.explosion_images = explosion_images # A vector specifying the creep's position on the screen # self.pos = vec2d(init_position) # The direction is a normalized vector # self.direction = vec2d(init_direction).normalized() self.state = Creep.ALIVE self.health = 15
def closest_point(self, point): closest = 99999 the_point = vec2d(point) for p in self.pointlist: p = vec2d(p) dist = p.get_distance(the_point) if closest > dist: closest = dist the_point = p return the_point
def helpdrone(target, pos): for drone in target.drones: if drone.pos.get_distance(vec2d(pos[0] + target.hud.pos[0], pos[1] + target.hud.pos[1])) < 20 and drone.power < 1: if drone is not target.selected: target.selected.target.append(target.buildings[0].pos) target.selected.task = 2 target.selected.target.append(vec2d(int(drone.pos[0]), int(drone.pos[1]))) print("Going to charge another drone!") return 1 return 0
def __init__(self, pos = None): if pos == None: self.pos = vec2d((randrange(100,401)*1.00),(randrange(100,401)*1.00)) else: self.pos = pos self.mass = float(randrange(5,15)) self.color = (self.mass/100.0)*255.0 self.direction = vec2d(0,0) self.dead = False self.rect = pygame.Rect(self.pos.x, self.pos.y, int(self.mass/3), int(self.mass/3))
def __init__(self, surface, pos=vec2d(0, 0), size=vec2d(20, 20), color=(255, 0, 0), speed=vec2d(1, 0), gravity=0): """ creates an object that moves around the screen """ self.surface = surface self.surfaceSize = vec2d(self.surface.get_size()) self.pos = pos self.size = size self.speed = speed self.gravity = gravity self.rect = Rect(self.pos.x, self.pos.y, self.size.x, self.size.y) self.color = color
def __init__(self, filename, position, direction=(1, 0)): Sprite.__init__(self) self.filename = filename self.position = vec2d(position) self.direction = vec2d(direction).normalized() self.prev_direction = vec2d(self.direction) self.base_image = load_image(filename) self.layer = 0 self.wheeled = False self._render()
def displace(self, a, b, amount): av = vec2d(a) bv = vec2d(b) lv = bv - av hv = lv / 2 jv = av + hv jv.length += rai(-amount, amount) line1 = [av.inttup(), jv.inttup()] line2 = [jv.inttup(), bv.inttup()] return line1, line2
def displace(self, a, b, amount): av = vec2d(a) bv = vec2d(b) lv = bv - av hv = lv/2 jv = av + hv jv.length += rai(-amount, amount) line1 = [av.inttup(), jv.inttup()] line2 = [jv.inttup(), bv.inttup()] return line1, line2
def __init__(self,screen,img_filename,init_position,init_direction,speed): pygame.sprite.Sprite.__init__(self) self.screen = screen self.speed = speed self.base_image_0 = creep_filenames[0] self.base_image_45 = creep_filenames[1] self.pos = vec2d(init_position) self.prev_pos = vec2d(self.pos) self.direction = vec2d(init_direction).normalized()
def __init__(self, pos, kind, genes = {}): self.pos = vec2d(pos[0]*1.0, pos[1]*1.0) if self.pos.x < 0: self.pos.x += 700 elif self.pos.x > 700: self.pos.x -= 700 self.dir = vec2d(0,1) self.kind = kind #this will be Grass for the first seeds self.sprout = False self.genes = genes
def __init__(self, screen, init_position, init_direction, speed): pygame.sprite.Sprite.__init__(self) self.screen = screen # Skapa en rect! för ritning och kollisionshantering init_x, init_y = init_position self.rect = pygame.Rect(init_x, init_y, 16, 16) # Start-position. En vektor self.pos = vec2d(init_position) # Start-riktning. En normaliserad vektor self.direction = vec2d(init_direction).normalized() self.speed = speed
def __init__(self, screen, img_filename, init_position, init_direction, speed): pygame.sprite.Sprite.__init__(self) self.screen = screen self.speed = speed self.base_image = pygame.image.load(img_filename).convert_alpha() self.image = self.base_image self.pos = vec2d(init_position) self.direction = vec2d(init_direction).normalized()
def __init__(self, screen, enemyImg, startPosition, direction, speed): Sprite.__init__(self) self.screen = screen self.speed = speed self.base_image = pygame.image.load("dalek.png").convert_alpha() self.image = self.base_image self.pos = vec2d(startPosition) self.direction = vec2d(direction).normalized()
def run_game(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) clock = pygame.time.Clock() creep = pygame.image.load(CREEP_FILENAME).convert_alpha() autocreep = Creep(CREEP_FILENAME, vec2d(300, 100), vec2d(1, 1), 0.1, screen) creep_pos = vec2d(220, 200) creep_speed = 0.09 # px per ms creep_dir = vec2d(-1, -1).normalized() while True: time_passed = clock.tick(35) movement_dir = 0 rotation_dir = 0 for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: rotation_dir = -1 elif event.key == pygame.K_RIGHT: rotation_dir = 1 pressed_keys = pygame.key.get_pressed() if pressed_keys[pygame.K_UP]: movement_dir = 1 elif pressed_keys[pygame.K_DOWN]: movement_dir = -1 creep_dir.rotate(45 * rotation_dir) creep_pos += creep_dir * movement_dir * creep_speed * time_passed rotated_creep = pygame.transform.rotate(creep, -creep_dir.angle) w, h = rotated_creep.get_size() creep_draw_pos = vec2d(creep_pos.x - w / 2, creep_pos.y - h / 2) screen.fill(BG_COLOR) autocreep.update(time_passed) autocreep.blitme() #~ screen.blit(autocreep.image, autocreep.rect) screen.blit(rotated_creep, creep_draw_pos) pygame.display.flip()
def make_line(a, b): av = vec2d(a) bv = vec2d(b) line = [] between = bv - av endl = between.length l = 1 while l < endl: between.length = l x = av + between line.append(x.inttup()) l += 1 return line
def __init__(self, surface, radius, pos_init, dir_init, speed, SCREEN_WIDTH, SCREEN_HEIGHT, jitter_speed): self.windowSurface = surface self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.BOXWIDTH = 100 self.jitter_speed = jitter_speed self.speed = speed self.radius = radius self.pos = vec2d(pos_init) self.direction = vec2d(dir_init) self.direction.normalize() # normalized
def update(self, time_passed): """ Update the creep. time_passed: The time passed (in ms) since the previous update. """ if self.state == Creep.ALIVE: # Maybe it's time to change the direction ? # self._compute_direction(time_passed) # Make the creep image point in the correct direction. # Note that two images are used, one for diagonals # and one for horizontals/verticals. # # round() on the angle is necessary, to make it # exact, despite small deviations that may result from # floating-point calculations # if int(round(self.direction.angle)) % 90 == 45: self.image = pygame.transform.rotate( self.base_image_45, -(self.direction.angle + 45)) elif int(round(self.direction.angle)) % 90 == 0: self.image = pygame.transform.rotate( self.base_image_0, -self.direction.angle) else: assert False # Compute and apply the displacement to the position # vector. The displacement is a vector, having the angle # of self.direction (which is normalized to not affect # the magnitude of the displacement) # displacement = vec2d( self.direction.x * self.speed * time_passed, self.direction.y * self.speed * time_passed) self.prev_pos = vec2d(self.pos) self.pos += displacement # When the image is rotated, its size is changed. self.image_w, self.image_h = self.image.get_size() elif self.state == Creep.EXPLODING: if self.explode_animation.active: self.explode_animation.update(time_passed) else: self._die() elif self.state == Creep.DEAD: pass
def displace(self, a, b, amount): """ Here we displace each individual line. This method is called from the displacement method. """ av = vec2d(a) bv = vec2d(b) lv = bv - av hv = lv / 2 jv = av + hv jv.length += rai(-amount, amount) line1 = [av.inttup(), jv.inttup()] line2 = [jv.inttup(), bv.inttup()] return line1, line2
def __init__(self): infoObject = pygame.display.Info() print infoObject.current_w - 100, infoObject.current_h - 100 self.w, self.h = infoObject.current_w - 100, infoObject.current_h - 100 self.topx = vec2d(self.w / 2, self.h / 2) PygameHelper.__init__(self, size=(self.w, self.h), fill=((255, 255, 255))) self.bound = 50 self.e = Environment() self.mode_build = 0 ### 0 == Agent, 1 == Goal, 2 == landmark, 3 == nest, 4 == pipe self.actiontext = "" self.first = 0 self.firstpos = vec2d(0, 0)
def make_line(a, b): a = (int(round(a[0])), int(round(a[1]))) b = (int(round(b[0])), int(round(b[1]))) av = vec2d(a) bv = vec2d(b) line = [] between = bv - av endl = between.length l = 1 while l < endl: between.length = l x = av + between line.append(x.inttup()) l += 1 return line
def diagram_lists(points): point_dict = {item: [] for item in points} for y in xrange(size): for x in xrange(size): p = vec2d(x, y) minum = 999999 a = (0, 0) for i in points: i = vec2d(i) dist = i.get_distance(p) if minum > dist: minum = dist a = i.inttup() point_dict[a].append(p.inttup()) return point_dict
def __init__(self, screen, img_filename, init_position, init_direction, speed): Sprite.__init__(self) self.screen = screen self.speed = speed self.base_image = pygame.image.load('dalek.png') self.image = self.base_image self.pos = vec2d(init_position) self.direction = vec2d(init_direction).normalized() self.Rect = self.image.get_rect()