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

如何用ASCII符号在终端实现Python抛体运动轨迹绘制

终端ASCII绘制抛体运动轨迹解决方案

核心问题修正与实现思路

  1. 轨迹点存储优化:将计算后的整数坐标存入集合,快速判断当前位置是否属于轨迹,避免逐元素遍历列表的低效操作
  2. 终端坐标适配:终端的Y轴是从上到下递增的,需将物理计算的Y坐标反转,让抛体最高点显示在终端顶部
  3. While循环计数:通过手动维护current_y和current_x计数器,替代for循环实现区域遍历

完整代码实现

import numpy as np

# 抛体运动参数(可根据需求调整)
v0 = 20  # 初速度
theta = np.radians(45)  # 发射角度(转换为弧度)
g = 9.8  # 重力加速度

# 计算关键物理量
flight_time = 2 * v0 * np.sin(theta) / g
hmax = int(np.round((v0**2) * (np.sin(theta)**2) / (2 * g)))
flightdistance = int(np.round((v0**2) * np.sin(2*theta) / g))

# 生成轨迹点的时间序列
t = np.linspace(0, flight_time, num=100)
x = v0 * np.cos(theta) * t
y = v0 * np.sin(theta) * t - 0.5 * g * t**2

# 转换为适配终端的整数坐标集合
trajectory_points = set()
for xi, yi in zip(np.round(x).astype(int), np.round(y).astype(int)):
    if 0 <= xi <= flightdistance and 0 <= yi <= hmax:
        # 反转Y轴,让最高点在终端顶部
        trajectory_points.add((xi, hmax - yi))

# 使用while循环绘制轨迹
current_y = 0
while current_y <= hmax:
    current_x = 0
    current_line = []
    while current_x <= flightdistance:
        # 判断当前坐标是否在轨迹上
        if (current_x, current_y) in trajectory_points:
            current_line.append('X')
        else:
            current_line.append(' ')
        current_x += 1
    print(''.join(current_line))
    current_y += 1

原代码问题说明

  • 未定义listx和listy变量,直接调用np.around会触发报错
  • 错误地将整个坐标列表与单个整数比较(listy_rounded == iy),应检查单个坐标点是否属于轨迹集合
  • 空字符串填充会导致轨迹无间隔,需用空格填充非轨迹区域

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:16:07