import turtle,time,random bob = turtle.Turtle() sc = turtle.Screen() WIDTH = 1000 HEIGHT = 500 sc.setup(WIDTH,HEIGHT) ROWS = 10 COLUMNS = 20 START = (1,1) END = (10,20) centers = [[0 for i in range(COLUMNS)] for j in range(ROWS)] if HEIGHT//ROWS < WIDTH//COLUMNS: side = HEIGHT//ROWS-5 else: side = WIDTH//COLUMNS-5 def square(x,y,side,fill): bob.penup() bob.setpos(x,y) bob.setheading(0) bob.pendown() if fill: bob.begin_fill() for i in range(4): bob.forward(side) bob.right(90) bob.penup() if fill: bob.end_fill() def drawGrid(rows,columns): sc.tracer(1000) ycor = (-HEIGHT//2)+side+10 for i in range(rows): xcor = -WIDTH//2+10 for j in range(columns): centers[i][j] = (xcor+side//2,ycor-side//2) square(xcor,ycor,side,0) xcor+=side ycor+=side def goto(row,column): row = row-1 column = column-1 bob.setpos(centers[row][column][0],centers[row][column][1]) def gridsquare(row,column): row = row-1 column = column-1 bob.setpos(centers[row][column][0]-side//2,centers[row][column][1]+side//2) bob.begin_fill() for i in range(4): bob.forward(side) bob.right(90) bob.penup() bob.end_fill() def setobstacles(number): obstacles = [0]*number n = 0 while obstacles[-1] == 0: x = random.randint(1,ROWS) y = random.randint(1,COLUMNS) print(x,y) if (x,y) != START and (x,y) != END: obstacles[n] = (x,y) n += 1 return obstacles def drawobstacles(obstacles): for i in obstacles: print(i) gridsquare(i[0],i[1]) def drawstartend(START,END): bob.fillcolor("green") gridsquare(START[0],START[1]) bob.fillcolor("red") gridsquare(END[0],END[1]) obstacles = setobstacles(30) drawGrid(ROWS,COLUMNS) drawobstacles(obstacles) drawstartend(START,END) sc.tracer(2) bob.penup() goto(START[0],START[1]) currentx = START[0] currenty = START[1] DONE = False while not DONE: bob.pendown() candidates = [0]*4 if currentx-1 > 0 and (currentx-1,currenty) not in obstacles: candidates[0]=(currentx-1,currenty) if currentx+1 <= ROWS and (currentx+1,currenty) not in obstacles: candidates[1]=(currentx+1,currenty) if currenty+1 <= COLUMNS and (currentx,currenty+1) not in obstacles: candidates[2]=(currentx,currenty+1) if currenty-1 > 0 and (currentx,currenty-1) not in obstacles: candidates[3]=(currentx,currenty-1) candidates = [x for x in candidates if x != 0] print(currentx,currenty) #print(candidates) future = random.choice(candidates) print(future) #time.sleep(0.1) goto(future[0],future[1]) currentx = future[0] currenty = future[1] if currentx == END[0] and currenty == END[1]: DONE = True