【问题标题】:Pixel movement and loops Python像素移动和循环 Python
【发布时间】:2015-06-22 22:19:49
【问题描述】:

我们在我的编程入门课程中使用 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)

【问题讨论】:

    标签: python jes


    【解决方案1】:

    看起来您永远不会更新循环中错误的位置。您更改了xy,但这对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)
    

    【讨论】:

    • 这非常有效。谢谢!我认为当我感到沮丧时,我应该远离代码。 ;p
    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多