我们在我的介绍编程课程中使用JES,而且我的实验室遇到了障碍。该程序应该允许用户选择图片,然后飞蛾(虫子)将从图片的中心开始并进行随机移动并将像素更改为白色(如果它们尚未模拟进食)。我被困在运动部分。下面的当前程序将加载并在正中心吃掉1个像素但不做其他动作。有人可以给我一个关于我随机移动电话的错误提示吗?
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)
答案 0 :(得分:0)
看起来你永远不会在循环中更新错误的位置。您更改了x
和y
,但这对bug
没有任何影响。
尝试:
while hungerLevel < 400 :
bug= getPixelAt(pic,x,y)
#rest of code goes here
顺便提一下,如果if
块和else
块中的代码相同,则可以通过完全移动块外部的副本来简化操作。例如:
while hungerLevel < 400 :
bug= getPixelAt(pic,x,y)
if r == 255 and g == 255 and b == 255:
hungerLevel + 1
else:
setColor(bug, white)
pixelsEaten += 1
randx= randrange(-1,2)
randy= randrange(-1,2)
x= x + randx
y= y + randy
repaint(pic)