簡體   English   中英

像素移動和循環Python

[英]Pixel movement and loops Python

我們在入門編程課中使用的是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)

看起來您永遠不會在循環中更新錯誤的位置。 您更改xy ,但這對bug沒有任何影響。

嘗試:

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

順便說一句,如果在if塊和else塊中具有相同的代碼, if可以通過將重復項完全移出這些塊來簡化事情。 例如:

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