Longer than intended loop due to multiple variables
I'm making a program that charts a random movement across a grid, where
the starting point is the middle of the grid and the user gives the number
of columns and rows. The current problem is that I have two changing
variables that both need to signal the end of program. X is for horizontal
movement and Y is for vertical: if either of them go outside of the grid,
I need the program to end. At the moment, when one variable goes off, it
continues running until the other does. (Ex. If it moves off the grid
vertically, the program still keeps picking random directions and moving
horizontally. The same it true for horizontal.) So I'm not sure how to
write the program so that it ends when one of them goes off, instead of
waiting for both. Here's what I've got so far:
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()
Here's a sample of the intended output:
>>> 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
No comments:
Post a Comment