hnc-eduard/HNS/Excercises/13082023 ДЗ по фигурам JSON/main.py

78 lines
2.3 KiB
Python
Raw Normal View History

2023-08-18 19:27:51 +02:00
import json
import random
from classes import Shape, Square, Circle, Rectangle
2023-10-02 22:40:21 +02:00
from enums import ShapeColor
from enums import ShapeType
2023-08-18 19:27:51 +02:00
def safe_read(obj, property, default_value):
if property in obj:
return obj[property]
return default_value
def create_shape(json):
if 'type' in json:
2023-10-02 22:40:21 +02:00
shape_type_raw = json['type']
shape_type = ShapeType.from_string(shape_type_raw)
if shape_type == ShapeType.Circle:
radius = safe_read(json, 'radius', 0)
obj = Circle(radius)
2023-10-02 22:40:21 +02:00
elif shape_type == ShapeType.Square:
side = safe_read(json, 'side', 0)
obj = Square(side)
2023-10-02 22:40:21 +02:00
elif shape_type == ShapeType.Rectangle:
width = safe_read(json, 'width', 0)
height = safe_read(json, 'height', 0)
obj = Rectangle(width, height)
else:
raise TypeError(f'вот тебе >>>(оIo), а не фигура {shape_type}')
2023-10-02 22:40:21 +02:00
obj.color = ShapeColor.from_string(safe_read(json, 'color', 'unknown'))
return obj
def generate_shape():
max_length = 100
2023-10-16 21:06:27 +02:00
type_index = random.randint(0, len(list(ShapeType)) - 2)
shape_type = list(ShapeType)[type_index]
2023-10-02 22:40:21 +02:00
if shape_type == ShapeType.Circle:
obj = Circle(random.randint(1, max_length))
2023-10-02 22:40:21 +02:00
elif shape_type == ShapeType.Square:
obj = Square(random.randint(1, max_length))
2023-10-02 22:40:21 +02:00
elif shape_type == ShapeType.Rectangle:
obj = Rectangle(random.randint(1, 100), random.randint(1, max_length))
else:
raise TypeError(f'Происходит что-то непонятное')
2023-10-16 21:06:27 +02:00
color_index = random.randint(0, len(list(ShapeColor)) - 1)
obj.color = list(ShapeColor)[color_index]
return obj
def json_to_python(filename):
data_list = []
with open(filename) as lines:
data = json.load(lines)
for i in data["shapes"]:
sh1 = create_shape(i)
data_list.append(sh1)
return data_list
def python_to_json(data, filename):
with open(filename, 'w') as f:
json.dump({'shapes': data}, f, default=Shape.convert_to_json)
2023-08-18 19:27:51 +02:00
def filter_shapes(data, area):
return [shape for shape in data if shape.area() >= area]
2023-10-16 21:06:27 +02:00
shape_list = json_to_python('shapes.json')
shape_list = filter_shapes(shape_list, 100)
shape_list.append(generate_shape())
python_to_json(shape_list, 'shape change.json')