Python-矩形和圓形


Exercise 15.1. 定義一個叫做Circle 類,類的屬性是圓心 (center) 和半徑 (radius) , 其中,
圓心 (center) 是一個 Point 類,而半徑 (radius) 是一個數字。


實例化一個圓心 (center) (150, 100) ,半徑 (radius) 75 Circle 對象。
1、編寫一個名稱為point_in_circle 的函數,該函數可以接受一個圓類 (Circle) 對象和點類
(Point) 對象,然后判斷該點是否在圓內。在圓內則返回True


2、編寫一個名稱為rect_in_circle 的函數,該函數接受一個圓類 (Circle) 對象和矩形
(Rectangle) 對象,如果該矩形是否完全在圓內或者在圓上則返回True


3、編寫一個名為rect_circle_overlap 函數,該函數接受一個圓類對象和一個矩形類對象,如
果矩形有任意一個角落在圓內則返回True 。或者寫一個更具有挑戰性的版本,如果該矩
形有任何部分落在圓內返回True

 

#######15.9  p175
import math
class Circle: #
"""
This is a circle Class,
incude Center and radius
"""
class Point:
"""
This is a point
"""
class Rectangle():
"""
This is a 矩形
"""
radius=Circle()
radius.x=75.0
center=Circle()
center.box=Point()
center.box.x=150.0
center.box.y=100.0

##矩形
box=Rectangle()
box.wei=100.0
box.hei=100.0
box.point=Point()

#計算點到圓心的距離
def point_in_len(x,y):
b=math.sqrt((x-center.box.x)**2+(y-center.box.y)**2)
return b
#計算點是否在圓內
def point_in_circle(x,y):
b=point_in_len(x,y)
if b <=radius.x:
print( b)
return True
else:
return False
#
#計算矩形全部在圓內
def rect_in_circle(x,y):
x1=x+box.wei
y1=y+box.hei
b1=math.sqrt((x-center.box.x)**2+(y-center.box.y)**2)
b2= math.sqrt((x1-center.box.x)**2+(y-center.box.y)**2)
b3= math.sqrt((x-center.box.x)**2+(y1-center.box.y)**2)
b4=math.sqrt(box.wei**2+box.hei**2)
if b4 <=radius.x:
if b1<=radius.x and b2<=radius.x and b3<=radius.x:
return True
else:
return False
else:
return False

def rect_circle_overlap(x,y): ###
#算如果矩形在圓形的一部分就返回Ture,
#原理:比對在矩形的范圍內所有的點,是否有到圓心的距離,小於半徑的
###原理:如果有符合的就計數+1
##並計算 計數是否大於1,如果大於1,則認為矩形有點是在圓形中
x2=int(x)
x3=x2+int(x+box.wei)
y2=int(y)
y3=y2+int(y+box.hei)
count=0
for x1 in range(x2,x3):
for y1 in range(y2,y3):
len1=math.sqrt((x1-center.box.x)**2+(y1-center.box.y)**2)
if len1 >radius.x:
count=count+0
else:
count+=1
if count >=1:
return True

point=Point()
point.x=90.0
point.y=90.0
print(point_in_circle(point.x,point.y))



###矩形
box.point.x=160.0
box.point.y=100.0
###計算矩形是否全部包含在圓形內
print(rect_in_circle(box.point.x,box.point.y))
##計算矩形是否有部分在圓形內
print(rect_circle_overlap(box.point.x,box.point.y))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM