78 lines
2.3 KiB
Python
Executable File
78 lines
2.3 KiB
Python
Executable File
import json
|
||
import random
|
||
|
||
from classes import Shape, Square, Circle, Rectangle
|
||
from enums import ShapeColor
|
||
from enums import ShapeType
|
||
|
||
|
||
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:
|
||
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)
|
||
elif shape_type == ShapeType.Square:
|
||
side = safe_read(json, 'side', 0)
|
||
obj = Square(side)
|
||
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}')
|
||
obj.color = ShapeColor.from_string(safe_read(json, 'color', 'unknown'))
|
||
return obj
|
||
|
||
|
||
def generate_shape():
|
||
max_length = 100
|
||
type_index = random.randint(0, len(list(ShapeType)) - 2)
|
||
shape_type = list(ShapeType)[type_index]
|
||
|
||
if shape_type == ShapeType.Circle:
|
||
obj = Circle(random.randint(1, max_length))
|
||
elif shape_type == ShapeType.Square:
|
||
obj = Square(random.randint(1, max_length))
|
||
elif shape_type == ShapeType.Rectangle:
|
||
obj = Rectangle(random.randint(1, 100), random.randint(1, max_length))
|
||
else:
|
||
raise TypeError(f'Происходит что-то непонятное')
|
||
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)
|
||
|
||
|
||
def filter_shapes(data, area):
|
||
return [shape for shape in data if shape.area() >= area]
|
||
|
||
|
||
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')
|
||
|