Beispiel #1
0
    def __init__(self, **kwargs):
        '''Create a slider control
		
		Keyword arguments:
		name -- unique widget identifier
		min -- minimum value
		max -- maximum value
		value -- initial value
		action -- callback to be invoked when the slider is moved
		continuous -- if true, invoke action on every movement, else
			invoke action only when the user releases the mouse button
		'''
        Widget.__init__(self, **kwargs)

        self._min = kwargs.get('min', 0.0)
        self._max = kwargs.get('max', 1.0)

        self._value = kwargs.get('value', 0.5)

        self.shapes['track'] = Rectangle()
        self.shapes['knob'] = Rectangle()

        self.action = kwargs.get('action', None)
        self._continuous = kwargs.get('continuous', True)

        self._focused = False
Beispiel #2
0
    def __init__(self):
        Entity.__init__(self,
                        position=glm.vec2(0, 0),
                        color=glm.vec3(1.0, 0.0, 1.0),
                        rectangles=[Rectangle(glm.vec2(0, 0), 10, 10)])

        self.last_pos = glm.vec2()
Beispiel #3
0
 def __init__(self, ball_instance, world, size=50):
     position = glm.vec2(0.0, 0.0)
     Entity.__init__(self,
                     position=position * 1,
                     color=glm.vec3(0.7, 0.0, 0.0),
                     rectangles=[Rectangle(position * 1, size, size)])
     self.ball_instance = ball_instance
Beispiel #4
0
 def __init__(self,
              screen_size: tuple = (720, 480),
              path: str = os.path.join("..", "saves", "untitled"),
              caption: str = "Create a Pokemon Game"):
     self.size = screen_size
     self.path = path
     self.caption = caption
     pygame.init()
     self.shape_pos = None
     self.buttons = []
     self.screen = pygame.display.set_mode(self.size)
     pygame.display.set_caption(self.caption)
     super().__init__(screen_size)
     button_names = ["DRAW", "EDIT", "ATTR"]
     increase = 480 / screen_size[1]
     self.font_size = int(30 * increase)
     self.font = pygame.font.SysFont("Arial", self.font_size)
     space = 5 * increase
     size = (15 * increase, 40 * increase)
     for i, y in enumerate(
             range(int(space), int(space * (len(button_names) + 1)),
                   int(space))):
         button = Rectangle(size, (space, y),
                            Text(button_names[i - 1], self.font),
                            Color(0, 0, 0))
         self.buttons.append(button)
     self.screen.blit(self, self.position)
     err_code = self.main()
     self.stop(err_code)
Beispiel #5
0
    def __init__(self, title, **kwargs):
        '''Create a folding box
		
		Keyword arguments:
		name -- unique widget identifier
		content -- child container
		collapsed -- if true, container folded initially
		'''
        SingleContainer.__init__(self, **kwargs)

        self.shapes['topbar'] = Rectangle()
        self.elements['title'] = BasicLabel(title,
                                            font_size=8,
                                            color=(0, 0, 0, 255),
                                            anchor_x='left',
                                            anchor_y='center')

        self.content = kwargs.get('content', None)

        self._last_h = 15
        self._collapsed = False

        self._top_h = 0

        self.collapsed = kwargs.get('collapsed', False)
Beispiel #6
0
    def __init__(self, title, **kwargs):
        '''Create a dialogue
		
		Keyword arguments:
		name -- unique widget identifier
		content -- child container
		'''
        SingleContainer.__init__(self, **kwargs)

        self.resizeable = kwargs.get('resizeable', False)

        self.shapes['background'] = Rectangle()
        self.shapes['title_bar'] = Rectangle()
        self.elements['title'] = BasicLabel(title, anchor_x='center')

        self.topbar = Rect(0, 0, 0, 15)

        self._in_drag = False

        self.content = kwargs.get('content', None)
Beispiel #7
0
    def __init__(self, width, height):
        center_x = width / 2.0
        center_y = height / 2.0
        thicccckness = 100.0  # I'm sorry, I really am!
        halve_thicck = thicccckness / 2.0 - 1  # This -1 makes one pixel of the borders visible
        rects = [
            Rectangle(glm.vec2(center_x, 0 - halve_thicck),
                      width + thicccckness, thicccckness),
            Rectangle(glm.vec2(center_x, height + halve_thicck),
                      width + thicccckness, thicccckness),
            Rectangle(glm.vec2(0 - halve_thicck, center_y), thicccckness,
                      height + thicccckness),
            Rectangle(glm.vec2(width + halve_thicck, center_y), thicccckness,
                      height + thicccckness)
        ]

        Entity.__init__(self,
                        position=glm.vec2(0, 0),
                        color=glm.vec3(1.0, 1.0, 1.0),
                        rectangles=rects)
Beispiel #8
0
def main():
    square = Square(5)
    rectangle = Rectangle(12,5)
    ellipse = Ellipse(4, 10)
    oval = Oval(-4)

    shapeList = [square, rectangle, ellipse, oval]

    for s in shapeList:
        if isinstance(s, Shape):
            print("This " + s.getShape() + " has an area of " + str(s.calculateArea()))
Beispiel #9
0
 def create_vis_graph(self):
     '''Creates all the visual_nodes in a graph'''
     counter = 0
     for x in range(8, self.graph.dimensions.x_pos * 60, 60):
         for y in range(8, self.graph.dimensions.y_pos * 60, 60):
             rect = Rectangle(Vector2(x, y), self.surface, (255, 255, 255),
                              45, 45)
             new_node = Visual_Node(self.graph.nodes[counter],
                                    Vector2(x + (45 / 2), y + (45 / 2)),
                                    rect)
             self.vis_nodes.append(new_node)
             counter += 1
Beispiel #10
0
 def get_colliding_entities(self):
     box = Rectangle(
         Vector2(self.position.x - (self.size.x / 2),
                 self.position.y - (self.size.y / 2)),
         Vector2(self.position.x + (self.size.x / 2),
                 self.position.y + (self.size.y / 2)))
     entities = list()
     for entity in self.world.entities:
         if entity is not self and not isinstance(
                 entity, ArrowEntity) and entity.position in box:
             entities.append(entity)
     return entities
Beispiel #11
0
class RectangleClassTest(unittest.TestCase):
    def setUp(self):
        self.shape = Rectangle(12, 23.4)

    def tearDown(self):
        del self.shape

    def test_constructor(self):
        with self.assertRaises(InvalidSideError):
            r = Rectangle(5, -5)
        with self.assertRaises(InvalidSideError):
            r = Rectangle(-5, 5)

    def test_shape_area(self):
        self.assertAlmostEqual(280.8, self.shape.area())
def main():
    rectangle = Rectangle(center_x=0.0, center_y=0.0, width=10.0, height=5.0)
    rectangle.draw()
    circle = Circle(x=0.0, y=0.0, radius=7.0)
    circle.draw()

    color = input("Enter the color to fill: 'red' or 'blue': ")
    if color.lower() == 'red':
        color_impl = RedImplementor.get_instance()
    elif color.lower() == 'blue':
        color_impl = BlueImplementor.get_instance()
    else:
        return
    rectangle.set_color_implementor(color_impl)
    rectangle.fill_color()
    circle.set_color_implementor(color_impl)
    circle.fill_color()
Beispiel #13
0
    def __init__(self,
                 position=glm.vec2(400, 300),
                 force_per_px=2.0,
                 color=glm.vec3(1.0, 1.0, 1.0),
                 world=None):
        size = 10
        Entity.__init__(self,
                        position=position,
                        color=color,
                        rectangles=[Rectangle(position, size, size)])

        self.is_pressed = False
        self.possible_velocity = glm.vec2()
        self.force_per_px = force_per_px
        self.velocity = glm.vec2()
        self.distance = 0
        self.prediction = []
Beispiel #14
0
 def main(self):
     while True:
         for event in [pygame.event.wait()] + pygame.event.get():
             if event.type == pygame.QUIT:
                 return 0
             elif event.type == pygame.MOUSEBUTTONDOWN:
                 print("DOWN")
                 self.shape_pos = event.pos
             elif event.type == pygame.MOUSEBUTTONUP:
                 print("UP")
                 x, y = event.pos
                 if self.shape_pos:
                     shape = Rectangle((abs(x - self.shape_pos[0]),
                                        abs(y - self.shape_pos[1])),
                                       self.shape_pos)
                     self.shapes.append(shape)
                     self.shape_pos = None
         self.update()
Beispiel #15
0
	def __init__(self, text, **kwargs):
		'''Create a checkbox control
		
		Keyword arguments:
		name -- unique widget identifier
		value -- initial value
		action -- callback to be invoked when the value changes
		'''
		label = BasicLabel(text, font_size=8, color=(0,0,0,255), x=15, y=0, anchor_x='left', anchor_y='bottom')
		
		Widget.__init__(self, **kwargs)
		self.elements['label'] = label
		self.shapes['box'] = Rectangle()
		
		self._value = kwargs.get('value', False)
		self.action = kwargs.get('action', None)
		
		self._down = False
Beispiel #16
0
    def __init__(self, text, **kwargs):
        '''Create a button control
		
		Keyword arguments:
		action -- callback to be invoked when the button is clicked
		'''
        Widget.__init__(self, **kwargs)

        self.elements['label'] = BasicLabel(text,
                                            font_size=8,
                                            color=(0, 0, 0, 255),
                                            anchor_x='left',
                                            anchor_y='bottom')
        self.shapes['frame'] = Rectangle()
        self.active_region = Rect(0, 0, 0, 0)

        self.action = kwargs.get('action', None)
        self._down = False
Beispiel #17
0
    def __init__(self, **kwargs):
        '''Create a text input control
		
		Keyword arguments:
		name -- unique widget identifier
		text -- intitial value
		action -- callback to be invoked when text is entered
		'''
        Widget.__init__(self, **kwargs)

        self.label = EditableLabel(kwargs.get('text', ''))

        font = self.label.document.get_font()
        height = font.ascent - font.descent

        self.shapes['frame'] = Rectangle()
        self.elements['label'] = self.label

        self.action = kwargs.get('action', None)
        self._focused = False
        self.label.caret.visible = False
Beispiel #18
0
    def load_file(self, image_dir):
        self.reset()
        self.pixmap = QPixmap(image_dir)
        self.cv2_image = cv2.imread(image_dir)
        self.label_dir = os.path.splitext(image_dir)[0] + '.json'
        if QFile.exists(self.label_dir):
            with open(self.label_dir) as json_file:
                data = json.load(json_file)
                self.objects = []
                for obj in data['objects']:
                    points = []
                    for point in obj['points']:
                        points.append(QPointF(point['x'], point['y']))
                    if (obj['type'] == 'rectangle'):
                        self.objects.append(Rectangle(points, obj['label']))
                    elif (obj['type'] == 'polygon'):
                        self.objects.append(Polygon(points, obj['label']))
                self.cur_object = len(self.objects) - 1
                self.parent.load_object_list(self.objects)
                self.parent.object_list_widget.setCurrentRow(self.cur_object)

        self.repaint()
Beispiel #19
0
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            pos = self.transform_pos(event.localPos())
            if self.in_pixmap(pos):
                self.points.append(pos)
                self.repaint()

                if self.mode == self.RECTANGLE and len(self.points) == 2:
                    left_x = int(min(self.points[0].x(), self.points[1].x()))
                    right_x = int(max(self.points[0].x(), self.points[1].x()))
                    left_y = int(min(self.points[0].y(), self.points[1].y()))
                    right_y = int(max(self.points[0].y(), self.points[1].y()))

                    text = self.labelDialog.pop_up()
                    self.add_obj(Rectangle(self.points, text))
                    self.points = []

                if self.mode == self.AUTO_POLYGON and len(self.points) == 2:
                    left_x = int(min(self.points[0].x(), self.points[1].x()))
                    right_x = int(max(self.points[0].x(), self.points[1].x()))
                    left_y = int(min(self.points[0].y(), self.points[1].y()))
                    right_y = int(max(self.points[0].y(), self.points[1].y()))

                    tmp = rectilinear_polygon.main(
                        self.cv2_image[left_y:right_y, left_x:right_x])
                    points = [QPointF(left_x + x, left_y + y) for x, y in tmp]
                    if (len(points) > 0):
                        text = self.labelDialog.pop_up()
                        self.add_obj(Polygon(points, text))
                    self.points = []

                if self.mode == self.POLYGON and len(self.points) >= 4 \
                        and self.close_enough(self.points[0], self.points[-1]):
                    text = self.labelDialog.pop_up()
                    self.add_obj(Polygon(self.points[:-1], text))
                    self.points = []
Beispiel #20
0
def test_name(data):
    r = Rectangle(data[0], data[1])
    assert r.name == "Rectangle"
Beispiel #21
0
# conveyer belt using surface velocity
from shape import pymunk, space, App, Box, Rectangle

b0 = space.static_body
shape = pymunk.Segment(b0, (20, 20), (500, 150), 10)
shape.friction = 1
shape.surface_velocity = (100, 100)
space.add(shape)

Rectangle((100, 200))
App().run()
Beispiel #22
0
from shape import Rectangle, Triangle
import requests

if __name__ == "__main__":
    alas = int(input("masukan alas: "))
    tinggi = int(input("masukan tinggi: "))
    rect = Rectangle(alas, tinggi)
    trian = Triangle(alas, tinggi)
    print(rect.luas)
    print(trian.luas)
    req = requests.get('http://kjasdfkhsajkdhfkjsdhvkndsjnvio.com/')
    print(req.status_code)
Beispiel #23
0
def test_area(data):
    r = Rectangle(data[0], data[1])
    assert r.area == data[0] * data[1]
Beispiel #24
0
"""
실행부
A. s 변수는 도형이다.
B. 반지름이 5인 원을 정의하여 c 변수에 저장한다.
C. 가로, 세로가 5, 10인 직사각형을 정의하여 r에 저장한다.
D. 세변이 3(밑변), 4, 5이고, 높이가 4인 삼각형을 정의하여 t에 저장한다.
E. c의 면적과 둘레를 출력한다.
F. r의 면적과 둘레를 출력한다.
G. t의 면적과 둘레를 출력한다.
H. t의 변들을 리스트로 받아 출력한다.
"""
# 필요한 모듈 수입하기
from shape import Shape, Circle, Triangle, Rectangle

s = Shape() # shape.의 의미는 "shape.ps에서 정의된" 을 의미
                  # Shape가 shape.ps에 정의된 클래스임을 의미
c = Circle(5)
r = Rectangle(5, 10)
t = Triangle(3, 4, 4, 5)
print(c.area())
print(c.perimeter())
print(r.area())
print(r.perimeter())
print(t.area())
print(t.perimeter())
print(r.getSides())

l = [s, c, r, t]
for i in l:
    print(i)
Beispiel #25
0
 def test_constructor(self):
     with self.assertRaises(InvalidSideError):
         r = Rectangle(5, -5)
     with self.assertRaises(InvalidSideError):
         r = Rectangle(-5, 5)
Beispiel #26
0
 def setUp(self):
     self.shape = Rectangle(12, 23.4)
Beispiel #27
0
def test_angles(data):
    r = Rectangle(data[0], data[1])
    assert r.angles == 4
Beispiel #28
0
import pytest
from shape import Square, Rectangle, Triangle, Circle


class BadShape:
    def __init__(self, a):
        self.a = a

    @property
    def area(self):
        return self.a


figure_set_one = [
    Square(58.095),
    Rectangle(0.000887799, 44),
    Triangle(22.00001, 22.001, 22.1),
    Circle(900000234)
]
figure_set_two = [
    Square(1),
    Rectangle(999993242, 555),
    Triangle(78.956, 112.44, 96.928),
    Circle(5667.00938),
    pytest.param(BadShape(4444), marks=pytest.mark.xfail)
]


@pytest.mark.parametrize("f1", figure_set_one)
@pytest.mark.parametrize("f2", figure_set_two)
def test_add(f1, f2):
Beispiel #29
0
# 파이썬 파일에서 필요한 클래스만 수입
import shape
# shape.py에 정의된 클래스, 함수 등을 수입해서 사용하겠다는 의미. .py 확장자는 붙이지 않는다.
from shape import Shape, Circle, Rectangle, Triangle

s = Shape() # s에 Shape()를 저장
c = Circle(5) # c에 반지름이 5인 Circle 저장
r = Rectangle(5, 10) # r에 밑변이 5이고 높이가 10인 Rectangle 저장
t = Triangle(3, 4, 5, 4) # t에 밑변이 3이고 두 변이 각각 4, 5, 높이가 4인 Triangle 저장

# c, r, t의 면적과 둘레 출력
print("c면적:"+str(c.area())+" c둘레"+str(c.perimeter()))
print("r면적:"+str(r.area())+" r둘레"+str(r.perimeter()))
print("t면적:"+str(t.area())+" t둘레"+str(t.perimeter()))

# t의 변들을 출력
st=""
for i in t.getSides():
    st = st + str(i) + " "
print(st)

# l 리스트를 생성해 s, c, r을 추가
l =[]
l.append(s)
l.append(c)
l.append(r)

# for문을 돌며 넓이와 둘레를 출력
for i in l:
    print(i)
    print("넓이:"+str(i.area()))
Beispiel #30
0
def test_perimeter(data):
    r = Rectangle(data[0], data[1])
    assert r.perimeter == data[0] * 2 + data[1] * 2