《python语言程序设计》第4章 第23题-----turtle和random 偷懒画矩形和设置点 如何判断点是否在矩形内。

在这里插入图片描述

利用turtle和random两种功能,省去了我每次都要输入数值的麻烦。

代码如下:



import turtle as tu
import random as ra

tu.speed(4)
# 矩形中心点随机出现
rx = ra.randint(0, 20)
ry = ra.randint(0, 20)

# 矩形长宽随机出现
rw = ra.randint(50, 200)
rh = ra.randint(50, 200)
r_x_w = rw / 2 + rx
r_y_h = rh / 2 + ry
r_y_h1 = r_y_h - rh
r_x_w1 = r_x_w - rw

# 矩形体的中心点
tu.penup()
tu.goto(rx, ry)
tu.dot(8, "red")
tu.write(f"矩形中心 x {rx}, y {ry}")

# 矩形体右上角的点
tu.goto(r_x_w, r_y_h)
tu.dot(8, "red")
tu.write(f"第一点 x {r_x_w},y {r_y_h}")
tu.pendown()

# 矩形体右下角的点
tu.goto(r_x_w, r_y_h1)
tu.dot(8, "red")
tu.penup()
tu.goto(r_x_w, r_y_h1 - 20)
tu.write(f"第二点 x {r_x_w}, y {r_y_h1}")
tu.penup()
tu.goto(r_x_w, r_y_h1)
tu.pendown()
# 矩形体左下角的点
tu.goto(r_x_w1, r_y_h1)
tu.dot(8, "red")
tu.penup()
tu.goto(r_x_w1, r_y_h1 - 20)
tu.write(f"第三点 x {r_x_w1}, y {r_y_h1}")
tu.penup()
tu.goto(r_x_w1, r_y_h1)
tu.pendown()

# 矩形体左上角的点
tu.goto(r_x_w1, r_y_h)
tu.dot(8, "red")
tu.write(f"第四点 x {r_x_w1}, y {r_y_h}")

# 回到矩形右上角的点,完成矩形绘制
tu.goto(r_x_w, r_y_h)

# 计算机随机点x,y
px = ra.randint(20, 200)
py = ra.randint(20, 80)
# print(f"X-point x {px}, y{py}")
tu.penup()
tu.goto(px, py)
tu.dot(8, "blue")
tu.goto(px, py - 20)
tu.write(f"X-point x {px}, y{py}")
# p_to_p = pow(pow(px - rx, 2) + pow(py - ry, 2), 0.5)

# 判断计算机随机点是否在矩形内
j_rw = rw / 2
j_rh = rh / 2
j_x = rx - px
j_y = ry - py

if j_rw >= abs(j_x) and j_rh >= abs(j_y):
    print(f"X-point x {px} and y {py} is in the rectangle")
    print(f"rectangle width {rw} and long {rh}")
    print(f"rectangle half width {rw / 2} and half long {rh / 2}")
    print(f"rectangle sub  width {j_x} and  long {j_y}")


else:
    print(f"X-point x {px} and y {py} is not in the rectangle")
    print(f"rectangle width {rw} and long {rh}")
    print(f"rectangle half width {rw / 2} and half long {rh / 2}")
    print(f"rectangle sub  width {j_x} and  long {j_y}")

tu.hideturtle()
tu.done()


本题判断点是否在矩形内。用的是矩形的长宽与随机点的x,y长度进行对比。特殊说明一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

电饭叔

谢谢各位兄弟们的关注,谢谢破费

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值