def calculate_canvas_size_and_stretch( bounds: Rectangle, rquested_canvas_size: Tuple[int, int] ) -> Tuple[Tuple[int, int], float]: canvas_stretch_factor_h = rquested_canvas_size[0] / bounds.width() canvas_stretch_factor_w = rquested_canvas_size[1] / bounds.height() canvas_stretch_factor = (canvas_stretch_factor_w + canvas_stretch_factor_h) / 2 canvas_size = int(bounds.height() * canvas_stretch_factor), int( bounds.width() * canvas_stretch_factor ) return canvas_size, canvas_stretch_factor
def lineGeneration(y): #generating random gap position gapPos = rn.randint(1, 400) gapSize = rn.randint(40, 120) #left side of the gap leftLine = Rectangle((0, y), rn.choice(colorChoices), gapPos, 2) #right side of the gap x = gapPos + gapSize rightLine = Rectangle((x, y), rn.choice(colorChoices), 500 - x, 2) return [leftLine, rightLine]
def testPerimeter(self): self.assertAlmostEqual(Rectangle(5,2).getPerimeter(),(5+2)*2) self.assertAlmostEqual(Rectangle(7.2,2).getPerimeter(),((7.2)+2)*2) self.assertAlmostEqual(Rectangle(0.5,0.2).getPerimeter(),((0.5)+(0.2))*2) self.assertAlmostEqual(Rectangle(0.231,0.3214).getPerimeter(),((0.231)+(0.3214))*2) self.assertAlmostEqual(Rectangle(0,2).getPerimeter(),-1) self.assertAlmostEqual(Rectangle(-5,4).getPerimeter(),-1) self.assertAlmostEqual(Rectangle(-8.23,-23.1).getPerimeter(),-1) self.assertAlmostEqual(Rectangle(5,None).getPerimeter(),-1) self.assertAlmostEqual(Rectangle('cat',9).getPerimeter(),-1)
def testArea(self): self.assertAlmostEqual(Rectangle(5,2).getArea(),5*2) self.assertAlmostEqual(Rectangle(7.2,2).getArea(),(7.2)*2) self.assertAlmostEqual(Rectangle(0.5,0.2).getArea(),(0.5)*(0.2)) self.assertAlmostEqual(Rectangle(0.231,0.3214).getArea(),(0.231)*(0.3214)) self.assertAlmostEqual(Rectangle(0,2).getArea(),-1) self.assertAlmostEqual(Rectangle(-5,4).getArea(),-1) self.assertAlmostEqual(Rectangle(-8.23,-23.1).getArea(),-1) self.assertAlmostEqual(Rectangle(None,2).getArea(),-1) self.assertAlmostEqual(Rectangle(3,'hello').getArea(),-1)
def calibrate_screen_bounds(cam) -> Optional[Rectangle]: img = cam.read() h, w, _ = img.shape cnvs = np.zeros(img.shape, np.uint8) cv2.rectangle(cnvs, (0, 0), (w, h), SQUARE_COLOR, cv2.FILLED) corners = None for _ in range(5): show_image_fullscreen(cnvs) cv2.waitKey(1000) img = cam.read() filtered = filter_cyan(img) corners = find_corners(filtered) cv2.waitKey(1000) if corners: break else: print("Failed to find screen corners!") return None # print ("Corners are at: ", corners) return Rectangle(*corners)
def createShape(type): if type.lower() == 'square': return Square() elif type.lower() == 'rectangle': return Rectangle() elif type.lower() == 'circle': return Circle() else: return None
def add_button(self, callback: Callable, icon_path: str, button_size: int): button = Button( callback, Rectangle( Point(self.next_button_x, self.next_button_y), Point( self.next_button_x + button_size, self.next_button_y + button_size ), ), icon_path, ) self.buttons.append(button) self.next_button_y += int(button_size * 1.5)
#-------------------------------------------------------------------------------------------- # OOP program that is calculate Area and Perimeter of different shapes. #-------------------------------------------------------------------------------------------- from Shapes import Square, Rectangle #-------------------------------------------------------------------------------------------- if __name__ == '__main__': square = Square(5) print("Square Area :", square.getArea()) print("Square Perimeter :", square.getPerimeter()) rectangle = Rectangle(2, 3) print("Rectangle Area :", rectangle.getArea()) print("Rectangle Perimeter :", rectangle.getPerimeter()) #--------------------------------------------------------------------------------------------
def test_Rectangle(self): rec = Rectangle(np.array([1, 1]), np.array([2, 2]), np.pi / 4) rec_bb = rec.bounding_box rec_bb_1, rec_bb_4 = rec_bb.xlower, rec_bb.yupper self.assertTrue(np.abs(rec_bb_1 - 1 + np.sqrt(2) / 2) <= 10**-6) self.assertTrue(np.abs(rec_bb_4 - 1 - np.sqrt(2)) <= 10**-6)
def mousePressEvent(self, event): self.__clickx = event.x() self.__clicky = event.y() self.__randomLength = randint(10, 100) self.__randomWidth = randint(10, 100) triangle_orientation = randint(1, 4) colors = [Qt.magenta, Qt.blue, Qt.red, Qt.yellow, Qt.cyan, Qt.green] color_choice = colors[randint(0, 5)] shape_choice = randint(1, 7) if shape_choice == 1: newshape = Rectangle(self.__clickx - (self.__randomLength / 2), self.__clicky - (self.__randomWidth / 2), self.__randomLength, self.__randomWidth, color_choice) self.__shapes.append(newshape) if shape_choice == 2: newshape = Ellipse(self.__clickx - (self.__randomLength / 2), self.__clicky - (self.__randomWidth / 2), self.__randomLength, self.__randomWidth, color_choice) self.__shapes.append(newshape) if shape_choice == 3: newshape = Square(self.__clickx - (self.__randomLength / 2), self.__clicky - (self.__randomLength / 2), self.__randomLength, color_choice) self.__shapes.append(newshape) if shape_choice == 4: newshape = Circle(self.__clickx - (self.__randomLength / 2), self.__clicky - (self.__randomLength / 2), self.__randomLength, color_choice) self.__shapes.append(newshape) if shape_choice == 5: if triangle_orientation == 1: newshape = Triangle( (self.__clickx - (self.__randomLength / 2)), self.__clicky, self.__randomLength, color_choice, triangle_orientation) self.__shapes.append(newshape) if triangle_orientation == 2: newshape = Triangle( (self.__clickx + (self.__randomLength / 2)), self.__clicky, self.__randomLength, color_choice, triangle_orientation) self.__shapes.append(newshape) if triangle_orientation == 3: newshape = Triangle(self.__clickx, self.__clicky + (self.__randomLength / 2), self.__randomLength, color_choice, triangle_orientation) self.__shapes.append(newshape) if triangle_orientation == 4: newshape = Triangle(self.__clickx, self.__clicky - (self.__randomLength / 2), self.__randomLength, color_choice, triangle_orientation) self.__shapes.append(newshape) if shape_choice == 6: newshape = HourGlass(self.__clickx, self.__clicky + self.__randomLength, self.__randomLength, color_choice) self.__shapes.append(newshape) if shape_choice == 7: newshape = Diamond(self.__clickx, self.__clicky + self.__randomLength, self.__randomLength, color_choice) self.__shapes.append(newshape) self.update()
def testName(self): self.assertEqual(Rectangle(8,12).getName(),"Rectangle")
def main(): display = 500, 750 screen = pg.display.set_mode((display)) caption = pg.display.set_caption("Rainbow Runner") screen.fill(BLACK) #---------------Instructions------------ pg.font.init() instructionbutton = Rectangle((5, 5), WHITE, 30, 60) font = pg.font.SysFont(None, 15) text = font.render("Instructions", True, BLACK) screen.blit(text, (7, 12)) #----------------------------------------- #sprite sp = Rectangle((250, 20), WHITE, 20, 20) sp.draw(screen) #test line # line = Rectangle((0,700),GREEN,2,500) # line.draw(screen) #list of lines, starting y at 100 lines = [] y = 200 #generating lines for i in range(8): #generate a line at y and add to y lines.append(lineGeneration(y)) y += 100 y = 800 leftLines = [] rightLines = [] for line in lines: for index in range(len(line)): #get the left and right line if index == 0: leftLines.append(line[index]) else: rightLines.append(line[index]) #speeds xspeed = 99 / 100 yspeed = 6 riseSpeed = -1 #detecting if the sprite is on a line onLine = False while True: pg.time.wait(10) pg.event.pump() instructionbutton.draw(screen) screen.blit(text, (7, 12)) #quit if pg.event.get(pg.QUIT): break #instructions printing button if pg.event.get(pg.MOUSEBUTTONDOWN): if instructionbutton.rectangle.collidepoint(pg.mouse.get_pos()): with open('Documentations/instructions.txt', 'r') as f: print(f.read()) keys = pg.key.get_pressed() #the sprite moves slower in air and faster when landed if keys[pg.K_LEFT]: sp.move(-(xspeed * 4), 0) if onLine else sp.move(-xspeed, 0) if keys[pg.K_RIGHT]: sp.move((xspeed * 4), 0) if onLine else sp.move(xspeed, 0) screen.fill(BLACK) for i in range(len(leftLines)): #remove = False leftLines[i].draw(screen) rightLines[i].draw(screen) # if sprite hits a line if sp.rectangle.bottom >= leftLines[i].rectangle.top and ( sp.rectangle.left <= leftLines[i].rectangle.right or sp.rectangle.right >= rightLines[i].rectangle.left): #sp.rectangle.bottom = leftLine.rectangle.top yspeed = 0 onLine = True if sp.rectangle.bottom >= leftLines[ i].rectangle.top and sp.rectangle.left >= leftLines[ i].rectangle.right and sp.rectangle.right <= rightLines[ i].rectangle.left: # print("Rightline Left side:",rightLines[i].rectangle.left) # print("Sprite right side:",sp.rectangle.right) yspeed = 2 onLine = False #remove = True leftLines[i].rectangle.bottom += riseSpeed rightLines[i].rectangle.bottom += riseSpeed # if remove: # # leftLines.remove(leftLines[i]) # # rightLines.remove(rightLines[i]) # onLine = False #if sp.rectangle.y >= 720: sp.rectangle.y = 1 #stop the sprite from going off screen if sp.rectangle.left <= 0: sp.rectangle.left = 0 if sp.rectangle.right >= 500: sp.rectangle.right = 500 #sprite naturally drops if onLine: sp.move(0, -1) else: sp.move(0, 2) #when the top line leaves the screen, create new line at the at the bottom of the screen if leftLines[0].rectangle.bottom <= 0: leftLines.pop(0) rightLines.pop(0) newLine = lineGeneration(y) leftLines.append(newLine[0]) rightLines.append(newLine[1]) sp.draw(screen) pg.display.flip()
from RTree import RTree import numpy as np import csv # construct query list and crime tree query_lst = [] with open('crime-boxes.csv', newline='') as csvfile: box_reader = list(csv.reader(csvfile, delimiter=',')) dim_name_query = box_reader[0] query_names = [] for i in range(1, len(box_reader)): query_names.append(box_reader[i][0]) new_line = box_reader[i][1:] x1, y1, x2, y2 = list(map(float, new_line)) new_rec = Rectangle(np.array([x1, y1]), np.array([x2, y2]), angle=0, id=None) query_lst.append(new_rec) crime_tree = RTree() with open('crimes.csv', newline='') as csvfile: crime_reader = list(csv.reader(csvfile, delimiter=',')) dim_name_crime = crime_reader[0] for i in range(1, len(crime_reader)): new_line = crime_reader[i] new_rec = Rectangle(np.array([0, 0]), np.array([1, 1]), angle=0, id=None) # crime_tree.insert(new_rec)
# Two triangles t1 = Triangle(0, 0, 6, 8, 10) print(t1) print(repr(t1)) print() t2 = Triangle(5, 7, 3, 4, 5) print(t2) print(repr(t2)) # In[79]: # Two rectangles r1 = Rectangle(0, 0, 10, 10) print(r1) print(repr(r1)) print() r2 = Rectangle(5, 11, 4, 6) print(r2) print(repr(r2)) # ## Repr and str # In the previous examples, together with the definition of the geometric shapes, their _printable_ version and their representations have been shown. # # In particular, \_\_str_\_ has been implemented in order to return a human-readable description of the object (e.g. 'A Rectangle centered at (0,0) with base 12 and height 10'), while \_\_repr_\_ gives a more formal output ('Rectangle(0,0,12,10)'), the same used in the code to define the object itself. # ## Some operations between points
from Shapes import Triangle, Rectangle, Oval rectangle1 = Rectangle() rectangle1.set_width(200) rectangle1.set_height(100) rectangle1.set_color('red') rectangle1.draw() new_rect = Rectangle() new_rect.set_width(70) new_rect.set_height(50) new_rect.set_color('blue') new_rect.draw()
def main(): display = 500, 750 screen = pg.display.set_mode((display)) caption = pg.display.set_caption("Rainbow Runner") pg.font.init() #----------------------------------------- #sprite sp = Rectangle((250,20),WHITE,20,20) sp.draw(screen) #list of lines, starting y at 100 lines = [] y = 300 #generating lines for i in range(8): #generate a line at y and add to y lines.append(lineGeneration(y)) y += 100 y = 800 leftLines = [] rightLines = [] for line in lines: for index in range(len(line)): #get the left and right line if index == 0: leftLines.append(line[index]) else: rightLines.append(line[index]) #speeds xspeed = 99999/100000 yspeed = 6 riseSpeed = -1 #detecting if the sprite is on a line onLine = False #score score = 0 scoreFont = pg.font.SysFont(None, 45) scoreText = scoreFont.render(str(score), True, rn.choice(colorChoices)) screen.blit(scoreText, (480, 0)) try: while True: pg.time.delay(7) pg.event.pump() #quit if pg.event.get(pg.QUIT): pg.quit() #instructions printing button if pg.event.get(pg.MOUSEBUTTONDOWN): if instructionbutton.rectangle.collidepoint(pg.mouse.get_pos()): with open('Documentations/instructions.txt', 'r') as f: print(f.read()) keys = pg.key.get_pressed() #the sprite moves slower in air and faster when landed if keys[pg.K_LEFT]: sp.move(-(xspeed*4),0) if onLine else sp.move(-xspeed,0) if keys[pg.K_RIGHT]: sp.move((xspeed*4),0) if onLine else sp.move(xspeed,0) screen.fill(BLACK) for i in range(len(leftLines)): leftLines[i].draw(screen) rightLines[i].draw(screen) # if sprite hits a line if sp.rectangle.bottom >= leftLines[i].rectangle.top and (sp.rectangle.left <= leftLines[i].rectangle.right or sp.rectangle.right >= rightLines[i].rectangle.left): #change the color of the sprite to the color of the line that it hits if sp.rectangle.right <= leftLines[i].rectangle.right: sp.color = leftLines[i].color elif sp.rectangle.left >= rightLines[i].rectangle.left: sp.color = rightLines[i].color #reset yspeed and onLine yspeed = 0 onLine = True #if the sprite goes through the gap if sp.rectangle.bottom >= leftLines[i].rectangle.top and sp.rectangle.left >= leftLines[i].rectangle.right and sp.rectangle.right <= rightLines[i].rectangle.left: #reset yspeed and onLine yspeed = 6 onLine = False leftLines[i].rectangle.bottom += riseSpeed rightLines[i].rectangle.bottom += riseSpeed #stop the sprite from going off screen if sp.rectangle.left <= 0: sp.rectangle.left = 0 if sp.rectangle.right >= 500: sp.rectangle.right = 500 #sprite naturally drops if onLine: sp.move(0,riseSpeed) else: sp.move(0,6) #create new line when the first line reaches the top if leftLines[0].rectangle.bottom <= 0: leftLines.pop(0) rightLines.pop(0) newLine = lineGeneration(y) leftLines.append(newLine[0]) rightLines.append(newLine[1]) score += 1 # when sprite hits top of screen, game over if sp.rectangle.top <= 0: with open('Documentations/scores.txt', 'a') as f: f.write(str(score) + "\n") break #displaying score scoreText = scoreFont.render(str(score), True, rn.choice(colorChoices)) if score < 10: screen.blit(scoreText, (480, 0)) elif score >= 10 and score < 100: screen.blit(scoreText, (463, 0)) else: screen.blit(scoreText, (443, 0)) #change the difficulty if score > 50 : riseSpeed = -2 elif score > 100 : riseSpeed = -3 sp.draw(screen) pg.display.flip() except: print("Exited Game")