def _update_transform(self): bounds = self._graph.bounds range = vec2_sub(bounds.hi, bounds.lo) pad = vec2(range.x * 0.2, range.x * 0.1) # pad more on x because of labels lo = vec2_sub(bounds.lo, pad) # move lo down by pad range = vec2_add(range, pad) #increase range by 2*pad range = vec2_add(range, pad) # hehe laziness size = vec2(self.allocation.width, self.allocation.height) if range.x == 0 or range.y == 0: scale = vec2(1, 1) else: scale = vec2_piecewise_div(size, range) def to_screen(v): return ivec2(vec2_piecewise_mul(vec2_sub(v, lo), scale)) def from_screen(in_s): s = vec2(in_s) return vec2_add(vec2_piecewise_div(s, scale), lo) def from_screen_size(in_s): s = vec2(in_s) return vec2_piecewise_div(s, scale) self._to_screen = to_screen self._from_screen = from_screen self._from_screen_size = from_screen_size
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, vec2(Constants.GRID_SIZE * j, Constants.GRID_SIZE * i), vec2(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_common__(self): # innards self._graph = None self._cur_force = vec2(0,0) self._last_drawn_size = vec2(0,0) self._mouse_enter = Event() self._mouse_leave = Event() self._clicked = Event()
def get_bounds(self): if self._bounds_dirty: b = DynObject() b.lo = vec2() b.hi = vec2() if len(self._nodes): b.lo.x = min([n._position.x for n in self._nodes]) b.lo.y = min([n._position.y for n in self._nodes]) b.hi.x = max([n._position.x for n in self._nodes]) b.hi.y = max([n._position.y for n in self._nodes]) self._bounds = b self._bounds_dirty = False # print "Computed bounds: %s - %s" % (str(b.lo),str(b.hi)) return self._bounds
def buildObstacles(graph): # Random Obstacles for i in range(Constants.NBR_RANDOM_OBSTACLES): start = vec2(randrange(0, Constants.WORLD_WIDTH), randrange(0, Constants.WORLD_HEIGHT)) graph.placeObstacle(start, (0, 0, 0)) for j in range(randrange(Constants.NBR_RANDOM_OBSTACLES)): start += vec2((randrange(3) - 1) * Constants.GRID_SIZE, (randrange(3) - 1) * Constants.GRID_SIZE) while (start.x >= Constants.WORLD_WIDTH - Constants.GRID_SIZE or start.y >= Constants.WORLD_HEIGHT - Constants.GRID_SIZE): start += vec2((randrange(3) - 1) * Constants.GRID_SIZE, (randrange(3) - 1) * Constants.GRID_SIZE) graph.placeObstacle(start, (0, 0, 0))
def handleCollision(self, collision_type, brick=None): v = self.velocity.clone() if collision_type in (collision.NO_COLLISION, collision.INSIDE): return elif collision_type == collision.X_AXIS_COLLISION: self.velocity.x = -self.velocity.x elif collision_type == collision.Y_AXIS_COLLISION: self.velocity.y = -self.velocity.y elif collision_type == collision.BOUNCE_BACK: self.velocity = -self.velocity else: # Oo-wee, here comes corner collision. # Things are going to get... physical. # S - center of ball. C - corner of the brick. v = self.velocity.normalized() S = self.position + vec2(Ball.RADIUS, Ball.RADIUS) bpos = vec2( brick[0].position.x * Constants.BRICKSIZE.x + Constants.SIDE_MARGIN, brick[0].position.y * Constants.BRICKSIZE.y + Constants.UPPER_MARGIN) C = { collision.LT_CORNER: bpos, collision.RT_CORNER: bpos + vec2(Constants.BRICKSIZE.x, 0), collision.LB_CORNER: bpos + vec2(0, Constants.BRICKSIZE.y), collision.RB_CORNER: bpos + Constants.BRICKSIZE }[collision_type] # Unit vector, pointing toward the corner that had been hit. unit_i = (C - S).normalized() # Unit vector, perpendicular to 'i'. unit_j = vec2(unit_i.y, -unit_i.x) # Ball's velocity can be written as: v0 = ai + bj # The goal is to turn it into v1 = -ai + bj a = unit_i.x * v.x + unit_i.y * v.y b = unit_i.y * v.x - unit_i.x * v.y self.velocity = -a * unit_i + b * unit_j # ddd = 0 # if abs(self.velocity.x) > abs(self.velocity.y): #self.position.y += Ball.RADIUS - S.y + C.y # print("Y move by {}".format(Ball.RADIUS - S.y + C.y)) # else: #self.position.x += Ball.RADIUS + S.x - C.x # print("X move by {}".format(Ball.RADIUS + S.x - C.x)) dev.report('wbcoll', collision_type, v, self.velocity)
def __init__(self, position, bonus_type=None): """Create new bonus. Initial velocity angle is randomly generated.""" self.position = position - vec2(Constants.BONUS_SIZE // 2, Constants.BONUS_SIZE // 2) # Randomly select the bonus type. if not bonus_type: #bonus_type = randomDict(self.types) bonus_type = randomWithWeights(list( self.types.keys()), [x.weight for x in self.types.values()]) self.type = bonus_type phi = random.random() * math.pi self.velocity = self.START_SPEED * vec2(math.cos(phi), -math.sin(phi))
def __init__(self, position, velocity, binding=None): super().__init__(position, self.SPEED * velocity.normalized()) self.binding = binding # If a ball lies upon a palette, binding represents # the palette. If ball flies, binding=None. if binding: self.offset = 20 position = binding.position + vec2(self.offset, -2 * self.RADIUS)
def update(self): if not self.binding: self.position += self.velocity.normalized( ) * self.SPEED * Constants.DELTA_T else: self.position = self.binding.position + vec2( self.offset, -2 * self.RADIUS)
class Palette(GameObject): """Palette representation.""" TEXTURE = None SIZE = vec2(140, 20) SPEED = 20 def __init__(self): super().__init__( vec2(self.SIZE.x // 2, Constants.WINDOW_SIZE.y - self.SIZE.y - 10)) self.width = self.SIZE.x def move(self, offset): """Used to control palette using a keyboard. Deprecated.""" new_x = self.position.x + offset * self.SPEED self.setPosition(new_x) def setPosition(self, x): if x == self.position.x: return if x < Constants.SIDE_MARGIN: x = Constants.SIDE_MARGIN elif x >= Constants.WINDOW_SIZE.x - self.width - Constants.SIDE_MARGIN: x = Constants.WINDOW_SIZE.x - self.width - Constants.SIDE_MARGIN self.position.x = x dev.report('pmov', self.position.x) def render(self, renderer): if self.TEXTURE is not None: renderer.copy(self.TEXTURE, None, tuple(self.position) + (self.width, self.SIZE.y)) def rect(self): return tuple(self.position) + (self.width, self.SIZE.y)
def __init__(self,name): self.__init_common__() self._name = name self._label = "%s" % name self._position = vec2(0,0) self._border_color = "black" self._background_color = "white" self._text_color = "black"
def renderTechSupport(self, renderer): """Make bonus named Tech Support useful.""" return origin = self.ball.position + vec2(Ball.RADIUS, Ball.RADIUS) versor = self.ball.velocity.normalized() for i in range(20): pos = origin + versor * i*i * 4 pos = int(pos.x), int(pos.y) renderer.draw_point([*pos], colour.Colour.greyscale(0.77))
def _on_expose(self, a, b): style = self.get_style() gdk = gtk.gdk black = gdk.color_parse("black") yellow = gdk.color_parse("yellow") white = gdk.color_parse("white") g = self.window gc = g.new_gc() colormap = self.get_colormap() colors = {} def get_color(c): if colors.has_key(c) == False: colors[c] = colormap.alloc_color(c, False, False) return colors[c] # draw edges gc.foreground = yellow for e in self._graph.edges: n1p = self._to_screen(e.node1._position) n2p = self._to_screen(e.node2._position) gc.line_width = e._weight gc.foreground = get_color(e._color) g.draw_line(gc, n1p.x, n1p.y, n2p.x, n2p.y) # now draw nodes... :( i'm tired! max_w = 100 layout = self.create_pango_layout("") gc.line_width = 1 for n in self._graph.nodes: np = self._to_screen(n._position) layout.set_width(max_w) layout.set_alignment(pango.ALIGN_LEFT) layout.set_text(n._label) layout_size = layout.get_pixel_size() w = layout_size[0] + 4 lo_x = int(np.x - w / 2) h = layout_size[1] lo_y = np.y - h / 2 n._last_drawn_size = self._from_screen_size(vec2(w, h)) gc.foreground = get_color(n._background_color) g.draw_rectangle(gc, True, lo_x, lo_y, w, h) gc.foreground = get_color(n._border_color) g.draw_rectangle(gc, False, lo_x, lo_y, w, h) x = np.x - layout_size[0] / 2 y = np.y - layout_size[1] / 2 gc.foreground = get_color(n._text_color) g.draw_layout(gc, x, y, layout)
def __init__(self, bricks): self.endgame = False self.score = 0 self.lives = 3 self.bonuses = [] self.palette = Palette() self.bricks = bricks self.ball = Ball(vec2(0, 0), vec2(0, 1), self.palette) self.break_reason = None self.spawner = self.Spawner() mx, my = misc.getMousePos() self.palette.setPosition(mx) # Bonus-related flags. self.catch_n_hold = False self.skyfall = False self.fireball = False self.tech_support = True #False
def __call__(self, t): """ Evaluate curve at t """ m_t = 1.0 - t b = m_t * m_t c = t * t d = c * t a = b * m_t b *= 3. * t c *= 3. * m_t return vec2(a * self.x0 + b * self.x1 + c * self.x2 + d * self.x3, a * self.y0 + b * self.y1 + c * self.y2 + d * self.y3)
def _on_expose(self,a,b): style = self.get_style() gdk = gtk.gdk black = gdk.color_parse("black") yellow = gdk.color_parse("yellow") white = gdk.color_parse("white") g = self.window gc = g.new_gc() colormap = self.get_colormap() colors = {} def get_color(c): if colors.has_key(c) == False: colors[c] = colormap.alloc_color(c, False,False) return colors[c] # draw edges gc.foreground = yellow for e in self._graph.edges: n1p = self._to_screen(e.node1._position) n2p = self._to_screen(e.node2._position) gc.line_width = e._weight gc.foreground = get_color(e._color) g.draw_line(gc, n1p.x, n1p.y, n2p.x, n2p.y) # now draw nodes... :( i'm tired! max_w = 100 layout = self.create_pango_layout("") gc.line_width = 1 for n in self._graph.nodes: np = self._to_screen(n._position) layout.set_width(max_w) layout.set_alignment(pango.ALIGN_LEFT); layout.set_text(n._label) layout_size = layout.get_pixel_size() w = layout_size[0] + 4 lo_x = int(np.x - w/2) h = layout_size[1] lo_y = np.y - h/2 n._last_drawn_size = self._from_screen_size(vec2(w,h)) gc.foreground = get_color(n._background_color) g.draw_rectangle(gc, True, lo_x, lo_y, w, h) gc.foreground = get_color(n._border_color) g.draw_rectangle(gc, False, lo_x, lo_y, w, h) x = np.x - layout_size[0] / 2 y = np.y - layout_size[1] / 2 gc.foreground = get_color(n._text_color) g.draw_layout(gc, x, y, layout)
def __call__(self, t): """ Evaluate curve at t """ m_t = 1.0 - t b = m_t * m_t c = t * t d = c * t a = b * m_t b *= 3. * t c *= 3. * m_t return vec2(a*self.x0 + b*self.x1 + c*self.x2 + d*self.x3, a*self.y0 + b*self.y1 + c*self.y2 + d*self.y3)
def handlePaletteCollision(self, collision_type, palette): if self.binding or collision_type == collision.NO_COLLISION: return if collision_type == collision.Y_AXIS_COLLISION: v = self.velocity.clone() a = self.position.x + self.RADIUS - palette.position.x w = palette.width eta_prim = -math.pi / 3.0 * math.cos(a * math.pi / w) self.velocity = vec2(math.sin(eta_prim), -math.cos(eta_prim)) dev.report('pcoll', collision_type, v, self.velocity) elif collision_type == collision.X_AXIS_COLLISION: self.handleCollision(collision.X_AXIS_COLLISION)
def circleBoxCollision(circle_pos, circle_radius, box): """Check whether a circle collides with a box.""" r = circle_radius center = circle_pos + vec2(circle_radius, circle_radius) if (box[0] - r <= center.x <= box[0] + box[2] + r) and ( box[1] - r <= center.y <= box[1] + box[3] + r): # The circle does collide. This we know. if center.y < box[1]: # LTZ, TZ or RTZ if center.x < box[0]: if (vec2(box[0], box[1]) - center).length() <= r: return LT_CORNER #LTZ elif center.x < box[0] + box[2]: return Y_AXIS_COLLISION #TZ else: if (vec2(box[0] + box[2], box[1]) - center).length() <= r: return RT_CORNER #RTZ elif center.y < box[1] + box[3]: # LZ, RZ or inside the box if center.x < box[0]: return X_AXIS_COLLISION #LZ elif center.x < box[0] + box[2]: return INSIDE else: return X_AXIS_COLLISION #RZ else: # LBZ, BZ, RBZ if center.x < box[0]: if (vec2(box[0], box[1] + box[3]) - center).length() <= r: return LB_CORNER #LBZ elif center.x < box[0] + box[2]: return Y_AXIS_COLLISION #BZ else: if (vec2(box[0] + box[2], box[1] + box[3]) - center).length() <= r: return RB_CORNER #RBZ return NO_COLLISION
def _update_transform(self): bounds = self._graph.bounds range = vec2_sub(bounds.hi, bounds.lo) pad = vec2(range.x * 0.2, range.x * 0.1) # pad more on x because of labels lo = vec2_sub(bounds.lo,pad) # move lo down by pad range = vec2_add(range,pad) #increase range by 2*pad range = vec2_add(range,pad) # hehe laziness size = vec2(self.allocation.width,self.allocation.height) if range.x == 0 or range.y == 0: scale= vec2(1,1) else: scale = vec2_piecewise_div(size,range) def to_screen(v): return ivec2(vec2_piecewise_mul(vec2_sub(v,lo),scale)) def from_screen(in_s): s = vec2(in_s) return vec2_add(vec2_piecewise_div(s,scale),lo) def from_screen_size(in_s): s = vec2(in_s) return vec2_piecewise_div(s,scale) self._to_screen = to_screen self._from_screen = from_screen self._from_screen_size = from_screen_size
def flatten_forward_iterative(self, n=50): """ Dumb segmentation """ h = 1.0 / n; fph = 3 * (self.p1 - self.p0) * h fpphh = (6 * self.p0 - 12 * self.p1 + 6 * self.p2) * h * h fppphhh = (-6 * self.p0 + 18 * self.p1 - 18 * self.p2 + 6 * self.p3) * h * h * h P = [(self.x0,self.y0)] p = vec2(self.x0,self.y0) for i in range(1,n-1): p += fph + fpphh/2. + fppphhh/6. P.append((p.x,p.y)) fph = fph + fpphh + fppphhh/2. fpphh = fpphh + fppphhh P.append((self.x3,self.y3)) return P
def flatten_forward_iterative(self, n=50): """ Dumb segmentation """ h = 1.0 / n fph = 3 * (self.p1 - self.p0) * h fpphh = (6 * self.p0 - 12 * self.p1 + 6 * self.p2) * h * h fppphhh = (-6 * self.p0 + 18 * self.p1 - 18 * self.p2 + 6 * self.p3) * h * h * h P = [(self.x0, self.y0)] p = vec2(self.x0, self.y0) for i in range(1, n - 1): p += fph + fpphh / 2. + fppphhh / 6. P.append((p.x, p.y)) fph = fph + fpphh + fppphhh / 2. fpphh = fpphh + fppphhh P.append((self.x3, self.y3)) return P
def buildGates(graph): X = 0 Y = 1 # Add the gates to the game # pick one end, then pick the second end about 50 spaces away (pick a direction, generate the far end for gate in Constants.GATES: graph.placeObstacle(vec2(gate[0][X], gate[0][Y]), (0, 255, 0)) graph.placeObstacle(vec2(gate[1][X], gate[1][Y]), (255, 0, 0)) print("Placing Obstacles: " + str(gate[0]) + " " + str(gate[1])) # Add the final pen based on the final gate finalGate = gate[-2:] # If the gate is horizontally arranged if finalGate[0][Y] == finalGate[1][Y]: # If the green gate (the first gate) is on the right, paddock goes "up" if finalGate[0][X] > finalGate[1][X]: direction = -1 else: direction = 1 for y in range(finalGate[0][Y] + direction * 16, finalGate[0][Y] + direction * 112, direction * 16): graph.placeObstacle(vec2(finalGate[0][X], y), (0, 0, 0)) graph.placeObstacle(vec2(finalGate[1][X], y), (0, 0, 0)) for x in range(finalGate[0][X] + direction * 16, finalGate[1][X], direction * 16): graph.placeObstacle(vec2(x, finalGate[0][Y] + direction * 96), (0, 0, 0)) # If the gate is vertically arranged else: # If the green gate (the first gate) is on the bottom, paddock goes "right" if finalGate[0][Y] < finalGate[1][Y]: direction = -1 else: direction = 1 for x in range(finalGate[0][X] + direction * 16, finalGate[1][X] + direction * 112, direction * 16): graph.placeObstacle(vec2(x, finalGate[0][Y]), (0, 0, 0)) graph.placeObstacle(vec2(x, finalGate[1][Y]), (0, 0, 0)) for y in range(finalGate[0][Y] - direction * 16, finalGate[1][Y], -direction * 16): graph.placeObstacle(vec2(finalGate[0][X] + direction * 96, y), (0, 0, 0))
def from_screen_size(in_s): s = vec2(in_s) return vec2_piecewise_div(s, scale)
def p3(self): return vec2(self.x3, self.y3)
def update(self, playerlocation, world_objs): projectile = None self.awareness = self.rect.copy() self.awareness = self.awareness.inflate(500, 500) dpos = vec2(self.x, self.y) dir = 'down' direction = self.intelligence(playerlocation) if direction[0] > 75: dir = 'left' elif direction[0] < -75: dir = 'right' if direction[1] < -75: dir = 'down' elif direction[1] > 75: dir = 'up' self.angle = self.angle_lookup.get(dir) if self.state != gameobj.ATTACKING: if self.type == 'melee': self.set_state(gameobj.WALKING) elif self.type == 'projectile': self.set_state(gameobj.IDLE) if self.state == gameobj.ATTACKING and self.type == 'projectile': if self.attack_timer == 0: projectile = projectileobj((self.rect.centerx, self.rect.centery), (10, 10), direction) if not self.modal: if self.awareness.collidepoint(playerlocation.center): egameobj.Gameobj.update(self, dpos, world_objs, self.type, False) direction = self.intelligence(playerlocation) if direction[0] < 0: self.x = 1 elif direction[0] > 0: self.x = -1 else: self.x = 0 if direction[1] < 0: self.y = 1 elif direction[1] > 0: self.y = -1 else: self.y = 0 else: check = egameobj.Gameobj.update(self, dpos, world_objs, self.type) if check == True: if random.randint(0, 1) == 1: self.x = -1 * self.x else: self.x = 1 * self.x if random.randint(0, 1) == 1: self.y = -1 * self.y else: self.y = 1 * self.y else: egameobj.Gameobj.update(self,dpos,world_objs, self.type) if self.lock == True: self.image.blit(self.lockarrow, (50, 0)) return projectile
def from_screen(in_s): s = vec2(in_s) return vec2_add(vec2_piecewise_div(s, scale), lo)
def __init__(self, parent, node, manage_function, delete_function, x=0, y=0): #Initialize members self.node = node num_args = len(node.get_arguments()) #Create the frame, name, and delete buttons self.pos = vec2(x, y) self.frame = ttk.Frame(parent, relief="solid", borderwidth=2) self.name_label = ttk.Label(self.frame, text=node.get_name()) self.name_label.grid(column=0, row=0, sticky=(N, W, S)) self.name_label.bind("<B1-Motion>", lambda e: self.place(e.x, e.y)) delete_button = ttk.Button(self.frame, text="X", width=1, command=self.destroy) delete_button.grid(row=0, column=1, sticky=(N, E, S)) self.frame.place(x=self.pos.x, y=self.pos.y, anchor=NW) self.frame.bind("<B1-Motion>", lambda e: self.place(e.x, e.y)) self.frame.bind("<1>", lambda e: skip()) self.name_label.bind("<1>", lambda e: skip()) #Set callbacks self.manage_function = manage_function self.delete_function = delete_function #Display arguments self.vars = [] for i in range(len(node.get_arguments())): self.vars.append(StringVar()) arg = node.get_arguments()[i] label = ttk.Label(self.frame, text=arg) label.grid(row=i + 1, column=0, sticky=(E, W)) entry = ttk.Entry(self.frame, width=18 - len(arg), textvariable=self.vars[i]) entry.bind( "<Return>", lambda e, n=i: self.node.argument(n, self.vars[n].get())) entry.bind( "<FocusOut>", lambda e, n=i: self.node.argument(n, self.vars[n].get())) entry.grid(row=i + 1, column=1, sticky=(E, W)) #Display return value if node.has_return(): self.return_val = StringVar() label = ttk.Label(self.frame, text="return").grid(row=num_args + 1, column=0, sticky=(E, W)) entry = ttk.Entry(self.frame, width=12, textvariable=self.return_val) entry.bind("<Return>", lambda e: self.node.return_value(self.return_val.get())) entry.bind("<FocusOut>", lambda e: self.node.return_value(self.return_val.get())) entry.grid(row=num_args + 1, column=1, sticky=(E, W)) ttk.Button(self.frame, text="True", command=lambda: self.manage(True)).grid(column=0, row=num_args + 2, sticky=(E, W)) ttk.Button(self.frame, text="False", command=lambda: self.manage(False)).grid(column=1, row=num_args + 2, sticky=(E, W))
def p2(self): return vec2(self.x2, self.y2)
def p1(self): return vec2(self.x1,self.y1)
def from_screen_size(in_s): s = vec2(in_s) return vec2_piecewise_div(s,scale)
def update(self): self.position += vec2( self.velocity.x * Constants.DELTA_T, self.velocity.y * Constants.DELTA_T + Constants.G_ACCEL * Constants.DELTA_T * Constants.DELTA_T) self.velocity.y += Constants.G_ACCEL * Constants.DELTA_T
(randrange(3) - 1) * Constants.GRID_SIZE) graph.placeObstacle(start, (0, 0, 0)) ################################################################################# # Main Functionality ################################################################################# pygame.init() screen = pygame.display.set_mode( (Constants.WORLD_WIDTH, Constants.WORLD_HEIGHT)) clock = pygame.time.Clock() sheepImage = pygame.image.load('sheep.png') dogImage = pygame.image.load('dog.png') bounds = vec2(Constants.WORLD_WIDTH, Constants.WORLD_HEIGHT) # Setup the graph graph = Graph() # Setup the dog # dog = player(dogImage, vec2(Constants.WORLD_WIDTH * .5, Constants.WORLD_HEIGHT * .5), # vec2(Constants.DOG_WIDTH, Constants.DOG_HEIGHT), (0, 255, 0), # Constants.DOG_SPEED, Constants.DOG_ANGULAR_SPEED) dog = player(cm.screen_size / 2, cm.player_spd, cm.wolf_spr, graph) # Setup the sheep (only 1 for now...) herd = [] # sheep = Sheep(sheepImage, vec2(randrange(int(bounds.x * .4), int(bounds.x * .6)), # randrange(int(bounds.y * .6), int(bounds.y * .8))), # vec2(Constants.DOG_WIDTH, Constants.DOG_HEIGHT), (0, 255, 0), Constants.SHEEP_SPEED, Constants.SHEEP_ANGULAR_SPEED)
def __init__(self, spritesheet, size, location): """ Parent class for all game objects. Inherits from pygame's Sprite Class and the States class. :type self: pygame.sprite.Sprite :param spritesheet: path to the spritesheet for the gameobj :param size: size of the object :param spritesheet_dim: size of each sprite on the spritesheet (in pixels) :param location: where to place the object """ # Parent constructor call SPRITE.Sprite.__init__(self) assert isinstance(spritesheet, str) assert isinstance(size, tuple) # Animation controls: # anim_delay: controls animation speed #anim_pos: controls which image in the animation string to display #anim_images: dictionary containing all animations #anim_delay: Controls how fast the current animation plays #angle: angle to rotate the current image so things make sense #current_anim: list of the frames for the current animation #image: the image that is currently being drawn self.anim_images = defaultdict(list) self.extract_sprites(spritesheet, size) self.anim_delay = .1 self.type = None self.anim_pos = 0 self.angle = 0 self.angle_lookup = {} self.image = None directions = ['', 'up', 'right', 'left', 'down', 'upleft', 'upright', 'downleft', 'downright'] angle = [0, 0, -90, 90, 180, 45, -45, 135, -135] for i in range(0, len(directions)): self.angle_lookup.update({directions[i]: angle[i]}) self.current_anim = self.anim_images.get('IDLE') #External game control: #rect: bounding rectangle for detection #state: current state of the object can take on: # IDLE: Default # RUNNING # ATTACKING # DAMAGED # STUNNED #pending_IDLE: used for movement control (maybe deleted?) #state_change: a boolean that allows the update loop to know # if the state was changed and do appropriate updates #vel: a vec2 that determines how fast the object moves #accel: how fast the vel is accelerating #decel: how fast the vel decelerating #walk_speed: how fast the object can move when state = WALKING #run_speed: how fast the object can move when state = RUNNING #max_speed: a generic variable that is set to walk_speed or run_speed self.rect = pygame.Rect(location, size) self.previous_position = (self.rect.centerx, self.rect.centery) self.attack_timer = 0 self.swordflag = False self.state = IDLE self.state_mod = None self.pending_IDLE = False self.state_change = False self.speed = 0 self.vel = vec2(0.0, 0.0) self.accel = .5 self.decel = .2 self.walk_speed = 3 self.run_speed = 7 self.max_speed = 0 self.modal = False self.damagetimer = 0 self.tick = 0 self.attacked = False self.bump = GAME_GLOBALS.BUMP self.bump.set_volume(0.2) self.can_sound = True self.attackbuffer = 0 self.attackpos = 1 self.freeze = False self.currentattack =''
def restart(self): self.ball = Ball(vec2(0, 0), vec2(0, 1), self.palette) pos = self.palette.position self.palette = Palette() self.palette.position = pos
def __init__(self): super().__init__( vec2(self.SIZE.x // 2, Constants.WINDOW_SIZE.y - self.SIZE.y - 10)) self.width = self.SIZE.x
weight = property(lambda self: self._weight, set_weight) # innards def _set_graph(self,g): self._graph = g def _on_changed(self,needsLayout=False): if self._graph: self._graph._on_changed(needsLayout) # Graph ########################################################################### _KK = 0.1 _INIT_ITER = 0 _INITIAL_TEMPERATURE = 0.05 _TEMP_CURVE = [ vec2(_INIT_ITER, _INITIAL_TEMPERATURE), vec2(_INIT_ITER+100, _INITIAL_TEMPERATURE * 0.5), vec2(_INIT_ITER+125,_INITIAL_TEMPERATURE * 0.00), vec2(_INIT_ITER+1000000,0.0) ] class Graph(object): def __init__(self): self._nodes = NamedItemList() self._nodes.changed.add_listener(self._on_changed) self._nodes.item_added.add_listener(self._on_node_added) self._edges = NamedItemList() self._edges.changed.add_listener(self._on_changed) self._edges.item_added.add_listener(self._on_edge_added) self._init_layout() self._bounds = None
def p2(self): return vec2(self.x2,self.y2)
def from_screen(in_s): s = vec2(in_s) return vec2_add(vec2_piecewise_div(s,scale),lo)
def p3(self): return vec2(self.x3,self.y3)
def p0(self): return vec2(self.x0,self.y0)
def center(self): sp = self.screenPos() return vec2(sp[0] + Constants.BRICKSIZE.x // 2, sp[1] + Constants.BRICKSIZE.y // 2)