简体   繁体   English

像素移动和循环Python

[英]Pixel movement and loops Python

We are using JES in my intro programming class and I have run into roadblock for my lab. 我们在入门编程课中使用的是JES,但遇到了实验的障碍。 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. 下面的当前程序将在最中央加载并吃掉1个像素,但不会进行其他移动。 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 and y , but this doesn't have any effect on bug . 您更改xy ,但这对bug没有任何影响。

Try: 尝试:

while hungerLevel < 400 :
    bug= getPixelAt(pic,x,y)
    #rest of code goes here

Incidentally, if you have identical code in an if block and an else block, you can streamline things by moving the duplicates outside of the blocks entirely. 顺便说一句,如果在if块和else块中具有相同的代码, if可以通过将重复项完全移出这些块来简化事情。 Ex: 例如:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM