def __init__ ( self, X, Y, limits) : self.width = 5 # dimensions self.height = 5 self.hasStroke = False # color properties self.strokeColor = color(255,255,255) self.hasFill = True self.fillColor = color(255,255,255) self.velX = 3 # initial velocity self.velY = 3 self.x = X self.y = Y self.limits = limits self.ox = X self.oy = Y self.xcenter = X self.ycenter = Y self.rectangle = Rectangle(self.width, self.height, self.hasStroke, self.strokeColor, self.hasFill, self.fillColor) self.rectangle.setPosition(self.x, self.y)
import csv import sys import Rectangle # Main method file_name = '' # get the command line arguments if len(sys.argv) == 2: file_name = sys.argv[1] print(file_name) # parse in the csv to rectangle objects rectangles = {} rectangles = Rectangle.get_rectangles(file_name) for rect in rectangles: rect.print()
def computerThrow(computerVelocity, computerAngle, inputVelocity, \ angle, computerBananaX, computerBananaY, userBananaX, userBananaY, \ userMonkey, originalUBX, originalUBY, originalUserMonkey, \ originalCBX, originalCBY, originalComputerMonkey,\ userScore, computerScore, vdone, adone, computerAngleHigh, computerAngleLow): #sets the boundaries of the game board lowerBorder = 600 leftBorder = -20 #variables determining the direction of the throw unit vector c = -1 k = 1 #time step variable gameTime = 0 #creates an arbitrary area for computer banana computerBanana = Rectangle.Rectangle(0, 0, 30, 45) #initialize distance to maximum value minDistance = 10000000000 #determines the new round timeForNewRound = True #game is still in play gameOver = False #continue updating position of banana until banana intersects monkey or #travels out of bounds while (int(computerBananaY) <= lowerBorder and int(computerBananaX) >= \ leftBorder) and (not computerBanana.intersects(userMonkey)): #update time intervals of throw gameTime += 0.1 #reverses direction of banana when it exceeds maximum height if computerBananaY <= 0: k = -1 #initialize throw and update position according to displacment formula computerBananaX = computerBananaX + c * (computerVelocity * gameTime * \ math.cos(math.radians((computerAngleHigh + computerAngleLow)/2))) computerBananaY = computerBananaY - k * (computerVelocity * gameTime * \ math.sin(math.radians((computerAngleHigh + computerAngleLow)/2))) #contiunes redrawing the board with each position of the banana Draw.clear() scoreBoard(computerScore, userScore) userInput(inputVelocity, angle) drawBoard(userBananaX, userBananaY) drawBoard(computerBananaX, computerBananaY) Draw.show(40) #creates area of computerBanana using Rectangle.py with last position of #computerBanana computerBanana = Rectangle.Rectangle(computerBananaX-33, \ computerBananaY+3, 30, 45) #Computer Strategy #Computes the distance from computerbanana to usermonkey distance = computerBanana.distance(userMonkey) #Finds the minimum distance from computerbanana to usermonkey if distance < minDistance: minDistance = distance closestComputerBananaX = computerBananaX #Binary Search on last computer angle computerAngle = (computerAngleHigh + computerAngleLow)/2 #determine under or over throw based on closest x position of banana #using Rectangle.py method for center of monkey area x coordinate if closestComputerBananaX < userMonkey.getCenterX(): #Banana over thrown-increase angle computerAngleLow = computerAngle else: #Banana under thrown-decrease angle computerAngleHigh = computerAngle #checks to see if computer banana hits user monkey and updates the score if computerBanana.intersects(userMonkey): computerScore += 1 #displays exploading monkey monkeyHit("computer", userBananaX, userBananaY, \ computerBananaX, computerBananaY, computerScore, userScore, \ inputVelocity, angle, originalUserMonkey, originalComputerMonkey) #checks if the game is over if userScore >= 3 or computerScore >= 3: #redraws the final state of the board with monkey explosion Draw.clear() scoreBoard(computerScore, userScore) userInput(inputVelocity, angle) drawBoard(userBananaX, userBananaY) drawBoard(computerBananaX, computerBananaY) monkeyHit("computer", userBananaX, userBananaY, \ computerBananaX, computerBananaY, computerScore, userScore, \ inputVelocity, angle, originalUserMonkey, originalComputerMonkey) #displays the winner of the game end(computerScore, userScore) Draw.show(2000) #ends the game gameOver = True #start new round if game not over and monkey hit (inputVelocity, angle, vdone, adone, originalUBX, originalUBY, \ originalUserMonkey, originalCBX, originalCBY, originalComputerMonkey, computerAngleHigh, computerAngleLow)\ = newRound(computerScore, userScore, inputVelocity, angle, vdone, adone, computerAngleHigh, computerAngleLow) #restore banana position for new throw (userBananaX, userBananaY, userMonkey, computerBananaX, computerBananaY, \ computerMonkey) = restoreBananaPosition(originalUBX, originalUBY, \ originalUserMonkey, originalCBX, originalCBY, originalComputerMonkey) #contiune with new throw for same round else: #not time for new round timeForNewRound = False #pass game state to the caller return userBananaX, userBananaY, userMonkey, computerBananaX, \ computerBananaY, originalUBX, originalUBY, originalUserMonkey, \ originalCBX, originalCBY, originalComputerMonkey,\ computerScore, inputVelocity, \ angle, vdone, adone, timeForNewRound, gameOver, computerAngleHigh, computerAngleLow, computerAngle
# draw the banana y coordinate based on the new monkey position if bananaX == 0: bananaX = monkeyChooser*buildingWidth + bananaOffSetX #else: keep bananaX, don't change banana position # draw the banana y coordinate based on the new monkey position if bananaY == 0: bananaY = buildingYNumbers[monkeyChooser] - monkeyHeight + bananaOffSetY #else: keep bananaX, don't change banana position #compute the coordinates of the monkey monkeyX = monkeyChooser*buildingWidth monkeyY = buildingYNumbers[monkeyChooser] - monkeyHeight #creates area of monkey using Rectangle.py monkeyArea = Rectangle.Rectangle(monkeyX+10, monkeyY, monkeyWidth, \ monkeyHeight) #draws monkeys and bananas banana(bananaX, bananaY) monkey(monkeyX, monkeyY) return monkeyChooser, bananaX, bananaY, monkeyArea # rotate points in a shape def _rotatePoint(x, y, angle): r = math.sqrt(x*x + y*y) theta = math.atan2(y, x) theta += angle newx = math.cos(theta) * r newy = math.sin(theta) * r
canvas.pack() text = canvas.create_text(X_TEXT, Y_TEXT, text="Use the WASD buttons to speed up, slow down and turn the tank, use mouse movement\nto " "rotate the tank tower, use LMB to shoot and score points hitting targets," " use Esc to exit.", font=(FONT_TEXT, FONT_SIZE_TEXT), fill=TEXT_COLOR_ON_TOP) border = canvas.create_rectangle(FIELD_X, FIELD_Y, FIELD_X + FIELD_WIDTH, FIELD_Y + FIELD_HEIGHT, fill=COLOR_FIELD, outline=COLOR_BORDER, width=2 * BORDER_WIDTH) score = create_score(START_VALUE_SCORE, COLOR_SCORE, X_SCORE, Y_SCORE, FONT_SCORE, FONT_SIZE_SCORE) tank1 = Tank.create_tank(FIELD_X + FIELD_WIDTH / 2, FIELD_Y + FIELD_HEIGHT / 2, TANK_HEIGHT, TANK_WIDTH, COLOR_TANK, TOWER_TANK_SIZE, TOWER_TANK_SIZE, COLOR_TOWER_TANK, GUN_HEIGHT, GUN_WIDTH, COLOR_GUN, 0, 0, START_ROTATE_TANK) draw_tank(tank1) mouse_position = Rectangle.create_point(FIELD_X + FIELD_WIDTH / 2, FIELD_Y + FIELD_HEIGHT / 2) last_time = time.time() time_for_target = time.time() time_for_bullet = time.time() root.bind("<Key>", process_key) root.bind("<Button-1>", process_shot) root.bind("<Motion>", mouse_position_memorization) Test_rectangle.tests() update_physics() root.mainloop()
#now we will get the first two cordiniates for the canvas heightOfCanvas = allVertex[0][0] widthOfCanvas = allVertex[0][1] #A list of the rectangle cordinates rectangleCoordinates = allVertex[1::] #now create the Rectangle objects for each rectangle coordinate rectangleObjects = [] * len(rectangleCoordinates) for y in rectangleCoordinates: heightOfRectangle = y[0] #print(heightOfRectangle) widthOfRectangle = y[1] #print(widthOfRectangle) z = Rectangle(heightOfRectangle, widthOfRectangle, 0, 0) rectangleObjects.append(z) #print(z.getHeight) #shows us how to get the height of the first rectangle object #print(rectangleObjects[0].getHeight()) #now create the canvas class and we might need to make a list of the heightOfCanvas and widthOfCanvas #canvas = CustomCanvasMaker(heightOfCanvas, heightOfCanvas) tupleOfCanvasSize = (heightOfCanvas, widthOfCanvas) #print(tupleOfCanvasSize) RectObjToPlaceInCanvas = pack(rectangleObjects, tupleOfCanvasSize) canvas = CustomCanvasMaker(heightOfCanvas, heightOfCanvas, RectObjToPlaceInCanvas)
class Commands: rectangle = Rectangle() ellipse = Ellipse() def __init__(self, canvas, current_shape_list): """ :param canvas: """ self.canvas = canvas self.current_shape_list = current_shape_list self.imported_groups = [] self.TAG_ID = 1 # stack for redo/undo self.command_stack = [] self.command_stack_pointer = 0 self.command_stack_name_index = 0 self.command_stack_args_index = 1 self.current_command = None def set_current_shape_list(self, shape_list): self.current_shape_list = shape_list return self def get_current_command(self): """ :return: """ return self.current_command def set_current_command(self, command): """ :param command: :return: """ self.current_command = command def create(self, shape, coordinates): """ :param shape: :param coordinates: :return: """ args = (coordinates, self.canvas) if shape is Rectangle.shapeName: rectangle = Figure(*args, 'rectangle', self.rectangle) rectangle.strategy = RectangleStrategy() rectangle.draw() self.command_stack_push(COMMAND_REDRAW, rectangle) return rectangle elif shape is Ellipse.shapeName: ellipse = Figure(*args, 'ellipse', self.ellipse) ellipse.strategy = EllipseStrategy() ellipse.draw() self.command_stack_push(COMMAND_REDRAW, ellipse) return ellipse @staticmethod def redraw(shape): """ Function to redraw a shape after a undo or redo action :param shape: :return: """ shape.descriptions = [] shape.draw() def select(self, coordinates, group_list): """ :param group_list: :param coordinates: :return: """ closest_shape = self.canvas.find_closest(coordinates[0], coordinates[1]) if closest_shape: if len(self.canvas.gettags(*closest_shape)) < 2: return None selected_tag = self.canvas.gettags(*closest_shape)[self.TAG_ID] shape_object = None for shape in self.current_shape_list: if shape.tag == selected_tag: shape_object = shape if not shape_object: return None for group in group_list: return self.get_shape_in_nested_group(group, shape_object) return [shape_object] return None def get_shape_in_nested_group(self, group, shape_object): """ Gets a shape from nested groups :param group: :param shape_object: :return: """ for shape in group.get_all(): if isinstance(shape, Group): return self.get_shape_in_nested_group(shape, shape_object) elif shape.tag == shape_object.tag: return group.get_all() return [shape_object] def move(self, shapes_list, coordinates, push_to_command_stack=True): """ Execute the move command :param push_to_command_stack: :param shapes_list: :param coordinates: :return: """ if not shapes_list: return False if push_to_command_stack: self.command_stack_push(COMMAND_MOVE, shapes_list, coordinates, False) for shape in shapes_list: shape.accept(Move(coordinates)) def resize(self, shape_list, coordinates, push_to_command_stack=True): """ this was literally done by trail and error, thanks to the poor documentation of tkinter :param push_to_command_stack: :param shape_list: :param coordinates: :return: """ if not shape_list: return False if push_to_command_stack: self.command_stack_push(COMMAND_RESIZE, shape_list, coordinates, False) for shape in shape_list: (x0, y0, x1, y1) = self.canvas.coords(shape.tag) width = x0 / coordinates[0] height = y0 / coordinates[1] x1 = x0 / width y1 = y0 / height shape.accept(Resize([x0, y0, x1, y1])) def command_stack_push(self, command_name, *args): """ Pushes command to the command stack :param command_name: :return: """ self.command_stack.insert(0, [command_name, args]) def undo(self): """ Handles the undo command :return: """ self.canvas.delete(ALL) if self.command_stack_pointer + 1 <= len(self.command_stack): self.command_stack_pointer += 1 # prevent out of bounds stack pointer self.redraw_canvas() def redo(self): """ Handles the redo command :return: """ self.canvas.delete(ALL) if self.command_stack_pointer - 1 >= 0: self.command_stack_pointer -= 1 # prevent negative stack pointer self.redraw_canvas() def add_figures_to_shape_list(self, shape): """ Sorts imported figures to groups and shapes :param shape: :return: """ for figure in shape.get_all(): if type(figure) == Group: if figure not in self.imported_groups: self.imported_groups += [figure] self.add_figures_to_shape_list(figure) else: if figure not in self.current_shape_list: self.current_shape_list += [figure] def import_(self, filename, push_to_command_stack=True): """ Handles the import command :return: """ shapes = IO(self.canvas).parse_file(filename) if push_to_command_stack: self.command_stack_push(COMMAND_IMPORT, filename, False) for shape in shapes: if type(shape) == Group: if shape not in self.imported_groups: self.imported_groups += [shape] self.add_figures_to_shape_list(shape) else: self.current_shape_list += [shape] for shape in shapes: if isinstance(shape, Group): for _shape in shape.get_all(): if isinstance(_shape, Group) or _shape.tag is None: continue _shape.draw() if shape.descriptions is not None: shape.render_description() else: shape.draw() if shape.descriptions is not None: shape.render_description() return self.current_shape_list + self.imported_groups def export_(self, shapes, groups): """ Execute the export command :return: """ return IO(self.canvas).shapes_to_text(shapes, groups) def group(self, shapes, push_to_command_stack=True): """ Handles the group command :param push_to_command_stack: :param shapes: :return: """ if not shapes: return False group = Group(self.canvas) for shape in shapes: group.add(shape) if push_to_command_stack: self.command_stack_push(COMMAND_GROUP, shapes, False) return group def redraw_canvas(self): """ Redraws the canvas based on the stack pointer :return: """ for command_index in range( len(self.command_stack) - 1, self.command_stack_pointer - 1, -1): command = self.command_stack[command_index] command_name = command[self.command_stack_name_index] command_args = command[self.command_stack_args_index] getattr(self, command_name)(*command_args) @staticmethod def replace_figure_with_group(shape_list, group_list): """ Returns the group a figure is part of :param shape_list: :param group_list: :return: """ new_shape_list = [] temp_shape_list = shape_list[:] for shape in temp_shape_list[:]: for group in group_list: for group_shape in group.get_all(): if group_shape is shape: temp_shape_list.remove(group_shape) if group not in new_shape_list: new_shape_list.insert(0, group) return temp_shape_list + new_shape_list def ornament(self, selected_shapes, description, position, group_list, push_to_command_stack=True): """ Execute the description command :param group_list: :param push_to_command_stack: :param selected_shapes: :param description: :param position: :return: """ if push_to_command_stack: self.command_stack_push(COMMAND_DESCRIPTION, selected_shapes, description, position, group_list, False) for selected_shape in self.replace_figure_with_group( selected_shapes, group_list): if not push_to_command_stack: #undo or redo triggered. Reset descriptions in Figure object to prevent double drawing selected_shape.descriptions = None if position == "Left": selected_shape.set_description(Left(Description(description))) elif position == "Right": selected_shape.set_description(Right(Description(description))) elif position == "Top": selected_shape.set_description(Top(Description(description))) elif position == "Bottom": selected_shape.set_description(Bottom( Description(description))) selected_shape.render_description()
def getWindowRectangleAsRectangle(): return Rectangle.Rectangle(getWindowRectangle().x, getWindowRectangle().y, getWindowRectangle().width, getWindowRectangle().height)
def Analyse(acquire_new, result_path, source_path, obj_mag, material, ftr, presentation): steps = [ '', '', '1_Image_Acquisition', 'Global_Histogram', '2_Segmentation', '3_ROIs', '4_Local_Histogram' ] full_path = [] for step in steps: full_path.append(os.path.join(result_path, step)) #print (full_path) if not acquire_new: full_path[2] = source_path list_of_samples = os.listdir(full_path[2]) stats_file = open(os.path.join(result_path, 'ListOfFlakes.csv'), "a+") stat = "LithoCoord,Contrast,EstLayers,BoundingBoxArea(um^2)\n" stats_file.write(stat) stats_file.close() for sample in list_of_samples: #sample_path = os.path.join(full_path[2], str(sample)) print(sample) ContourObj = Contour.Contour(str(sample), full_path[2], result_path, obj_mag, material, ftr) if material == 'Sb': ContourObj.edges_gluey(obj_mag=obj_mag, ftr=0, glue_remover=True, presentation=presentation) else: ContourObj.edges_gluey(obj_mag, ftr, glue_remover=False, presentation=presentation) #self.ContourObj.segmentation(ftr=self.filter) ROIObj = Rectangle.Rectangle((full_path[4] + '\\Contours'), sample, full_path[2], result_path, obj_mag, material, ftr) X_Y_FS = ROIObj.markROIs(True, presentation) list_of_chunks = os.listdir((full_path[5] + '\\' + sample[:-4])) list_of_chunk_numbers = [] if material == 'C': for chunk, ant in zip(list_of_chunks, X_Y_FS): stat = str(sample)[:-4] + '_' HistogramObj = Histogram.Histogram( str(chunk), (full_path[5] + '\\' + sample[:-4]), (full_path[6]), result_path, obj_mag) #self.HistogramObj = Histogram.Histogram(str(chunk), (full_path[5]+'\\'+sample), (full_path[6]+'\\'+sample), self.result_path,obj_mag=self.obj_mag) #deeper directory contrast, layers = HistogramObj.saveLocalHistogram( ftr, material, presentation) if not contrast is None and len(contrast) > 3: chunk_number = int(chunk[-6:-4]) stat += str(chunk_number).zfill(2) + ',' + contrast stat += ',' + layers list_of_chunk_numbers.append(chunk_number) if ant[3] in list_of_chunk_numbers: #TB = 'T' if (ant[1]<256) else ('B') #LR = 'L' if (ant[0]<256) else ('R') stat += "," + str(ant[2]) + "\n" stats_file = open( os.path.join(result_path, 'ListOfFlakes.csv'), "a+") stats_file.write(stat) stats_file.close() cv2.destroyAllWindows()
from Rectangle import* pygame.init() gameDisplay = pygame.display.set_mode((display_width, display_height)) clock = pygame.time.Clock() # -------------------- # SPAWNING # -------------------- # spawn WALLS wall1 = Rectangle(0, 0, display_width, 10) wall2 = Rectangle(0, display_height-10, display_width, 10) wall3 = Rectangle(0, 10, 10, display_height-20) wall4 = Rectangle(display_width-10, 10, 10, display_height-20) obstacles = [wall1, wall2, wall3, wall4] # spawn OBSTACLES for i in range(num_obstacles): x0 = random.randint(0, display_width) y0 = random.randint(0, display_height) obstacle_width = random.randint(obstacle_min_width, obstacle_max_width) obstacle_height = random.randint(obstacle_min_height, obstacle_max_height) obstacle = Rectangle(x0, y0, obstacle_width, obstacle_height) check = 0 while check < len(obstacles): check = 0 for x in obstacles: if obstacle.poly_collides_rect(x): x0 = random.randint(0, display_width) y0 = random.randint(0, display_height)
class Ball: def __init__ ( self, X, Y, limits) : self.width = 5 # dimensions self.height = 5 self.hasStroke = False # color properties self.strokeColor = color(255,255,255) self.hasFill = True self.fillColor = color(255,255,255) self.velX = 3 # initial velocity self.velY = 3 self.x = X self.y = Y self.limits = limits self.ox = X self.oy = Y self.xcenter = X self.ycenter = Y self.rectangle = Rectangle(self.width, self.height, self.hasStroke, self.strokeColor, self.hasFill, self.fillColor) self.rectangle.setPosition(self.x, self.y) def display( self, paddle, bricks ): self.updatePosition( paddle, bricks ) self.rectangle.display() def updatePosition( self, paddle, bricks ) : # add velocity to position self.x += self.velX self.y += self.velY # collision with limits if(self.x <= self.limits[0] or self.x >= self.limits[2]-self.width): self.velX = -self.velX self.x = constrain(self.x, self.limits[0], self.limits[2]-self.width) if(self.y <= self.limits[1] or self.y >= self.limits[3]-self.height): self.velY = -self.velY self.y = constrain(self.y, self.limits[1], self.limits[3]-self.height) self.xcenter = self.x+self.width/2 self.ycenter = self.y+self.height/2 # collision with paddle result = self.checkCollisionWithRectangle(paddle.rectangle) # if collides on top, control direction of ball # if (result == 1): # if(self.xcenter < paddle.rectangle.x1+paddle.rectangle.width/2): # if(self.velX>0): # self.velX = -self.velX # else: # if(self.velX<0): # self.velX = -self.velX # collision with bricks if (result == 0) : for i in range( len(bricks) ): if(bricks[i].imAlive): res = self.checkCollisionWithRectangle(bricks[i].rectangle) if not(res == 0): bricks[i].die() break self.ox = self.x self.oy = self.y self.rectangle.setPosition(self.x, self.y) def checkCollisionWithRectangle( self, R ): """ Collision Detection Function result: 0 = no collision, 1 = top, 2 = right, 3 = bottom, 4 = left, 5 = couldn't detect which side """ result = 0 if (R.doesPointTouchMe(self.xcenter, self.ycenter)): # which side did it collide trajectory = LineSeg(self.xcenter,self.ycenter,self.ox+self.width/2,self.oy+self.height/2) result = R.whatSideDoesLineTouch(trajectory, self.velX, self.velY) # top if(result==1): self.velY = -self.velY self.y = R.y1-self.height # right elif(result==2): self.velX = -self.velX self.x = R.x2 # bottom elif(result==3): self.velY = -self.velY self.y = R.y2 # left elif(result==4): self.velX = -self.velX self.x = R.x1-self.width else: result = 5 return result
def calculate_bbox_area_of_an_annotation(anno): bbox = CroppingRegionProposal.get_bbox(anno) bbox_by_2point = rect.Rectangle.convert_bbox_to_2points(bbox) rect_bbox = rect.Rectangle(*bbox_by_2point) return rect_bbox.get_area()
import Rectangle s_rect = Rectangle.PyRectangle.hello() s_rect.dayin() rect = Rectangle.PyRectangle(2, 5, 0x22, 0x11) # x0, y0, x1, y1 = 1, 3, 5, 4 print(rect.getArea()) rect.move(1, 2) rect.dayin() size = rect.getSize() print(size) rect.getShape()
import Circle,Rectangle radius = input("Enter radius: ") length = input("Enter length: ") width = input("Enter width: ") radius = float(radius) length = float(length) width = float(width) myCircle = Circle.Circle(radius) myRectangle = Rectangle.Rectangle(length, width) myCircle.getArea() myCircle.getCircumference() myRectangle.getArea() myRectangle.getPerimeter() print("Circumference of circle with radius %.3f is %.3f" %(radius,myCircle.circumference)) print("Area of circle with radius %.3f is %.3f" %(radius,myCircle.area)) print("Perimeter of rectangle with length of %d and width%3d is %d" %(length, width, myRectangle.perimeter)) print("Area of rectangle with length of %d and width%3d is %d" %(length, width, myRectangle.area))
from Rectangle import * from Triangle import * rect = Rectangle() trey = Triangle() rect.set_values(3, 5) trey.set_values(4, 5) print('Rect area:', rect.area()) print('trey area:', trey.area())
def creerRectangles(self, n=4): for i in range(n): x = random.randrange(350) + 50 y = random.randrange(350) + 50 self.rectangles.append(Rectangle(self, x, y))
import Rectangle import Square import Circle r1 = Rectangle.Rect(3, 2, 'blue') print(r1) r2 = Circle.Circ(5, 'green') print(r2) r3 = Square.Squar(5, 'red') print(r3)
class Sprite(Entity): def __init__(self, x=0, y=0): self.x = x self.y = y self.texture = Texture() self.width = 0 self.height = 0 self.visible = True # collision self.boundary = Rectangle() # graphics self.angle = 0 self.scale = 1 # not used self.opacity = 1 self.mirrored = False self.flipped = False # physics self.physics = None # animation self.animation = None # actions self.actionList = [] ###### basic methods def setPosition(self, x, y): self.x = x self.y = y def moveBy(self, dx, dy): self.x += dx self.y += dy def setTexture(self, texture): self.texture = texture self.width = texture.width self.height = texture.height # override from GameObject class def draw(self, displaySurface): if ( not self.visible ): return # if no modifications are made to the image, draw and return if ( not(self.opacity == 1) and not self.mirrored and not self.flipped and not(self.angle == 0) ): modifiedRect = self.texture.image.get_rect( center=(self.x, self.y) ) displaySurface.blit( self.texture.image, modifiedRect ) return # if any modifications are made to the image, make a local copy modifiedImage = self.texture.image.copy() # mirror/flip, if needed if ( self.mirrored or self.flipped ): modifiedImage = pygame.transform.flip( modifiedImage, self.mirrored, self.flipped ) # rotate, if needed # Note: rotating the image results in a larger image (larger bounding rectangle) # which must be used as destination rectangle when blitting the image (for proper alignment) if ( not(self.angle == 0) ): modifiedImage = pygame.transform.rotozoom( modifiedImage, -self.angle, self.scale ) # set opacity, if needed if ( not(self.opacity == 1) ): blendImage = pygame.Surface( (self.texture.width, self.texture.height), pygame.SRCALPHA) alpha = int(self.opacity * 255) blendImage.fill( (255, 255, 255, alpha) ) modifiedImage.blit( blendImage, (0, 0), special_flags=pygame.BLEND_RGBA_MULT ) #modifiedImage.set_alpha( int(self.opacity * 255) ) modifiedRect = modifiedImage.get_rect( center=(self.x, self.y) ) displaySurface.blit( modifiedImage, modifiedRect ) ###### collision methods def getBoundary(self): self.boundary.setValues(self.x - self.width/2, self.y - self.height/2, self.width, self.height) return self.boundary def isOverlapping(self, other): return self.getBoundary().overlaps( other.getBoundary() ) def preventOverlap(self, other): if ( self.isOverlapping(other) ): mtv = self.getBoundary().getMinTranslationVector( other.getBoundary() ) self.moveBy( -mtv.x, -mtv.y ) ###### angle methods def rotateBy(self, da): self.angle += da def moveAtAngle(self, distance, angleDegrees): self.x += distance * math.cos(angleDegrees * math.pi/180) self.y += distance * math.sin(angleDegrees * math.pi/180) def moveForward(self, distance): self.moveAtAngle(distance, self.angle) ###### behavior methods def boundToScreen(self, screenWidth, screenHeight): if (self.x - self.width/2 < 0): self.x = self.width/2 if (self.x + self.width/2 > screenWidth): self.x = screenWidth - self.width/2 if (self.y - self.height/2 < 0): self.y = self.height/2 if (self.y + self.height/2 > screenHeight): self.y = screenHeight - self.height/2 def wrapToScreen(self, screenWidth, screenHeight): if (self.x + self.width/2 < 0): self.x = screenWidth + self.width/2 if (self.x - self.width/2 > screenWidth): self.x = -self.width/2 if (self.y + self.height/2 < 0): self.y = screenHeight + self.height/2 if (self.y - self.height/2 > screenHeight): self.y = -self.height/2 def isOnScreen(self, screenWidth, screenHeight): offScreen = (self.x + self.width/2 < 0) \ or (self.x - self.width/2 > screenWidth) \ or (self.y + self.height/2 < 0) \ or (self.y - self.height/2 > screenHeight) return (not offScreen) ###### physics methods def setPhysics(self, accValue, maxSpeed, decValue): self.physics = Physics(accValue, maxSpeed, decValue) # requires physics object to be initialized def bounceAgainst(self, other): if ( self.isOverlapping(other) ): mtv = self.getBoundary().getMinTranslationVector( other.getBoundary() ) # prevent overlap self.moveBy(mtv.x, mtv.y); # assume surface perpendicular to displacement surfaceAngle = mtv.getAngle() + 90; # adjust velocity self.physics.bounceAgainst(surfaceAngle); ###### action methods def addAction(self, action): self.actionList.append(action) # override from Entity class def act(self, deltaTime): # update physics, position (based on velocity and acceleration) # if it has been initialized for this sprite if ( not(self.physics == None) ): self.physics.positionVector.x = self.x self.physics.positionVector.y = self.y self.physics.update(deltaTime) self.x = self.physics.positionVector.x self.y = self.physics.positionVector.y # update animation, current texture # if it has been initialized for this sprite if ( not(self.animation == None) ): self.animation.update(deltaTime) self.texture = self.animation.currentTexture # update all actions (in parallel, by default) actionListCopy = self.actionList[:] for action in actionListCopy: finished = action.apply(self, deltaTime) if (finished): self.actionList.remove(action) ###### animation methods def setAnimation(self, animation): self.animation = animation self.setTexture( animation.currentTexture )
# Name: dd32.py # Date: 12/13/2013 # Author: Thorin Schmidt from Rectangle import * print("Welcome to the Rectangle Module Tester!") print("First, I'm going to make two rectangles,") print("one with no parameters, and the second") print("with values 6 and 9. Let's see what happens!") input("\nPress a key to see the fun!") rectangle1 = Rectangle() rectangle2 = Rectangle(6,9) print("\nFirst, the length and width:") print("\tRectangle 1 length: ", rectangle1.get_length(), "width: ", rectangle1.get_width()) print("\tRectangle 2 length: ", rectangle2.get_length(), "width: ", rectangle2.get_width()) input("\nPress a key to continue") print("\nNow the perimeters:") print("\tRectangle 1 Perimeter:", rectangle1.perimeter) print("\tRectangle 2 Perimeter:", rectangle2.perimeter) input("\nPress a key to continue") print("\nNow the areas:") print("\tRectangle 1 Area:", rectangle1.area) print("\tRectangle 2 Area:", rectangle2.area)
# main workstation area as canvas # size of the WIDTH = 700 HEIGHT = 280 my_canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="white", bd=5) my_canvas.grid(row=5, column=0, columnspan=6) rect_spray1 = my_canvas.create_rectangle(100, 160, 200, 170, fill="yellow") #first spray rect_spray2 = my_canvas.create_rectangle(350, 160, 450, 170, fill="yellow") #second spray # this following rectangles are different part of the workstations rect1 = Rectangle(my_canvas, 20, 200, 300, 220, "red", "ws1") #conveyor 1 rect1_end = Rectangle(my_canvas, 300, 170, 305, 220, "yellow", "es1") # base coating machine rect2 = Rectangle(my_canvas, 305, 200, 500, 220, "cyan", "ws2") #conveyor 2 rect2_end = Rectangle(my_canvas, 500, 170, 505, 220, "green", "es2") # main coating machine # my_canvas.itemconfigure(rect_spray1, fill='red') # text in the canvas to indicate some key parts my_canvas.create_text(150, 250, text=" conveyor 1") my_canvas.create_text(400, 250, text=" conveyor 2") my_canvas.create_text(150, 150, text=" Spray 1") my_canvas.create_text(400, 150, text=" spray 2") my_canvas.create_text(300, 230, text=" base") my_canvas.create_text(493, 230, text=" main") my_canvas.create_text(52, 160, text=" load")
from Square import * from Rectangle import * from Cube import * from Box import * shapes = list() shapes.append(Square("Square 1", 10)) shapes.append(Rectangle("Rectangle 1", 20, 10)) shapes.append(Cube("Cube 1", 10)) shapes.append(Box("Box 1", 20, 10, 5)) print("Number of shapes: ", Shape.count) print("-" * 50) for current in shapes: print(current) print("-" * 50)
class surface: def__init__(self,"image.png",x,y,width,height): self.rect = Rectangle.rectangle(x,y,height,width) self.image = "image.png"
def pack(allRect, canvasSize): allRectangles = allRect listOfHeightAndWidth = [] * len(allRectangles) for aR in allRectangles: print(aR) heightOfRectObj = aR.getHeight() #print(heightOfRectObj) widthOfRectObj = aR.getWidth() #print(widthOfRectObj) heightandWidthInAList = [heightOfRectObj, widthOfRectObj] listOfHeightAndWidth.append(heightandWidthInAList) #print(listOfHeightAndWidth) packer = newPacker() for r in listOfHeightAndWidth: packer.add_rect(*r) canvasSizeForBin = canvasSize bins = canvasSizeForBin height = canvasSizeForBin[0] width = canvasSizeForBin[1] #print(bins) prints out a tuple of the height of canvas and width packer.add_bin(height, width) packer.pack() nbins = len(packer) abin = packer[0] height = abin.height width = abin.width rect = packer[0][0] x = rect.x y = rect.y w = rect.width h = rect.height #print("below will show us where to put things in") CorrectVertex = [] * len(allRectangles) all_rects = packer.rect_list() for rect in all_rects: #print(rect) b, x, y, w, h, rid = rect addAllTheVertex = [h, w, x, y] CorrectVertex.append(addAllTheVertex) #print(h) #print(w) #print(x) #print(y) #print(rid) #print(CorrectVertex) #rectangleObjects = [] * len(rectangleCoordinates) #for y in rectangleCoordinates: #heightOfRectangle = y[0] #print(heightOfRectangle) #widthOfRectangle = y[1] #print(widthOfRectangle) #z = Rectangle(heightOfRectangle, widthOfRectangle, 0, 0) #rectangleObjects.append(z) #print(z.getHeight) returnRectObjects = [] * len(allRectangles) for changeObjects in CorrectVertex: finalHeigh = changeObjects[0] finalWidth = changeObjects[1] finalX = changeObjects[2] finalY = changeObjects[3] addRectObj = Rectangle(finalHeigh, finalWidth, finalX, finalY) addRectObj.setX(finalX) addRectObj.setY(finalY) print("Here is the real high and width x and y") print(finalHeigh) print(finalWidth) print(finalX) print(finalY) returnRectObjects.append(addRectObj) print() print() print() print() print("France France France France France ") for returedObj in returnRectObjects: h = returedObj.getHeight() w = returedObj.getWidth() x = returedObj.getX() y = returedObj.getY() print(h) print(w) print(x) print(y) print() print() print() print() return returnRectObjects
def checkCollisions(self, r): box = Rectangle( Point(r.center.x - self.halfSize, r.center.y - self.halfSize), Point(r.center.x + self.halfSize, r.center.y + self.halfSize)) boxes = self.qt.searchBox(box) boxes.sort(key=lambda tup: tup[1], reverse=True)
from 16.8 import Rectangle, Square, Circle rec1 = Rectangle(3, 4) rec2 = Rectangle(12, 5) square1 = Square(5) square2 = Square(10) i = 0 circle1 = Circle(66) circle2 = Circle(83) print(f"Rectangle 1 area = {rec1.get_area_rectangle()}") print(f"Rectangle 2 area = {rec2.get_area_rectangle()}") print(f"Square 1 area = {square1.get_area_square()}") print(f"Square 2 area = {square2.get_area_square()}") print(f"Circle 1 area = %0.2f" % circle1.get_area_circle()) print(f"Circle 2 area = %0.2f" % circle2.get_area_circle()) print() figures = [rec1, square1, rec2, square2, i, circle1, circle2] ri = 0 si = 0 ci = 0 for fig in figures: if isinstance(fig, Rectangle): ri += 1 print(fig.name, ri, "area =", fig.get_area_rectangle()) elif isinstance(fig, Square): si += 1 print(fig.name, si, "area =", fig.get_area_square())
def move_tank(tank: Tank, dr: Rectangle.Point) -> None: Rectangle.move_rectangle(tank.body.rectangle, dr) Rectangle.move_rectangle(tank.tower.rectangle, dr) Rectangle.move_rectangle(tank.gun.rectangle, dr)
def userThrow(inputVelocity, angle, userBananaX, userBananaY, \ computerBananaX, computerBananaY, computerMonkey, originalUBX, originalUBY, originalUserMonkey, \ originalCBX, originalCBY, originalComputerMonkey, userScore, computerScore,\ computerTurn, vdone, adone, computerAngleHigh, computerAngleLow): #sets the boundaries of the game board lowerBorder = 600 rightBorder = 1100 #variables determining the direction of the throw unit vector c = 1 k = 1 #time step variable gameTime = 0 #creates an arbitrary area for user banana userBanana = Rectangle.Rectangle(0, 0, 30, 45) #game is still in play gameOver = False #continue updating position of banana until banana intersects monkey or #travels out of bounds while (userBananaY <= lowerBorder and userBananaX <= rightBorder) and \ (not userBanana.intersects(computerMonkey)): #update time intervals of throw gameTime += 0.1 #reverses direction of banana when it exceeds maximum height if userBananaY <= 0: k = -1 #initialize throw and update position according to displacment formula userBananaX = userBananaX + c * (inputVelocity * gameTime * \ math.cos(math.radians(angle))) userBananaY = userBananaY - k * (inputVelocity * gameTime * \ math.sin(math.radians(angle))) #contiunes redrawing the board with each position of the banana Draw.clear() scoreBoard(computerScore, userScore) userInput(inputVelocity, angle) drawBoard(computerBananaX, computerBananaY) drawBoard(userBananaX, userBananaY) Draw.show(40) #creates area of userBanana using Rectangle.py with last position of #userBanana userBanana = Rectangle.Rectangle(userBananaX-33, userBananaY+3, 30, 45) #checks to see if user banana hits computer monkey and updates the score if userBanana.intersects(computerMonkey): userScore += 1 #displays exploading monkey monkeyHit("user", userBananaX, userBananaY, \ computerBananaX, computerBananaY, computerScore, userScore, \ inputVelocity, angle, originalUserMonkey, originalComputerMonkey) #checks if the game is over if userScore >= 3 or computerScore >= 3: #redraws the final state of the board with monkey explosion Draw.clear() scoreBoard(computerScore, userScore) userInput(inputVelocity, angle) drawBoard(userBananaX, userBananaY) drawBoard(computerBananaX, computerBananaY) monkeyHit("user", userBananaX, userBananaY, \ computerBananaX, computerBananaY, computerScore, userScore, \ inputVelocity, angle, originalUserMonkey, originalComputerMonkey) #displays the winner of the game end(computerScore, userScore) Draw.show(2000) #ends the game gameOver = True #start new round if game not over and monkey hit (inputVelocity, angle, vdone, adone, originalUBX, originalUBY, \ originalUserMonkey, originalCBX, originalCBY, originalComputerMonkey, computerAngleHigh, computerAngleLow)\ = newRound(computerScore, userScore, inputVelocity, angle, vdone, adone, computerAngleHigh, computerAngleLow) #restore banana position for new throw (userBananaX, userBananaY, userMonkey, computerBananaX, computerBananaY, \ computerMonkey) = restoreBananaPosition(originalUBX, originalUBY, \ originalUserMonkey, originalCBX, originalCBY, originalComputerMonkey) #contiune with new throw for same round else: #sets the computer's turn computerTurn = True #not time for new round timeForNewRound = False #pass game state to the caller return userBananaX, userBananaY, computerBananaX, computerBananaY, computerMonkey, \ originalUBX, originalUBY, originalUserMonkey, \ originalCBX, originalCBY, originalComputerMonkey, userScore, computerTurn, inputVelocity, \ angle, vdone, adone, gameOver, computerAngleHigh, computerAngleLow
def tests(): x_centre_1 = 0 y_centre_1 = 0 height_1 = 20 width_1 = 40 start_rotate_1 = pi / 4 color_1 = None x_centre_2 = 40 y_centre_2 = 40 height_2 = 20 width_2 = 20 start_rotate_2 = 0 color_2 = None x_centre_3 = 100 y_centre_3 = 100 height_3 = 20 width_3 = 20 start_rotate_3 = 0 color_3 = None x_centre_4 = 40 y_centre_4 = 40 height_4 = 20 width_4 = 20 start_rotate_4 = pi / 4 color_4 = None rectangle_1 = Rectangle.create_rectangle(x_centre_1, y_centre_1, height_1, width_1, start_rotate_1, color_1) rectangle_2 = Rectangle.create_rectangle(x_centre_2, y_centre_2, height_2, width_2, start_rotate_2, color_2) rectangle_3 = Rectangle.create_rectangle(x_centre_3, y_centre_3, height_3, width_3, start_rotate_3, color_3) rectangle_4 = Rectangle.create_rectangle(x_centre_4, y_centre_4, height_4, width_4, start_rotate_4, color_4) assert Rectangle.intersection(rectangle_1, rectangle_1) is True assert Rectangle.intersection(rectangle_2, rectangle_1) is True assert Rectangle.intersection(rectangle_1, rectangle_2) is True assert Rectangle.intersection(rectangle_1, rectangle_3) is False assert Rectangle.intersection(rectangle_2, rectangle_3) is False assert Rectangle.intersection(rectangle_1, rectangle_4) is True assert Rectangle.intersection( rectangle_2, rectangle_4 ) is False # Должно быть True, но из-за самого метода определения соприкосновения там False
def main(): #polygon dot = [100, 100, 150, 200, 300, 400, 500, 500] poly = Polygon(dot, WHITE) poly.draw_me(canvas) #right triangle x = 500 y = 100 side1 = 100 side2 = 100 color = "tan1" ri_tri = Right_Tri(x, y, side1, side2, color) ri_tri.draw_me(canvas) print "The right triangle's area is: ", ri_tri.calc_area() #Isosceles triangle x = 500 y = 500 base = 600 side = 500 color = BLACK is_tri = Isosceles_Tri(x, y, base, side, color) is_tri.draw_me(canvas) print "The Isosceles triangle's area is: ", is_tri.calc_area() #Equilateral Triangle x = 500 y = 500 side1 = 300 color = GREEN equ_tri = Equilateral_Triangle(x, y, side1, color) equ_tri.draw_me(canvas) print "The Equilateral Triangle's area is: ", equ_tri.calc_area() #square x = 500 y = 500 side1 = 150 color = RED sqr = Square(x, y, side1, color) sqr.draw_me(canvas) print "The square's area is: ", sqr.calc_area() #Rectangle re = [300, 300, 150, 50] x = 300 y = 300 side1 = 150 side2 = 50 color = GREEN rec = Rectangle(x, y, side1, side2, color) rec.draw_me(canvas) print "The Rectangle's area is: ", rec.calc_area() #Parallelogram x = 500 y = 400 side1 = 100 side2 = 50 angle = 150 color = RED para = Parallelogram(x, y, side1, side2, angle, color) para.draw_me(canvas) print "The Parallelogram area is: ", para.calc_area() #Circle x = 200 y = 200 radius = 200 color = RED cr = Circle(x, y, radius, color) cr.draw_me(canvas) print "The Circle area is: ", cr.calc_area() #Ellipse x = 200 y = 200 hor_rad = 200 rad = 100 color = BLUE el = Ellipse(x, y, hor_rad, rad, color) el.draw_me(canvas) print "The Ellipse area is: ", el.calc_area() root.mainloop()
import Rectangle as rect rectA = rect.Rectangle() print("RectA Perimeter: " + str(rectA.getPerimeter())) print("RectA Area: " + str(rectA.getArea())) rectB = rect.Rectangle(0, -80, 400, 160) print("RectB Perimeter: " + str(rectB.getPerimeter())) print("RectB Area: " + str(rectB.getArea())) rectC = rect.Rectangle(100, -100, 20, 300) print("RectC Perimeter: " + str(rectC.getPerimeter())) print("RectC Area: " + str(rectC.getArea()))
angle_list = np.arange(0, max_angle) sample_number = int(len(angle_list)) #Neural network parameters epoch = 50 layer_1 = width * height ######## #SAMPLES ######## #Randomly generate a list of rectangles with the same center rectangleList = [] for theta in np.random.choice(angle_list, int(sample_number / 2), replace=True): rect = Rectangle.RectangleImage(height, width, border, line_height, line_width, theta) rectangleList.append(rect) #d.writeImage() #Convert a list of rectangles to a torch tensor def makeTensor(rectangleList): height = rectangleList[0].height width = rectangleList[0].width W = torch.Tensor(len(rectangleList), 1, height, width) A = list(map(lambda rect: rect.TorchImage, rectangleList)) W = torch.cat(A, out=W) return W
FRAMES_PER_SECOND = 30 N_SHAPES = 10 # set up the window pygame.init() window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32) clock = pygame.time.Clock() shapesList = [] shapeTypesTuple = ('square', 'rectangle', 'circle', 'triangle') for i in range(0, N_SHAPES): thisType = random.choice(shapeTypesTuple) if thisType == 'square': oShape = Square(window) elif thisType == 'rectangle': oShape = Rectangle(window) elif thisType == 'circle': oShape = Circle(window) else: # must be triangle oShape = Triangle(window) shapesList.append(oShape) statusLine = pygwidgets.DisplayText(window, (4,4), \ 'Click on shapes', fontSize=28) # main loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()
def main(): cam = WebCamera(1) opti = OpticalFlow.Dense_Optical_Flow() md = MotionDetect.MotionDetect() rect_new = [] rect_old = [] ppl = 0 prev = cam.fetch() xd = list() init_time = time.time() filename = "people.txt" count = 0 while True: # print i curr = cam.fetch() rect_new = md.detect_motion(prev, curr) img = Rectangle.draw_rectangles(curr, rect_new) ts = time.time() if len(rect_new) > 0 or count == 0: flow = opti.dense_opti_flow(prev, curr) x, y = opti.get_fx_fy(flow) matches = Templating.match_rects(rect_new, rect_old) print matches mx = np.mean(x) xd.append(mx) ret = opti.draw_flow(curr, flow) else: if len(xd) != 0: x = np.mean(xd) print x xd = list() # yd = list() if x < -0.2: print "LEFT" ppl -= 1 elif x > 0.2: print "RIGHT" ppl += 1 else: print "NO MOTION" x = None # DO WORK HERE COUNT!!!! rect_old = rect_new if abs(ts - init_time) >= 600: f = open(filename, 'a') st = datetime.datetime.fromtimestamp(ts).strftime( '%Y-%m-%d,%H:%M:%S') f.write("%s|%d\n" % (st, ppl)) f.close() cv2.imwrite("../Results/Motion.jpg", img) cv2.imwrite("../Results/OpticalFlow.jpg", ret) prev = curr count = 1 if len(xd) != 0: x = np.sum(xd) print x xd = list() if x < -150: print "LEFT" ppl -= 1 elif x > 150: print "RIGHT" ppl += 1 else: print "NO MOTION" f = open(filename, 'a') st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d,%H:%M:%S') f.write("%s|%d\n" % (st, ppl)) f.close() x = None print ppl
from Rectangle import * from Triangle import * rect = Rectangle() trey = Triangle() rect.set_values( 4 , 5 ) trey.set_values( 4 , 5 ) print( 'Rectangle Area:' , rect.area() ) print( 'Triangle Area:' , trey.area() )