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

如何从Pygame Zero获取的(x,y)元组中提取单值用于画线?

提取坐标值绘制水平线/垂直线

在Pygame Zero里,你可以直接通过元组索引提取(x,y)中的单个值,再结合当前的绘制模式(水平线/垂直线)来决定使用哪个值,具体实现如下:

核心思路

  1. 用一个变量记录当前绘制模式(比如draw_mode,可选'horizontal'或'vertical')
  2. 在鼠标点击事件中,根据模式提取对应坐标:
    • 画水平线时,固定y值(水平线的纵向坐标不变),取pos[1]
    • 画垂直线时,固定x值(垂直线的横向坐标不变),取pos[0]

代码示例

import pgzrun

# 初始化绘制模式,默认设为水平线
draw_mode = 'horizontal'
# 存储要绘制的线的固定坐标
fixed_coord = None

def on_mouse_down(pos):
    global fixed_coord
    if draw_mode == 'horizontal':
        # 提取水平线的固定y坐标
        fixed_coord = pos[1]
    elif draw_mode == 'vertical':
        # 提取垂直线的固定x坐标
        fixed_coord = pos[0]

def draw():
    screen.clear()
    if fixed_coord is not None:
        if draw_mode == 'horizontal':
            # 绘制贯穿屏幕的水平线
            screen.draw.line((0, fixed_coord), (screen.width, fixed_coord), 'white')
        elif draw_mode == 'vertical':
            # 绘制贯穿屏幕的垂直线
            screen.draw.line((fixed_coord, 0), (fixed_coord, screen.height), 'white')

# 按键切换模式:H切换水平线,V切换垂直线
def on_key_down(key):
    global draw_mode
    if key == keys.H:
        draw_mode = 'horizontal'
    elif key == keys.V:
        draw_mode = 'vertical'

pgzrun.go()

补充说明

  • Pygame Zero的on_mouse_down函数会自动传入点击位置pos,这是一个元组:索引0对应横向x坐标,索引1对应纵向y坐标。
  • 如果需要实现“点击起点-拖动确认终点”的画线逻辑,只需在鼠标按下时记录初始单值,鼠标释放时提取终点的对应值,再绘制两点连线即可。

内容的提问来源于stack exchange,提问作者Cheesy Pig 88

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:58:01