python - Curses 使用 Python 编程

标签 python python-3.x curses

所以我开始在 Python 中使用 Curses。 我已经有了这个源代码,慢慢地我会对其进行一些更新:

    #!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Testing out the curses lib.
"""

import curses


def main(scr):
    """
    Draw a border around the screen, move around using the cursor and leave a mark
    of the latest pressed character on the keyboard.

    Perhaps you could make a nice painting using asciart?

    Quit using 'q'.
    """

    # Clear the screen of any output
    scr.clear()

    # Get screen dimensions
    y1, x1 = scr.getmaxyx()
    y1 -= 1
    x1 -= 1

    y0, x0 = 0, 0

    # Get center position
    yc, xc = (y1-y0)//2, (x1-x0)//2

    # Draw a border
    scr.border()

    # Move cursor to center
    scr.move(yc, xc)

    # Refresh to draw out
    scr.refresh()

    # Main loop
    x = xc
    y = yc
    ch = 'o'

    while True:
        key = scr.getkey()
        if key == 'q':
            break
        elif key == 'KEY_UP':
            y -= 1
        elif key == 'KEY_DOWN':
            y += 1
        elif key == 'KEY_LEFT':
            x -= 1
        elif key == 'KEY_RIGHT':
            x += 1
        else:
            ch = key

        # Draw out the char at cursor position
        scr.addstr(ch)

        # Move cursor to new position
        scr.move(y, x)

        # Redraw all items on the screen
        scr.refresh()



if __name__ == "__main__":
    print(__doc__)
    print(main.__doc__)
    input("Press enter to begin playing...")
    curses.wrapper(main)

我现在想做的事情是确保当我无法触及屏幕边框时。但我不确定 this 中的什么函数可以用于此目的。 我读过python docs但找不到任何我认为有用的东西。

最佳答案

您知道有效范围。从 0y1(含)。 (分别为 0 到 x1)。因此只需添加测试以确保坐标保持在范围内:

    elif key == 'KEY_UP':
      if y > 0:
        y -= 1
    elif key == 'KEY_DOWN':
      if y < y1:
        y += 1

x类似。

关于python - Curses 使用 Python 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39507305/

相关文章:

python - 向多人发送带有附件的电子邮件

python - 如何修复错误 : Could not find a version that satisfies the requirement for uncompyle6-3. 7.4-py3.8?

Python:使用异常参数时出现语法错误

无法使用 ncurses 获取 KEY_UP

python - 如何减少 python 中的多处理时间

Python嵌套for循环向下计数

django - 在 django 项目中使用 xhtml2pdf 从 html 生成 pdf

sorting - Pandas 数据透视表嵌套排序第 2 部分

python - 刷新时在 python getstr() 中诅咒

c - getyx 返回 -1 -1