def exchange_speed(self, otherplayer): self_rect, other_rect = self.get_body_rect(), otherplayer.get_body_rect() mtv_self = Point(other_rect.x - self_rect.x, other_rect.y - self_rect.y) mtv_other = Point(self_rect.x - other_rect.x, self_rect.y - other_rect.y) speed_self = Point(self.xspeed, self.yspeed) speed_other = Point(otherplayer.xspeed, otherplayer.yspeed) impact_self = speed_self.projection(mtv_self) impact_other = speed_other.projection(mtv_other) def get_speed(speed): if speed > 0: return min(int(speed), settings.maxspeed) else: return max(int(speed), -settings.maxspeed) self.xspeed = get_speed(impact_other.x + mtv_other.x / settings.player_collision_x_factor) self.yspeed = get_speed(impact_other.y + mtv_other.y / settings.player_collision_y_factor) otherplayer.xspeed = get_speed(impact_self.x + mtv_self.x / settings.player_collision_x_factor) otherplayer.yspeed = get_speed(impact_self.y + mtv_self.y / settings.player_collision_y_factor) self.move() otherplayer.move() while self.intersects_player(otherplayer): self.move() otherplayer.move()
def main(): root = Tk() root.title('Rescaling') W, H = 700, 500 PAD = 50 canvas = Canvas(root, width=W, height=H, background='black') canvas.grid(row=0, column=1) #triangle = make_random_triangle(W, H) triangle = [ Point(W / 2, PAD), Point(PAD, H - PAD), Point(W - 3 * PAD, H - 4 * PAD) ] scale_factor = 0.8 for i in range(37): color1 = random_color() color2 = random_color() center = locate(triangle)['center'] t_list = [point.as_list() for point in triangle] print(t_list) canvas.create_polygon(t_list, fill=color1, outline=color2, width=2) triangle = rotate_shape(triangle, center, degrees=10) [print(point) for point in triangle] root.mainloop()
def main(): root = Tk() root.title('Bouncing ball with energy loss on collision') W, H = 700, 500 canvas = Canvas(root, width=W, height=H, background='black') canvas.grid(row=0, column=1) CYCLE_IN_MS = 30 N_FRAMES = 5000 TIME_INCR = 0.2 GRAVITY = 10 ball_position = Point(15, 180) velocity = Point(20, 50) BALL_DIAMETER = 30 COEF_RESTITUTION = 0.7 COLOR = 'cyan' for i in range(N_FRAMES): velocity += Point(0, GRAVITY * TIME_INCR) ball_position += (velocity * TIME_INCR) canvas.create_oval(ball_position.as_list(), (ball_position + Point(BALL_DIAMETER, BALL_DIAMETER)).as_list(), fill=COLOR) ball_location, velocity = detect_collision(canvas, ball_position, BALL_DIAMETER, velocity, COEF_RESTITUTION) canvas.update() canvas.after(CYCLE_IN_MS) canvas.delete(ALL) root.mainloop()
def OnChar(self, event): if self._selectedKeyHandle == None: self._selectKey(self._displayKeys.keys()[0]) displayKey = self._displayKeys[self._selectedKeyHandle] pos = None code = event.GetKeyCode() if code == wx.WXK_LEFT: pos = Point(displayKey.unscaled.x - self._keySpacing.width - 1, displayKey.unscaled.y) elif code == wx.WXK_RIGHT: pos = Point( displayKey.unscaled.x + displayKey.unscaled.width + self._keySpacing.width + 1, displayKey.unscaled.y) elif code == wx.WXK_UP: pos = Point(displayKey.unscaled.x, displayKey.unscaled.y - self._keySpacing.height - 1) elif code == wx.WXK_DOWN: pos = Point( displayKey.unscaled.x, displayKey.unscaled.y + displayKey.unscaled.height + self._keySpacing.height + 1) else: event.Skip() return selectKeyHandle = None for (displayKeyHandle, displayKey) in self._displayKeys: if displayKey.unscaled.Contains(pos): selectKeyHandle = displayKeyHandle break if selectKeyHandle != None: self._selectKey(selectKeyHandle)
def main(): root = Tk() root.title('Ball') W, H = 700, 700 PAD = 10 DIAMETER = 25 CYCLE_MS = 15 canvas = Canvas(root, width=W, height=H, background='white') canvas.grid(row=0, column=1) ball = [Point(PAD, PAD), Point(PAD + DIAMETER, PAD + DIAMETER)] ball_box = [point.as_list() for point in ball] shift = Point(1, 1) canvas.create_oval(ball_box, fill='green') for i in range(1, 500): ball = [point + shift for point in ball] ball_box = [point.as_list() for point in ball] canvas.create_oval(ball_box, fill='green') canvas.update() canvas.after(CYCLE_MS) canvas.delete(ALL) root.mainloop()
def createLines(Ti): L = [] for i in Ti: a = [Point(i[0]), Point(i[1])] a = sorted(sorted(a, key=lambda x: x.y), key=lambda x: x.x) L.append(Line(a[0], a[1])) return L
def collide(ball, canvas, collision_side, absorb=0): width, height = canvas.winfo_reqwidth(), canvas.winfo_reqheight() # Collision may have occurred on previous step, but the ball may not yet # have cleared the wall, which will trigger "another" collision. If so, do # nothing if (collision_side == 'right' and ball.acceleration.x < 0 or collision_side == 'left' and ball.acceleration.x > 0 or collision_side == 'bottom' and ball.acceleration.y < 0 or collision_side == 'top' and ball.acceleration.y > 0): return ball if collision_side in ['left', 'right']: factor = Point(-1, 1) else: factor = Point(1, -1) ball.acceleration = Point(ball.acceleration.x * factor.x, ball.acceleration.y * factor.y) if collision_side == 'top': ball.acceleration.y *= absorb elif collision_side == 'bottom': ball.acceleration.y *= absorb elif collision_side == 'left': ball.acceleration.x *= absorb elif collision_side == 'right': ball.acceleration.x *= absorb return ball
def create_random_ball(ident): diameter = random.uniform(5, MAX_DIAMETER) return Ball( Point(random.uniform(0, W - diameter), random.uniform(0, H - diameter)), Point(random.uniform(-MAX_SPEED, MAX_SPEED), random.uniform(-MAX_SPEED, MAX_SPEED)), diameter, random_color(), random.uniform(ELASTICITY_RANGE[0], ELASTICITY_RANGE[1]), ident)
def make_random_ball(max_x, max_y, max_diameter): location = Point(random.uniform(0, max_x), random.uniform(0, max_y)) diameter = random.uniform(5, max_diameter) initial_acceleration = Point(random.uniform(0, 20), random.uniform(-20, 0)) ball = Ball(location, diameter, initial_acceleration) ball.set_color(random_color()) ball.set_outline(random_color()) return ball
def __init__(self, bounds, plate_height_ratio, height): self.bounds = bounds self.plate_scale_real = Point( [unit_distance, unit_distance * plate_height_ratio, unit_distance]) self.ratio = Point([plate_height_ratio, 1, plate_height_ratio]) self.scale = (height / bounds.range_.y) * self.ratio self.grid_dimensions = Point.as_int(np.ceil(self.scale * bounds.range_))
def make_ball_with_trajectory(max_width, max_height): diameter = random.uniform(5, 35) p1 = Point(random.uniform(0, max_width), random.uniform(0, max_height)) ball = [p1, p1 + Point(diameter, diameter)] trajectory = Point(random.choice([-3, -2, -1, 1, 2, 3]), random.choice([-3, -2, -1, 1, 2, 3])) color = random_color() return {'ball': ball, 'trajectory': trajectory, 'color': color}
def create_random_ball(max_width, max_height, max_speed, max_diameter, elasticity_range, ident): diameter = random.uniform(5, max_diameter) return Ball( Point(random.uniform(0, max_width - diameter), random.uniform(0, max_height - diameter)), Point(random.uniform(-max_speed, max_speed), random.uniform(-max_speed, max_speed)), diameter, random_color(), random.uniform(elasticity_range[0], elasticity_range[1]), ident)
def move(self, *, direction: Direction): head = self.head() if direction == Direction.UP: head = Point(x=head.x, y=head.y - 1) elif direction == Direction.DOWN: head = Point(x=head.x, y=head.y + 1) elif direction == Direction.LEFT: head = Point(x=head.x - 1, y=head.y) else: head = Point(x=head.x + 1, y=head.y) self._points.append(head)
def make_rainbow(canvas, n_color, line, colors, n_steps, degree_factor, center, width): for i in range(n_color): line_a = [ Point(line[i].x, line[i].y), Point(line[i + 1].x, line[i + 1].y) ] for j in range(n_steps): new_shape = rotate_shape(line_a, center, degree_factor * j) new_shape = [point.as_list() for point in new_shape] canvas.create_line(new_shape, fill=colors[i], width=width)
def update_ball(canvas, ball, gravity, time_incr): old_position = ball.position + Point(ball.diameter / 2, ball.diameter / 2) ball.velocity += Point(0, gravity) ball.position += ball.velocity * time_incr canvas.create_oval(ball.get_coords(), fill=ball.color, outline=ball.outline, tags='ball') canvas.create_line(old_position.as_list(), (ball.position + Point(ball.diameter / 2, ball.diameter / 2)).as_list(), fill=ball.color) ball = detect_collision(canvas, ball) return ball
def update_balls(canvas, ball, balls): old_position = ball.position + Point(ball.diameter / 2, ball.diameter / 2) ball.velocity += Point(0, GRAVITY) ball.position += ball.velocity * TIME_INCR canvas.create_oval( ball.get_coords(), fill=ball.color, outline=ball.outline, tags='ball') canvas.create_line( old_position.as_list(), (ball.position + Point(ball.diameter / 2, ball.diameter / 2)).as_list(), fill=ball.color) ball = detect_wall_collision(ball) for b in balls: if ball.ident != b.ident: ball, b = detect_ball_collision(ball, b) return ball, balls
def people(): if request.method == 'POST': data = request.get_json() url = "ibm_weather_api_key" + str(data['lat']) + "/" + str( data['lng']) + "/alerts.json" response = requests.request("GET", url) rep = json.loads(response.text) severity = 1000000 if 'alerts' in rep: for alert in rep['alerts']: severity = min(severity, alert['severity_cd']) return str( people_table.insert({ 'location': [data['lat'], data['lng']], 'priority': data['priority'], 'note': data['note'], 'status': 0, 'time': str(datetime.datetime.now()), 'severity': severity })) if request.method == 'GET': l = [] for person in people_table.find(): person['time'] = str(person['time']) person['_id'] = str(person['_id']) person['location'] = Point( person['location'][0], person['location'][1]).get_serialisable() l.append(person) return json.dumps(l)
def main(): root = Tk() root.title('Gravity') W, H = 600, 750 canvas = Canvas(root, width=W, height=H, background='black') canvas.grid(row=0, column=1) GRAVITY = Point(0, 6) CYCLE_IN_MS = 30 N_STEPS = 300 ABSORB = 0.85 N_BALLS = 100 MAX_DIAMETER = 40 balls = [make_random_ball(W, H, MAX_DIAMETER) for ball in range(N_BALLS)] for step in range(N_STEPS): for ball in balls: draw(canvas, ball) ball.move() ball = add_gravity(GRAVITY, ball) collision = check_collision(ball, canvas) if collision['is_collision']: ball = collide(ball, canvas, collision['side'], ABSORB) print('Collision!') canvas.update() canvas.after(CYCLE_IN_MS) canvas.delete(ALL) root.mainloop()
def gen_cells(self, cell_value_func, stop_func): self.values[Point(0, 0)] = 1 while True: if stop_func(self.pos): break self.take_step() self.add_cell_to_values(cell_value_func)
def main(): root = Tk() root.title('Color Transititions along a Gradient') W, H = 300, 750 PAD = 8 canvas = Canvas(root, width=W, height=H, background='black') canvas.grid(row=0, column=1) fonts = ['Bookantiqua 12 bold', 'Bookantiqua 10 bold'] start_color = '#ff0000' end_color = '#ffff00' swatch_start = Point(20, 10) swatch_width = 40 swatch_height = 40 n_steps = 8 colors = make_discrete_color_series(start_color, end_color, n_steps) for i in range(n_steps): show_swatch(canvas, colors[i], swatch_start, swatch_width, swatch_height, PAD, fonts) swatch_start.set_y(swatch_start.y + swatch_height + PAD) root.mainloop()
def load_obj_file(obj_location): with open(obj_location) as f: faces = [] bounds = defaultdict(Bounds) textures = defaultdict(None) texture_to_rgb = defaultdict(None) vertices = defaultdict(list) file_dir = os.path.dirname(obj_location) mtl_state = None for components in (x.strip().split() for x in f if x.strip()): key = components[0] if key == 'mtllib': mtl_file_location = os.path.join(file_dir, components[1]) texture_to_file, texture_to_rgb = find_texture_info( mtl_file_location) textures = load_textures(file_dir, texture_to_file) elif key == 'usemtl': mtl_state = components[1] elif key.startswith('v'): value = Point(components[1:]) vertices[key].append(value) bounds[key].update(value) elif key == 'f': texture = textures.get(mtl_state, None) face = handle_face(components[1:], texture) face.Kd = texture_to_rgb.get(mtl_state, None) faces.append(face) return ParsedObjFile(faces, bounds, vertices)
def main(): root = Tk() root.title('') W, H = 1580, 200 PAD = 20 canvas = Canvas(root, width=W, height=H, background='black') canvas.grid(row=0, column=1) start_point = Point(PAD, PAD) ramp_height = H - 2 * PAD n_steps = 255 r1, r2, r3, r4, g1, g2, g3, g4, b1, b2, b3, b4 = ([ random.uniform(0., 100.) for i in range(12) ]) r_ramps = [[0., r1], [r1, r2], [r2, r3], [r3, r4], [r4, 0.]] g_ramps = [[0., g1], [g1, g2], [g2, g3], [g3, g4], [g4, 0.]] b_ramps = [[0., b1], [b1, b2], [b2, b3], [b3, b4], [b4, 0.]] for i in range(len(r_ramps)): start_point.set_x( make_color_ramp(canvas, start_point, r_ramps[i], g_ramps[i], b_ramps[i], n_steps, ramp_height)) root.mainloop()
def get_mean(self): ''' Returns a Point that is the mean of this cluster's members. The x and y positions are simple averages over the members' positions. The bearing is computed by averaging the x and y components of the unit vectors represented by the bearing. ''' if not self.members: return self.center x = 0 y = 0 bearing_x = 0 bearing_y = 0 for member in self.members: x += member.x y += member.y bearing_x += math.cos(math.radians(member.bearing)) bearing_y += math.sin(math.radians(member.bearing)) x /= len(self.members) y /= len(self.members) bearing_x /= len(self.members) bearing_y /= len(self.members) return Point(x, y, math.degrees(vector_angle(bearing_x, bearing_y)))
def get_translated(self, shift): translated_samples = [] for sample in self.samples: translated_sample = Point(sample.x + shift.x, sample.y + shift.y) translated_samples.append(translated_sample) return Path(translated_samples)
def parse(inp): g = [] mx = len(inp[0]) my = len(inp) for y, line in enumerate(inp): for x, point in enumerate(line): if point == '#': g.append(Point(x, y)) return g, mx, my
def find_init_snake_tail(self): head = self.find_init_snake_head() tail = [] for (y, x), value in np.ndenumerate(self._cells): if value == Type.SNAKE_TAIL: tail.append(Point(x, y)) tail.sort(key=lambda point: head.distance(point)) return tail
def test_kmeans(): positions = [ [0, 5], # cluster 1 [0, 4], [0, 3], [1.5, 2], # cluster 2 [1.5, 1], [2, 0], [3, 0], [3.5, 1], [3.5, 2], [5, 3], # cluster 3 [5, 4], [5, 5], ] initial_means = [ [2, 6], [2, 3], [4.5, 3], ] points = [ PointWithID(i, positions[i][0], positions[i][1], 0) for i in xrange(len(positions)) ] initial_clusters = [ Cluster(Point(mean[0], mean[1], 0)) for mean in initial_means ] initial_clusters[0].add_member(points[0]) initial_clusters[1].add_member(points[1]) initial_clusters[1].add_member(points[2]) initial_clusters[1].add_member(points[3]) initial_clusters[1].add_member(points[4]) initial_clusters[1].add_member(points[5]) initial_clusters[1].add_member(points[6]) initial_clusters[2].add_member(points[7]) initial_clusters[2].add_member(points[8]) initial_clusters[2].add_member(points[9]) initial_clusters[2].add_member(points[10]) initial_clusters[2].add_member(points[11]) clusters = kmeans(points, initial_clusters, 20, 0.01) expected_clusters = [[0, 1, 2], [3, 4, 5, 6, 7, 8], [9, 10, 11]] id_to_cluster = {} for cluster in clusters: for member in cluster.members: id_to_cluster[member.id] = cluster for group in expected_clusters: cluster = id_to_cluster[group[0]] for member in group: if id_to_cluster[member] != cluster: a = points[group[0]] b = points[member] print 'test_kmeans: expected points {} and {} to be in the same cluster'.format( a, b) print clusters break
def get_neighbours(tile: Tile, tile_dict: dict) -> List[Tile]: lst = [] p = Point(tile.point.x + 1, tile.point.y) if p in tile_dict.keys(): lst.append(tile_dict[p]) p = Point(tile.point.x - 1, tile.point.y) if p in tile_dict.keys(): lst.append(tile_dict[p]) p = Point(tile.point.x, tile.point.y + 1) if p in tile_dict.keys(): lst.append(tile_dict[p]) p = Point(tile.point.x, tile.point.y - 1) if p in tile_dict.keys(): lst.append(tile_dict[p]) return lst
def random_relocate(self, env): print(self.grid_shape) y = random.randint(0, self.grid_shape[0] - 1) x = random.randint(0, self.grid_shape[1] - 1) while env[y, x] != Type.EMPTY: y = random.randint(0, self.grid_shape[0] - 1) x = random.randint(0, self.grid_shape[1] - 1) print(y) self.pos = Point(x, y) self.relocated = True
def get_routes_wrapper(): start_entry = admin_table.find_one({'name': 'start'}) print(start_entry) start = Point(start_entry['location'][0], start_entry['location'][1]) vs = [] for vehicles in vehicles_table.find(): for i in range(0, int(vehicles['quantity'])): vs.append(int(vehicles['size'])) points = [] for person in people_table.find(): person['time'] = str(person['time']) person['_id'] = str(person['_id']) points.append( Point(person['location'][0], person['location'][1], person['priority'] if 'priority' in person else 0, person['severity'] if 'severity' in person else 0)) print(1) print(2) return json.dumps(libroute.get_routes(start, points, vs).get_list())