開始点がグリッドの中央で、ユーザーが列と行の数を指定する、グリッド全体のランダムな動きをグラフ化するプログラムを作成しています。現在の問題は、プログラムの終了を知らせる必要がある 2 つの変化する変数があることです。X は水平移動用、Y は垂直移動用です。どちらかがグリッドの外に出たら、プログラムを終了する必要があります。現時点では、1 つの変数がオフになると、もう一方がオフになるまで実行を続けます。(例.垂直方向にグリッドから外れても、プログラムはランダムな方向を選択して水平方向に移動し続けます。水平方向にも同じことが言えます。)したがって、どちらかが移動したときに終了するようにプログラムを作成する方法がわかりません。両方を待つのではなく、オフにします。ここに私がこれまでに持っているものがあります:
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