Menu
CoddyTech

복습 - 도형 계산기

Coddy GDScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 65개 중 25번째.

challenge icon

챌린지

중급

실제 도형, 계층 구조 외부의 도형과 비슷한 객체, 그리고 측정할 수 없는 객체를 처리하는 도형 계산기를 만드세요.

  • Shape는 추상 클래스이며, 추상 메서드 area() -> float, perimeter() -> float, shape_name() -> String을 가집니다. 일반 메서드 describe()는 소수점 두 자리까지 표시하는 NAME: area A, perimeter P 형식의 값을 반환합니다.
  • Circle(radius), Rectangle(width, height), Triangle(변 a, b, c)은 Shape를 상속합니다. 각 도형의 이름은 Circle, Rectangle, Triangle입니다. 원의 넓이는 PI * r * r이고 둘레는 2 * PI * r입니다. 삼각형에는 헤론의 공식을 사용하세요. s = (a + b + c) / 2일 때 넓이는 sqrt(s * (s - a) * (s - b) * (s - c))입니다.
  • CustomShape는 Shape를 상속하지 않습니다. custom_name과 size를 가집니다. area()는 size * size이고, perimeter()는 4 * size이며, describe()는 사용자 지정 이름을 사용해 Shape와 같은 형식의 값을 반환합니다.
  • ShapeCalculator에는 두 개의 정적 함수가 있습니다. process(thing)은 Shape인 경우 [Shape] 뒤에 describe()를 붙여 반환하고, 그 외에 describe() 메서드가 있는 객체인 경우 [Duck] 뒤에 describe()를 붙여 반환하며, 그렇지 않은 경우 Cannot measure this object을 반환합니다. total_area(things)는 area() 메서드가 있는 모든 객체의 area() 값을 더합니다.

제공된 코드는 객체의 개수를 읽은 다음, 한 줄에 하나씩 다음 형식으로 입력을 읽습니다. circle R, rectangle W H, triangle A B C, custom NAME SIZE 또는 unknown(일반 RefCounted 객체). 각 객체에 대해 process()의 결과와 전체 넓이를 출력합니다. circle 5, custom Hexa 3, unknown을 입력하면 다음을 출력합니다.

[Shape] Circle: area 78.54, perimeter 31.42
[Duck] Hexa: area 9.00, perimeter 12.00
Cannot measure this object
Total area: 87.54

코드는 shape.gd, circle.gd, rectangle.gd, triangle.gd, custom_shape.gd, shape_calculator.gd에 작성하세요. main.gd에는 제공된 입출력 코드가 있으며 수정할 수 없습니다.

직접 해보기

extends Node

func _ready():
	# 제공된 입력/출력 코드: 수정하지 말고 그대로 두세요
	var count := int(OS.read_string_from_stdin())
	var things := []
	for i in count:
		var p := OS.read_string_from_stdin().split(" ")
		if p[0] == "circle":
			things.append(Circle.new(float(p[1])))
		elif p[0] == "rectangle":
			things.append(Rectangle.new(float(p[1]), float(p[2])))
		elif p[0] == "triangle":
			things.append(Triangle.new(float(p[1]), float(p[2]), float(p[3])))
		elif p[0] == "custom":
			things.append(CustomShape.new(p[1], float(p[2])))
		else:
			things.append(RefCounted.new())
	for thing in things:
		print(ShapeCalculator.process(thing))
	print("Total area: %.2f" % ShapeCalculator.total_area(things))

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 GDScript 컴파일러