我正在制作一个程序来绘制网格中的随机移动,其中起点是网格的中间,用户给出列数和行数。当前的问题是我有两个变化的变量都需要发出程序结束的信号。X 用于水平移动,Y 用于垂直移动:如果它们中的任何一个超出网格,我需要程序结束。目前,当一个变量关闭时,它会继续运行,直到另一个变量关闭。(例如,如果它垂直离开网格,程序仍然会继续选择随机方向并水平移动。水平方向也是如此。)所以我不知道如何编写程序,以便在其中一个方向移动时结束关闭,而不是同时等待。这是我到目前为止所得到的:
import random
def rightmove(width, px):
px += 1
if px > width:
return px
else:
return px
def leftmove(width, px):
px -= 1
if px == -1:
return px
else:
return px
def downmove(height, py):
py += 1
if py == height:
return py
else:
return py
def upmove(height, py):
py += 1
if py == -1:
return py
else:
return py
def main():
height = raw_input("Please enter the desired number of rows: ")
height = int(height)
width = raw_input("Please enter the desired number of columns: ")
width = int(width)
px = round(width/2)
px = int(px)
py = round(height/2)
py = int(py)
print "Manhattan (" + str(width) + ", " + str(height) + ")"
print "(x, y) " + str(px) + " " + str(py)
topy = height + 1
topx = width + 1
while 0 <= px <= width:
while 0 <= py <= height:
s = random.randint(0, 1)
if s == 0:
x = random.randint(0, 1)
if x == 0:
px = leftmove(width, px)
if px <= 0:
print "Direction E (x, y) " + str(px)
else:
print "Direction E"
else:
px = rightmove(height, px)
if px <= width:
print "Direction W (x, y) " + str(px)
else:
print "Direction W"
else:
y = random.randint(0, 1)
if y == 0:
py = downmove(height, py)
if py <= height:
print "Direction S (x, y) " + str(py)
else:
print "Direction S"
else:
py = upmove(height, py)
if py <= 0:
print "Direction N (x, y) " + str(py)
else:
print "Direction N"
main()
这是预期输出的示例:
>>> manhattan(5,7)
(x, y) 2 3
direction N (x, y) 1 3
direction N (x, y) 0 3
direction S (x, y) 1 3
direction W (x, y) 1 2
direction S (x, y) 2 2
direction E (x, y) 2 3
direction S (x, y) 3 3
direction W (x, y) 3 2
direction N (x, y) 2 2
direction W (x, y) 2 1
direction E (x, y) 2 2
direction W (x, y) 2 1
direction N (x, y) 1 1
direction N (x, y) 0 1
direction S (x, y) 1 1
direction W (x, y) 1 0
direction E (x, y) 1 1
direction W (x, y) 1 0
direction W