如何使用Zelle的'graphics.py'库创建循环来替换硬编码窗口坐标?

时间:2013-03-25 03:05:13

标签: python loops coordinates

问题:我浪费了大量时间,通过手工编码我的坐标来创建错误,臃肿的代码。我需要帮助学习如何用这个冗长的代码替换将给出相同结果的循环结构。目前,x和y坐标分别存储在名为xCoords和yCoords的单独数组中。如何简化这个并编写一个更优雅的程序版本?

[注意:这是我的第一个 StackOverflow帖子。请告诉我样式,礼仪或发布错误,我会解决它们。这个论坛对我来说是不可或缺的,我感谢大家的帮助。]

相关详情:

  • 我正在创建一个名为“Dot Matrix”的双人GUI游戏。用户使用鼠标点击与窗口交互。可以在at this link找到此游戏的在线版本。绘制坐标点很重要,因为它定位了玩家并且是整个游戏板。此代码段不包含实际的游戏逻辑,因为我尚未编写它。
  • 我正在使用John Zelle的 Python Programming 一书中的graphics library

源代码:

    # dotmatrix.py
    # Dot Matrix Game
    # Michael Morelli
    # mmorelli at live dot com
    # Created: 03-24-13 with Python 2.7.3 and PyScripter

    from graphics import *

    win = GraphWin("Dot Matrix", 500, 500)
    win.setCoords(0.0, 0.0, 10.0, 10.0)
    win.setBackground("white")

    xCoords = [1,1,1,1,1,1,1,1,1,
               2,2,2,2,2,2,2,2,2,
               3,3,3,3,3,3,3,3,3,
               4,4,4,4,4,4,4,4,4,
               5,5,5,5,5,5,5,5,5,
               6,6,6,6,6,6,6,6,6,
               7,7,7,7,7,7,7,7,7,
               8,8,8,8,8,8,8,8,8,
               9,9,9,9,9,9,9,9,9]

    yCoords = [1,2,3,4,5,6,7,8,9,
               1,2,3,4,5,6,7,8,9,
               1,2,3,4,5,6,7,8,9,
               1,2,3,4,5,6,7,8,9,
               1,2,3,4,5,6,7,8,9,
               1,2,3,4,5,6,7,8,9,
               1,2,3,4,5,6,7,8,9,
               1,2,3,4,5,6,7,8,9,
               1,2,3,4,5,6,7,8,9]

    for i in range(81):
        Text(Point(xCoords[i], yCoords[i]), "*").draw(win)
        i+=1 # This for loop iterates through each of the coordinate arrays
             # and plots an * asterisk at each coordinate locus. There is a plot()
             # method included with the graphics library, but it plots single-pixel
             # points and are hardly visible. I do not think this will affect the game.

    input("Press <Enter> to quit.")
    win.close()

感谢您的帮助! -Michael

1 个答案:

答案 0 :(得分:0)

代码逻辑似乎等同于使用两个嵌套循环:

for xCoord in xrange(1, 10):
    for yCoord in xrange(1, 10):
        Text(Point(xCoord , yCoord ), "*").draw(win)