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 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 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 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('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('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 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 get_closest_offset(self, point: Point): closest_offset = math.inf closest_distance = point.get_distance(self.samples[0]) for offset in np.linspace(0, 1, 50): cur_point = self.get_point_on_path(offset) distance = point.get_distance(cur_point) if distance <= closest_distance: closest_offset = offset closest_distance = distance return closest_offset
def _updateKeys(self): """ Adjust position and scale of each display key based on current display rect. """ displayRect = self._getDisplayRect() self._scroll.width = self._scroll.height = 0 self._scrollUnit = displayRect.size scale = self._getScale(displayRect) if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE: print scale contentRect = deepcopy(displayRect) if scale > 0: adjustedSize = Size( self._contentSize.width * scale * self._zoom, self._contentSize.height * scale * self._zoom) contentRect.width = adjustedSize.width contentRect.height = adjustedSize.height contentRect = contentRect.CenterIn(displayRect) contentRect.x /= scale contentRect.y /= scale for displayKey in self._displayKeys.values(): displayKey.scaled = displayKey.unscaled * self._zoom displayKey.scaled.OffsetXY(contentRect.x, contentRect.y) else: maxWidth = displayRect.width / scale origin = Point(0, 0) for displayKeyHandle in self._orderedHeyHandles: displayKey = self._displayKeys[displayKeyHandle] if origin.x + self._keySize.width > maxWidth: origin.x = 0 origin.y += self._keySize.height + self._keySpacing.height displayKey.unscaled.x = origin.x displayKey.unscaled.y = origin.y displayKey.scaled = displayKey.unscaled * scale self._scroll.width = max( self._scroll.width, displayKey.scaled.x + displayKey.scaled.width) self._scroll.height = max( self._scroll.height, displayKey.scaled.y + displayKey.scaled.height) displayKey.scaled.OffsetXY(displayRect.x, displayRect.y) origin.x += self._keySize.width + self._keySpacing.width self._scrollUnit.width = min(self._scrollUnit.width, displayKey.scaled.width) self._scrollUnit.height = min(self._scrollUnit.height, displayKey.scaled.height) self._scroll.width += self._border * 2 self._scroll.height += self._border * 2 self._scrollUnit.width += self._keySpacing.width * scale self._scrollUnit.height += self._keySpacing.height * scale
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 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 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 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 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 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 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 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 getNextStep(self, updatedMap, currentPosition): if len(currentPosition) == 0: return [] self.board = updatedMap self.numberOfSteps += 1 # Perform a check every 6 steps if self.numberOfSteps > 15 and self.numberOfSteps % 6 == 0: # stop coverage? if self.continueCoverage() == False: return [] openDirections = self.getOpenDirections(currentPosition) if len(openDirections) > 1: if len(self.branchingStack) == 0 or (len(self.branchingStack) > 0 and self.branchingStack[-1] != (currentPosition)): self.branchingStack.append(currentPosition) directionFacing = "" if len(openDirections) > 0: directionFacing = openDirections[0] self.updateVisitedMap(currentPosition, directionFacing) # print("*************************************") # print(openDirections) # print("*************************************") # print(self.visitedMap) for direction in openDirections: prevStepPriority = self.stepPriority[0][direction] while True: newPoint = Point.addTuples(currentPosition, Directions.getCoordinate(direction)) openDirections = self.getOpenDirections(newPoint) if (len(openDirections) > 0 and self.stepPriority[0][openDirections[0]] == prevStepPriority): self.updateVisitedMap(newPoint, direction) currentPosition = newPoint else: # print(newPoint) return newPoint else: # backtracking # print("got back to branching point") if len(self.branchingStack) > 0: returnPoint = self.branchingStack.pop() print(returnPoint) return returnPoint else: # print("no more moves") return []
def __init__(self, pos, name, colors, world, conf): self.pos = Point(pos[0], pos[1], world) self.name = name self.colors = colors self.world = world self.conf = conf self.health = conf['tank_health'] self.fuel = conf['tank_fuel'] self.arsenal = copy.deepcopy(conf['tank_arsenal']) self.active_weapon = 0 self.weapon_display_timer = 0 self.angle = pi / 4 self.isdead = False self.active_shots = 0 self.isactive = False self.power = 0.50 self.pic = [r' ___ ', r'/lol\=', r'OOOOO ']
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 _updateKeys(self): """ Adjust position and scale of each display key based on current display rect. """ drawingArea = self._getDrawingArea() self._scroll.width = self._scroll.height = 0 self._scrollUnit = drawingArea.size scale = self._getScale(drawingArea) if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE: contentArea = self._getContentArea() for displayKey in self._displayKeys.values(): displayKey.scaled = displayKey.unscaled * scale displayKey.scaled.Offset(contentArea.origin) displayKey.labelRect = Rect(*displayKey.unscaled) displayKey.labelRect.Deflate(0.2, 0.2) displayKey.labelRect *= scale displayKey.labelRect.Offset(contentArea.origin) self._fontSize = scale * 0.37 else: maxWidth = drawingArea.width / scale origin = Point(0, 0) for displayKeyHandle in self._orderedKeyHandles: displayKey = self._displayKeys[displayKeyHandle] if origin.x + self._keySize.width > maxWidth: origin.x = 0 origin.y += self._keySize.height + self._keySpacing.height displayKey.unscaled.x = origin.x displayKey.unscaled.y = origin.y displayKey.scaled = displayKey.unscaled * scale self._scroll.width = max(self._scroll.width, displayKey.scaled.x + displayKey.scaled.width) self._scroll.height = max(self._scroll.height, displayKey.scaled.y + displayKey.scaled.height) displayKey.scaled.Offset(drawingArea.origin) displayKey.labelRect = Rect(*displayKey.unscaled) displayKey.labelRect.Deflate(0.2, 0.2) displayKey.labelRect *= scale displayKey.labelRect.Offset(drawingArea.origin) origin.x += self._keySize.width + self._keySpacing.width self._scrollUnit.width = min(self._scrollUnit.width, displayKey.scaled.width) self._scrollUnit.height = min(self._scrollUnit.height, displayKey.scaled.height) self._scroll.width += self._border * 2 self._scroll.height += self._border * 2 self._scrollUnit.width += self._keySpacing.width * scale self._scrollUnit.height += self._keySpacing.height * scale
def _updateKeys(self): """ Adjust position and scale of each display key based on current display rect. """ displayRect = self._getDisplayRect() self._scroll.width = self._scroll.height = 0 self._scrollUnit = displayRect.size scale = self._getScale(displayRect) if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE: print scale contentRect = deepcopy(displayRect) if scale > 0: adjustedSize = Size(self._contentSize.width * scale * self._zoom, self._contentSize.height * scale * self._zoom ) contentRect.width = adjustedSize.width contentRect.height = adjustedSize.height contentRect = contentRect.CenterIn(displayRect) contentRect.x /= scale contentRect.y /= scale for displayKey in self._displayKeys.values(): displayKey.scaled = displayKey.unscaled * self._zoom displayKey.scaled.OffsetXY(contentRect.x, contentRect.y) else: maxWidth = displayRect.width / scale origin = Point(0, 0) for displayKeyHandle in self._orderedHeyHandles: displayKey = self._displayKeys[displayKeyHandle] if origin.x + self._keySize.width > maxWidth: origin.x = 0 origin.y += self._keySize.height + self._keySpacing.height displayKey.unscaled.x = origin.x displayKey.unscaled.y = origin.y displayKey.scaled = displayKey.unscaled * scale self._scroll.width = max(self._scroll.width, displayKey.scaled.x + displayKey.scaled.width) self._scroll.height = max(self._scroll.height, displayKey.scaled.y + displayKey.scaled.height) displayKey.scaled.OffsetXY(displayRect.x, displayRect.y) origin.x += self._keySize.width + self._keySpacing.width self._scrollUnit.width = min(self._scrollUnit.width, displayKey.scaled.width) self._scrollUnit.height = min(self._scrollUnit.height, displayKey.scaled.height) self._scroll.width += self._border * 2 self._scroll.height += self._border * 2 self._scrollUnit.width += self._keySpacing.width * scale self._scrollUnit.height += self._keySpacing.height * scale
def get_bricks_by_layer(self): xdim, ydim, zdim = self.shape grid_iter_by_y_layer = it.product(*(range(dim) for dim in (ydim, zdim, xdim))) bricks_by_layer_asc = (Point.as_int((x, y, z)) for (y, z, x) in grid_iter_by_y_layer if self[(x, y, z)]) return bricks_by_layer_asc
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 __init__(self, pos, name, colors, world, conf): self.pos = Point(pos[0], pos[1], world) self.name = name self.colors = colors self.world = world self.conf = conf self.health = conf['tank_health'] self.fuel = conf['tank_fuel'] self.arsenal = copy.deepcopy(conf['tank_arsenal']) self.active_weapon = 0 self.weapon_display_timer = 0 self.angle = pi/4 self.isdead = False self.active_shots = 0 self.isactive = False self.power = 0.50 self.pic =[ r' ___ ', r'/lol\=', r'OOOOO ']
def reset(self): self.pos = Point.origin() self.facing = Direction.up
class Tank(): def __init__(self, pos, name, colors, world, conf): self.pos = Point(pos[0], pos[1], world) self.name = name self.colors = colors self.world = world self.conf = conf self.health = conf['tank_health'] self.fuel = conf['tank_fuel'] self.arsenal = copy.deepcopy(conf['tank_arsenal']) self.active_weapon = 0 self.weapon_display_timer = 0 self.angle = pi/4 self.isdead = False self.active_shots = 0 self.isactive = False self.power = 0.50 self.pic =[ r' ___ ', r'/lol\=', r'OOOOO '] def draw(self, win): if(self.isdead): self.pic =[ ''' ___ ''', ''' /rip\ ''', ''' OOOOO '''] elif(self.angle < pi*0.10): self.pic =[ ''' ___ ''', ''' /lol\=''', ''' OOOOO '''] elif(self.angle < pi*0.40): self.pic =[ ''' __// ''', ''' /lol\ ''', ''' OOOOO '''] elif(self.angle < pi*0.5): self.pic =[ ''' _|| ''', ''' /lol\ ''', ''' OOOOO '''] elif(self.angle < pi*0.60): self.pic =[ ''' ||_ ''', ''' /lol\\''', ''' OOOOO'''] elif(self.angle <= pi*0.90): self.pic =[ ''' \\\\__ ''', ''' /lol\\''', ''' OOOOO'''] else: self.pic =[ ''' ___ ''', '''=/lol\\''', ''' OOOOO'''] # Draw Crosshair if (self.isactive): p = self.muzzle for i in range(10): p += (cos(self.angle) * (self.power*4.0), -sin(self.angle) * (self.power*4.0)) dot = p.int() try: if(i == 9): win.addstr(dot.y, dot.x, '✜', curses.color_pair(self.colors)) else: win.addstr(dot.y, dot.x, '·', curses.color_pair(self.colors)) except curses.error: pass # Draw Selected Weapon h, w = win.getmaxyx() if(self.weapon_display_timer > 0): weapon = self.arsenal[self.active_weapon] weaponwin = win.derwin(3, 7, clamp(self.pos.y - 5, 0, h-3), clamp(self.pos.x - 3, 0, w-7)) try: weaponwin.box() if(weapon[1] == -1): weaponwin.addstr(1, 3, weapon[0].char) else: weaponwin.addstr(1, 2, weapon[0].char + ':' + str(weapon[1])) except curses.error: pass weaponwin.refresh() # Draw Tanks x_off = -int(max([len(line) for line in self.pic])/2) y_off = -tanksize for n,line in enumerate(self.pic): for k, char in enumerate(line): draw = self.pos + (x_off + k, y_off + n) if(char != ' ' and draw.in_box(0, w, 0, h)): win.addstr(draw.y, draw.x, char) if(self.pos == self.pos.clamp(0, w-1, 0, h-1)): win.addstr(self.pos.y, self.pos.x, self.name[-1], curses.color_pair(self.colors)) def update(self, win): self.weapon_display_timer = max(0, self.weapon_display_timer - 1) if(all( [not self.world.check_collision(self.pos+(xi,1)) for xi in range(-tanksize, tanksize+1)])): self.pos += (0, 1) self.muzzle = self.pos + ((1+tanksize)*cos(self.angle), -max(1,(tanksize)*sin(self.angle))) if(self.health <= 0): self.isdead = True self.isactive = False def processkey(self, key, win): h, w = win.getmaxyx() if (key == ord(' ')): weapon = self.arsenal[self.active_weapon] if (weapon[1] != 0): self.shoot() if(weapon[1] != -1): weapon[1] = max(0, weapon[1] - 1) return True else: self.weapon_display_timer = 50 elif (key == curses.KEY_LEFT): if self.angle <= pi/2: self.angle = pi - self.angle else: self.move(-1) elif (key == curses.KEY_RIGHT): if self.angle >= pi/2: self.angle = pi - self.angle else: self.move(1) elif (key == curses.KEY_UP): if (self.angle <= pi/2): self.angle = min(pi/2.001, self.angle+0.01) else: self.angle = max(pi/1.999, self.angle-0.01) elif (key == curses.KEY_DOWN): if (self.angle <= pi/2): self.angle = max(0, self.angle-0.01+pi/8)-pi/8 else: self.angle = min(pi*9/8, self.angle+0.01) elif (key == ord('+')): self.power = min(1.00, self.power+0.01) elif (key == ord('-')): self.power = max(0.00, self.power-0.01) elif (key in map(lambda k : ord(str(k)), range(10))): n = int(chr(key)) self.active_weapon = (n-1) % len(self.arsenal) self.weapon_display_timer = 50 return False def shoot(self): shot = self.arsenal[self.active_weapon][0]( self.muzzle, self.angle, self.power*self.conf['tank_power'], self, self.conf) self.world.gameobjects += [shot] self.isactive = False def move(self, direction): if self.fuel > 0: if not any([self.world.check_collision(self.pos + (direction*(tanksize + 1), -i)) for i in range(tanksize+1)]): self.pos += (direction, 0) self.fuel -= 1 elif not any([self.world.check_collision(self.pos + (direction*(tanksize + 1), -i)) for i in range(1, tanksize+2)]): self.pos += (direction, -1) self.fuel -= 1
def at_start(self): return self.facing == Direction.up and self.pos == Point.origin()