120 lines
2.7 KiB
Python
120 lines
2.7 KiB
Python
import json
|
||
import random
|
||
|
||
from Shape import Shape
|
||
from Circle import Circle
|
||
from Rectangle import Rectangle
|
||
from Square import Square
|
||
|
||
|
||
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 = json['type'].lower()
|
||
|
||
if shape_type == 'circle':
|
||
radius = safe_read(json, 'radius', 0)
|
||
obj = Circle(radius)
|
||
|
||
elif shape_type == 'square':
|
||
side = safe_read(json, 'side', 0)
|
||
obj = Square(side)
|
||
|
||
elif shape_type == '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 = safe_read(json, 'color', 'unknown')
|
||
|
||
return obj
|
||
|
||
|
||
def generate_shape():
|
||
types = ['square', 'circle', 'rectangle']
|
||
|
||
rnd = random.randint(0, len(types) - 1)
|
||
|
||
shape_type = types[rnd]
|
||
|
||
if shape_type == 'circle':
|
||
obj = Circle(rnd)
|
||
|
||
elif shape_type == 'square':
|
||
obj = Square(rnd)
|
||
|
||
elif shape_type == 'rectangle':
|
||
obj = Rectangle(rnd, rnd)
|
||
|
||
else:
|
||
raise TypeError(f'Происходит что-то непонятное')
|
||
|
||
obj.color = 'unknown'
|
||
|
||
return obj
|
||
|
||
def generate_shape():
|
||
max_length = [0, 100]
|
||
types = ['square', 'circle', 'rectangle']
|
||
colors = ['red', 'green', 'blue', 'yellow', 'black', 'white']
|
||
|
||
type_index = random.randint(0, len(types) - 1)
|
||
shape_type = types[type_index]
|
||
|
||
if shape_type == 'circle':
|
||
obj = Circle(random.randint(1, 100))
|
||
elif shape_type == 'square':
|
||
obj = Square(random.randint(1, 100))
|
||
elif shape_type == 'rectangle':
|
||
obj = Rectangle(random.randint(1, 100), random.randint(1, 100))
|
||
else:
|
||
raise TypeError(f'Происходит что-то непонятное')
|
||
|
||
color_index = random.randint(0, len(colors) - 1)
|
||
obj.color = colors[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, 20)
|
||
|
||
shape_list.append(generate_shape())
|
||
|
||
python_to_json(shape_list, 'shapes.json')
|
||
|
||
|
||
|
||
|
||
|