问题:我浪费了大量时间,通过手工编码我的坐标来创建错误,臃肿的代码。我需要帮助学习如何用这个冗长的代码替换将给出相同结果的循环结构。目前,x和y坐标分别存储在名为xCoords和yCoords的单独数组中。如何简化这个并编写一个更优雅的程序版本?
[注意:这是我的第一个 StackOverflow帖子。请告诉我样式,礼仪或发布错误,我会解决它们。这个论坛对我来说是不可或缺的,我感谢大家的帮助。]
相关详情:
源代码:
# 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
答案 0 :(得分:0)
代码逻辑似乎等同于使用两个嵌套循环:
for xCoord in xrange(1, 10):
for yCoord in xrange(1, 10):
Text(Point(xCoord , yCoord ), "*").draw(win)