有没有更简洁的方式来编写此代码?

时间:2020-11-02 15:33:49

标签: python-3.x

我正在创建一个通过逐行搜索显示地图的项目。这是外观的简短版本:

xpos=1
ypos=1
#xpos and ypos are the player's coordinates
running=True
while running:
    if xpos==1:
        if ypos==1:
            print('x . . ')
        if ypos==2:
            print('. x .')
        if ypos==3:
            print('. . x')
    else:
        print('. . .')

...等等。我正在创建的项目需要一张50 x 50的地图,因此这种方法似乎浪费了计算能力,而且要花很多时间才能打字。有没有更好的方法可以做到这一点?抱歉,您的代码令人讨厌! 编辑:有没有一种方法可以使用for或while循环来完成此操作?

1 个答案:

答案 0 :(得分:0)

您可以使用库 graphics.py 并在地图上显示书签的移动,例如,此代码沿直线移动一个圆。此举可以逐行包括页面。

from graphics import GraphWin,  Circle, Point
import time

def main():
    win = GraphWin('Back and Forth', 300, 300)
    win.setCoords(0, 0, 299, 299)

    cir1 = Circle(Point(40,100),5)
    cir1.setFill("yellow")
    cir1.draw(win)
    for i in range(46):
        cir1.move(5, 0)
        time.sleep(.05)

    for i in range(46):
        cir1.move(-5, 0)
        time.sleep(.05)
    win.getMouse()
    win.close()


if __name__ == '__main__':
    main()

https://pypi.org/project/graphics.py/

http://anh.cs.luc.edu/handsonPythonTutorial/graphics.html

相关问题