虽然循环不正确停止,因为它应该
问题描述:
我正在写一个小程序,旨在绘制一个25像素的地方,无论在哪里,randrange会给它它的点。我还有4个红色盒子,充当炸弹或地雷。当该行的x,y通过getColor函数为红色时,var'color'将变为红色。因此停止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")
答
你想实现这一点:
#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:
如何'red'和'blue'界定? – Iguananaut
您是否尝试过自己调试此问题?我打赌一些printf调试可以做到这一点。 https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – jdv
@Iguananaut更像是“颜色”定义在哪里...... –