像素移动和循环 Python
Pixel movement and loops Python
我们在我的入门编程中使用 JES class,我 运行 成为我实验室的障碍。该程序应该允许用户 select 一张图片,然后一只飞蛾(虫子)将从图片的中心开始并随机移动并将像素更改为白色(如果它们尚未模拟进食)。我被困在运动部分。下面的当前程序将在最中心加载并吃掉 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)
看来您从未更新循环中错误的位置。您更改 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)
我们在我的入门编程中使用 JES class,我 运行 成为我实验室的障碍。该程序应该允许用户 select 一张图片,然后一只飞蛾(虫子)将从图片的中心开始并随机移动并将像素更改为白色(如果它们尚未模拟进食)。我被困在运动部分。下面的当前程序将在最中心加载并吃掉 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)
看来您从未更新循环中错误的位置。您更改 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)