虽然循环没有按预期正确停止

时间:2017-10-21 13:39:22

标签: python

我正在编写一个小程序,旨在绘制一条25像素的行,只要randrange给它点数。我还有4个红色盒子作为炸弹或地雷。当getColor函数的行的x,y为红色时,var'颜色为'将==变为红色。因此停止while循环,这将阻止该行继续。这也是我在比赛场地上绘制的蓝点所需的功能。我发现我的程序不能以这种方式运行。关于我如何解决这个问题的任何建议?

 from random import *
 def main( ):
    #draw
    pic = makeEmptyPicture(600, 600, white)
    show(pic)

  #for the 4 boxes 
  boxCount = 0
  #while statement to draw
  while boxCount < 4:
       addRectFilled(pic, randrange(0,576), randrange(0,576), 25, 25, red)
       addArcFilled(pic, randrange(0,576), randrange(0,576), 10, 10, 0, 360, blue)
       boxCount = boxCount + 1
  repaint(pic)

  #vars for  while statement
  newX = 0
  newY = 0
  oldX = 0
  oldY = 0
  robotcount = 0
  finished = 0 
  safe = 0 
  triggered = 0
  #while loop, stops @ step 750, or when a px == red/blue
   while robotcount < 750 or color == red or color == blue:

         oldX = newX
         oldY = newY
         #how to generate a new line poing +25/-25
         newX = newX + randrange(-25, 26)
         newY = newY + randrange(-25, 26)
         #if statements to ensure no x or y goes over 599 or under 0
         if newX > 599 or newX < 0:
            newX = 0
         if newY > 599 or newY < 0:
            newY = 0
         #functions to get pixel color of x,y
         px = getPixel(pic, newX, newY)
         color = getColor(px)
         #draw the line from old to new, and also add +1 count for robot's steps
         addLine(pic, oldX, oldY, newX, newY, black)
         robotcount = robotcount + 1

  #if statement to determine why the while loop stops
  if color == red:
      triggered = 1
      printNow("trig")
  if color == blue:
      safe = 1
      printNow("safe")
  if robotcount == 750:
      finished = 1
      printNow("Fin")

1 个答案:

答案 0 :(得分:0)

你想实现这个目标:

 #while loop, stops @ step 750, or when a px == red/blue

这不起作用:

while robotcount < 750 or color == red or color == blue:

使用for循环会更简单:

for robotcount in range(750):
    if color == red or color == blue:
        break

您还可以使用while循环并修复条件(请注意!=):

while robotcount < 750 or color != red or color != blue: