Python 未按下键时诅咒 addstr() 错误

Python Curses addstr() error when keys are not pressed

我正在使用 curses 库在 python 中为终端重新创建 this 游戏。每当未按下某个键时,stdscr.addstr() returns 出错。

这似乎是因为在那些帧中光标不在屏幕上(在右下角),但我完全不知道它为什么会移动。我正在打印的 canvas 始终是相同的大小(它完全由空格组成,这些空格在呈现 Apple 或 Basket 对象时被替换)。我尝试减小 canvas 大小,但光标仍然指向那个角落。我也试过设置curses.leaveok(True),光标好像跟着篮筐,但是我的记录证明它还在往那个角走。

使用curses的文件:

import random
import time
import curses

from apple_season.basket import Basket
from apple_season.apple import Apple
from apple_season.coords import Canvas

def main(stdscr):

    curses.curs_set(1)  # so i can see where the cursor is
    dims = [curses.COLS - 1, curses.LINES - 1]  # pylint: disable=no-member

    stdscr.nodelay(True)
    stdscr.leaveok(True)
    key=""
    stdscr.clear()

    canvas = Canvas(*dims)

    basket = Basket(canvas)

    apples = []
    i = 0

    def finished_apples():
      if len(apples) <= 100:
         return False
      else:
         for apple in apples:
            if not apple.has_fallen:
               return False
         return True

    while not finished_apples():

        if len(apples) <= 100:  # don't make more if there are already 100
            # decide whether or not to create new apple (1/100 chance per frame)
            num = random.randint(0, 100)
            if num == 25:
                apples.append(Apple(canvas))

        try:
            key = stdscr.getkey()
            stdscr.clear()

            # pick up keyboard inputs
            # quit option
            if str(key) == "q":
                break

            # right arrow
            elif str(key) == "KEY_RIGHT":
                basket.move('right')

            # left arrow
            elif str(key) == "KEY_LEFT":
                basket.move('left')

        except Exception:
            pass

        # render objects - alters canvas to display them
        for apple in apples:
            if apple.has_fallen:
                apple.render()
            else:
                if '.0' not in str(i / 2):  # check if i is even (drop every other frame)
                    apple.fall()
                    apple.render()

        basket.render()

        try:
            stdscr.addstr(canvas.display)

        except Exception:
            pass

        stdscr.refresh()
        i += 1
        time.sleep(0.01)

if __name__ == "__main__":
    curses.wrapper(main)

(上面的代码运行良好,但当 stdscr.addstr(canvas.display) 不起作用时,它不会执行任何操作,即只要没有按下任何键)

有趣的是,当只有篮子或苹果时,不会发生这种情况。

查看所有代码:https://github.com/lol-cubes/Terminal-Apple-Season/tree/soErrorCode

我将 stdscr.clear() 放在 try 和 except 块中,这使得该代码仅在按下某个键时执行,因此由于我试图显示多个帧而使终端溢出立刻。