首页 > 解决方案 > 碰撞检测器解码问题

问题描述

我可以将乌龟移动到终点,但是当乌龟越过终点线时,我的碰撞检测器不起作用。它会越过白色边界线,但我需要它在碰到 FINISH 字样时停止。还需要将乌龟保持在边界内。也许我需要解码 xcor() 算法?请帮忙!

import turtle as trtl

background = trtl.Screen()
background.screensize(canvwidth =1, canvheight=1)



boundary = trtl.Turtle()

#draw square boundary
def squareDraw(boundary):
  boundary.speed(0)
  boundary.pu()
  boundary.goto(-175,160)
  boundary.pd()
  for i in range(4):
    boundary.color("white")
    boundary.forward(315)
    boundary.right(90)
    boundary.ht()
squareDraw(boundary)

boundary.pu()
boundary.goto(-40,160)
boundary.color("red")
boundary.pd()
boundary.write("FINISH!", font=40)



#moving square coordinates 
turtleCoordinate = (-25,-120)
turtleShape = trtl.Turtle()
turtleShape.left(90)
turtleShape.shape("turtle")
turtleShape.color("orange")
turtleShape.shapesize(1.75)
turtleShape.pu()
turtleShape.goto(turtleCoordinate)

#boundarys for answers
obstacles = trtl.Turtle()
obstacles.speed(0)
obstacles.pu()
obstacles.goto(-120,90)
obstacles.color("white")
for i in range(4):
  obstacles.pd()
  obstacles.forward(50)
  obstacles.right(90)
  obstacles.ht()

obstacles.pu()
obstacles.goto(0,12)
obstacles.color("white")
for i in range(4):
  obstacles.pd()
  obstacles.forward(40)
  obstacles.right(90)
  obstacles.ht()

obstacles.pu()
obstacles.goto(68,125)
obstacles.color("white")
for i in range(4):
  obstacles.pd()
  obstacles.forward(30)
  obstacles.right(90)
  obstacles.ht()



#1st math problem
firstProblem = []
secondProblem = [8,2,1]


#steps = 0
#while steps < 100:
for turtleShape in firstProblem:
  turtleShape.forward(4)
  if turtleShape.xcor() > 140:
    turtleShape.right(180)
  elif turtleShape.xcor() > -175:
    turtleShape.left(180)
  if turtleShape.ycor() > 160:
    turtleShape.right(180)
  elif turtleShape.ycor() < -155:
    turtleShape.right(180)


  
#actions to move turtle
move_speed = 15

def left():
  turtleShape.left(move_speed)
def right():
  turtleShape.right(move_speed)
def forward():
  turtleShape.forward(move_speed)
def backward():
  turtleShape.backward(move_speed)



background.onkey(forward, "Up")
background.onkey(backward, "Down")
background.onkey(left, "Left")
background.onkey(right, "Right")
background.listen()

steps = 0
for turtleShape in firstProblem:
  stepMax = 15
  if steps > stepMax:
    turtleShape.forward(3)



background = trtl.Screen()
background.mainloop()

标签: python

解决方案


在 left()、right()、forward()、backward() 函数中移动边界检查。示例:在 forward 函数中,您将检查您是否到达边界,并且仅向前执行 min(move_speed, boundary - y position)。这将使您准确地停在边界处。


推荐阅读