We are using JES in my intro programming class and I have run into roadblock for my lab. The program is supposed to allow a user to select a picture and then a moth(bug) will start at the center of the picture and make random movements and change pixels to white if they are not already to simulate eating. I am stuck on the movement part. the current program below will load and eat 1 pixel at the very center but make no other movements. Could someone give me a hint as to what I am doing wrong with my random movement calls?
from random import *
def main():
#lets the user pic a file for the bug to eat
file= pickAFile()
pic= makePicture(file)
show(pic)
#gets the height and width of the picture selected
picHeight= getHeight(pic)
picWidth= getWidth(pic)
printNow("The height is: " + str(picHeight))
printNow("The width is: " + str(picWidth))
#sets the bug to the center of the picture
x= picHeight/2
y= picWidth/2
bug= getPixelAt(pic,x,y)
printNow(x)
printNow(y)
color= getColor(bug)
r= getRed(bug)
g= getGreen(bug)
b= getBlue(bug)
pixelsEaten= 0
hungerLevel= 0
while hungerLevel < 400 :
if r == 255 and g == 255 and b == 255:
hungerLevel + 1
randx= randrange(-1,2)
randy= randrange(-1,2)
x= x + randx
y= y + randy
repaint(pic)
else:
setColor(bug, white)
pixelsEaten += 1
randx= randrange(-1,2)
randy= randrange(-1,2)
x= x + randx
y= y + randy
repaint(pic)
Looks like you're never updating the position of the bug within the loop. You change
x
andy
, but this doesn't have any effect onbug
.Try:
Incidentally, if you have identical code in an
if
block and anelse
block, you can streamline things by moving the duplicates outside of the blocks entirely. Ex: