首页 > 解决方案 > print_at - 使用字符串以外的变量

问题描述

有没有办法将字符串以外的变量从 asciimatics 库传递给 print_at?

手册中的描述:

print_at(text, x, y, colour=7, attr=0, bg=0, transparent=False)
使用指定的颜色和属性在指定位置打印文本。
参数

我正在测试的代码:

from asciimatics.screen import Screen

def print_test(screen):
    var1 = "string" #works
    var2 = int(2)   #error
    var3 = 3        #error
    var4 = [1,2,3]  #error
    var5 = (1,2,3)  #error
    screen.print_at(var1, 10, 10, 1, 1)
    screen.refresh()
    input()
Screen.wrapper(print_test)

完整代码:程序创建以绿色“@”表示的起点,然后进行10次移动,以黄色“@”表示。我想要实现的是用数字更改黄色“@”,以查看步骤的顺序。

from asciimatics.screen import Screen
import os
import random

os.system('mode con: cols=51')


def exit_point():
    global exitX
    global exitY

    wall = random.randint(1,4)

    if wall == 1:
        exitX = random.randint(1,49)
        exitY = 0
    elif wall == 2:
        exitX = 49
        exitY = random.randint(1,49)
    elif wall == 3:
        exitX = random.randint(1,49)
        exitY = 49
    elif wall == 4:
        exitX = 0
        exitY = random.randint(1,49)


def start_point():
    global startX
    global startY

    startX = random.randint(2,48)
    startY = random.randint(2,48)


def setup(screen):
    screen.fill_polygon([[(0, 0), (50, 0), (50, 50), (0, 50)],[(1, 1), (49, 1), (49, 49), (1, 49)]])
    exit_point()
    screen.print_at("#", exitX, exitY, 1, 1)
    start_point()
    screen.print_at("@", startX, startY, 2, 1)
    screen.refresh()
    input()



def move(screen):
    #trace list
    trace = []

    #bring back setup screen, waste of code but more intuiative
    screen.fill_polygon([[(0, 0), (50, 0), (50, 50), (0, 50)],[(1, 1), (49, 1), (49, 49), (1, 49)]])
    screen.print_at("#", exitX, exitY, 1, 1)
    screen.print_at("@", startX, startY, 2, 1)


    #Add starting point to the list
    point = [startX,startY]
    trace.append(point)

    #1st move
    moveX = startX + random.randint(-1,1)
    moveY = startY + random.randint(-1,1)
    point = [moveX,moveY]
    trace.append(point)
    screen.print_at("@", moveX, moveY , 3, 1)

    #more moves
    moves = 1
    while moves < 10:
        moveX = moveX + random.randint(-1,1)
        moveY = moveY + random.randint(-1,1)
        point = [moveX,moveY]
        if point not in trace: 
            trace.append(point)
            screen.print_at("@", moveX, moveY , 3, 1)
            moves = moves + 1

    screen.refresh()
    input()

Screen.wrapper(setup)
Screen.wrapper(move)
input()

标签: pythonpython-3.xascii

解决方案


看起来不print_at接受除字符序列之外的任何内容。但是您可以在将值传递给函数之前将其转换为字符串。

screen.print_at(str(var4), 10, 10, 1, 1)

如果您认为“好的,但是将我的所有print_at调用更改为 use会很不方便str()”,您可以创建一个Screen自动为您执行此操作的子类。

class PermissiveScreen(Screen):
    def print_at(self, text, *args, **kwargs):
        super().print_at(str(text), *args, **kwargs)

推荐阅读