You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Pygame两直线交点计算结果异常问题如何解决

问题修复方案

核心错误点

  1. 原有平行判定逻辑仅在两条直线都不是水平/垂直线时才会计算交点,遗漏了大量常规直线场景,导致很多情况下交点不更新
  2. 交点计算方法推导有偏差,且依赖单独除以a2、b2的操作,极易出现计算错误或除零异常
  3. 未做非双直线场景的交点重置逻辑,会残留历史错误交点坐标

修复后完整代码

#!/usr/bin/env python
from pygame import *
from time import sleep
init()
win = display.set_mode((500,500))
lines = []
cords = []
preview = False
xi = -100
yi = -100

def drawlines(flines):
    for fcords in flines:
        draw.line(win,(0,0,0),fcords[0],fcords[1],4)

while True:
    win.fill((255,255,255))
    for ev in event.get():
        if ev.type == QUIT:
            quit()
            exit()
        elif ev.type == MOUSEBUTTONDOWN:
            if ev.button == 1:
                preview = True
                a = mouse.get_pos()
                cords.append(mouse.get_pos())
        elif ev.type == MOUSEBUTTONUP:
            if ev.button == 1:
                cords.append(mouse.get_pos())
                lines.append(cords)
                cords = []
                preview = False

    # 修复后的交点计算逻辑
    if len(lines) >= 2:
        # 取最后两条绘制的直线计算
        points_line1 = lines[-2]
        point1_line1 = points_line1[0]
        point2_line1 = points_line1[1]
        line1_vector = (point2_line1[0]-point1_line1[0], point2_line1[1]-point1_line1[1])
        a1 = line1_vector[1]
        b1 = -line1_vector[0]
        c1 = -(a1 * point1_line1[0] + b1 * point1_line1[1])

        points_line2 = lines[-1]
        point1_line2 = points_line2[0]
        point2_line2 = points_line2[1]
        line2_vector = (point2_line2[0]-point1_line2[0], point2_line2[1]-point1_line2[1])
        a2 = line2_vector[1]
        b2 = -line2_vector[0]
        c2 = -(a2 * point1_line2[0] + b2 * point1_line2[1])

        # 用行列式判断平行+计算交点,鲁棒性更高
        d = a1 * b2 - a2 * b1
        if d != 0:
            xi = (b1 * c2 - b2 * c1) / d
            yi = (a2 * c1 - a1 * c2) / d
        else:
            # 平行时重置交点到屏幕外
            xi = -100
            yi = -100
    else:
        # 不足两条直线时重置交点到屏幕外
        xi = -100
        yi = -100

    if preview:
        draw.line(win,(0,0,0),a,mouse.get_pos(),4)
    drawlines(lines)
    # 仅当交点在屏幕范围内时绘制
    if 0 <= xi <= 500 and 0 <= yi <= 500:
        draw.circle(win,(0,200,0),(int(xi),int(yi)),10)
    display.flip()

额外优化点

  • 支持绘制超过2条直线时,自动取最后两条计算交点
  • 平行/不足两条直线时自动隐藏交点,避免屏幕角落残留无效绿圈
  • 仅当交点落在屏幕范围内时才绘制,优化视觉体验

内容的提问来源于stack exchange,提问作者s0n0fj0hn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:36:03