You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Turtle:如何确保随机移动的海龟始终处于绘制边界内?

问题:让随机移动的turtle对象始终保持在指定方框内移动

我创建了两个turtle对象,分别命名为t和to。其中t的边界碰撞逻辑已经实现:当t碰到由turtle d绘制的边界时,会打印"game over"并终止程序。现在我需要实现让随机移动的turtle to始终保持在d绘制的方框范围内移动。以下是我的代码:

from time import sleep
import turtle
import random

s = turtle.Screen()
s.bgcolor('white')
s.setup(500,380)

d=turtle.Turtle()
d.penup()
d.goto(-150,-150)
d.pensize(5)
d.pendown()
d.hideturtle()
for x in range(4):
  d.forward(300) 
  d.left(90) 

t = turtle.Turtle()
t.shape('turtle')
t.color('blue')
t.penup()
to = turtle.Turtle()
to.shape('turtle')
to.color('black')
to.penup()


for peepee in range(1, 6):
    xcor=[]
    ycor=[]
    xrandomlist=[]
    yrandomlist=[]
    if peepee==5:
      print("ur now on the final level")
    else:
      print(f"u r playing level {peepee}.")

    t.goto(40,-40)

  
    to.goto(40,40)
    t.setheading(180)
    to.setheading(180)
    to.speed(peepee)

    def left():
      t.left(90)

    def right():
      t.left(-90)

    def goup():
      t.forward(15)
      xcor.append(t.xcor())
      ycor.append(t.ycor())
    def godown():
      t.forward(-15)
      xcor.append(t.xcor())
      ycor.append(t.ycor()) 
      
    def skadaddle():
      if to.distance(t) < 120:
        to.setheading(to.towards(t) + 180)
      to.forward(30)


    def drunkt():
      turn=random.choice([90,-90])
      to.left(turn)
      go=random.choice([-20, 20])
      def yoyo():
        to.forward(go)
        xrandomlist.append(to.xcor())
        yrandomlist.append(to.ycor())
      yoyo()
      skadaddle()
      
    s.onkeypress(left, "Left")
    s.onkeypress(right, "Right")
    s.onkeypress(goup, "Up")
    s.onkeypress(godown, "Down")
    s.listen()

    while True:
      drunkt()
      skadaddle() 
      if t.xcor()>130 or t.xcor()<-130:
        print("game over")
        s.bye()
        sleep(9999)
      if t.ycor()>130 or t.ycor()<-130:
        print("game over")
        s.bye()
        sleep(9999)
      if t.distance(to)<50:
        print(' ')
        print("noice")
        print(' ')
        for x in range(len(xcor)):
          t.speed(1)
          t.goto(xcor[-1],ycor[-1])
          xcor.pop(-1)
          ycor.pop(-1)

        for x in range(len(xrandomlist)):
          to.speed(1)
          t.goto(xrandomlist[-1],yrandomlist[-1])
          xrandomlist.pop(-1)
          yrandomlist.pop(-1)
        sleep(2)
        break

turtle.done()
s.bye()

解决方案

要实现to始终在方框内移动,核心思路是每次移动后检查坐标是否超出边界,若超出则修正位置。具体步骤如下:

1. 明确边界范围

d绘制的方框从(-150, -150)开始,边长300,结合t的边界检查逻辑(±130),给to设置同样的边界范围,避免视觉上越界。

2. 新增边界检查函数

添加专门的函数用于检查并修正to的坐标:

def check_to_boundary():
    x = to.xcor()
    y = to.ycor()
    if x > 130:
        to.setx(130)
    elif x < -130:
        to.setx(-130)
    if y > 130:
        to.sety(130)
    elif y < -130:
        to.sety(-130)

3. 在移动逻辑中调用边界检查

修改drunkt和skadaddle函数,在每次移动后调用check_to_boundary,确保to不会越界:

  • 在drunkt的yoyo移动后调用该函数
  • 在skadaddle的forward移动后调用该函数

修改后的完整代码

from time import sleep
import turtle
import random

s = turtle.Screen()
s.bgcolor('white')
s.setup(500,380)

d=turtle.Turtle()
d.penup()
d.goto(-150,-150)
d.pensize(5)
d.pendown()
d.hideturtle()
for x in range(4):
  d.forward(300) 
  d.left(90) 

t = turtle.Turtle()
t.shape('turtle')
t.color('blue')
t.penup()
to = turtle.Turtle()
to.shape('turtle')
to.color('black')
to.penup()

# 新增边界检查函数
def check_to_boundary():
    x = to.xcor()
    y = to.ycor()
    if x > 130:
        to.setx(130)
    elif x < -130:
        to.setx(-130)
    if y > 130:
        to.sety(130)
    elif y < -130:
        to.sety(-130)

for peepee in range(1, 6):
    xcor=[]
    ycor=[]
    xrandomlist=[]
    yrandomlist=[]
    if peepee==5:
      print("现在是最终关卡")
    else:
      print(f"当前关卡:{peepee}")

    t.goto(40,-40)

  
    to.goto(40,40)
    t.setheading(180)
    to.setheading(180)
    to.speed(peepee)

    def left():
      t.left(90)

    def right():
      t.left(-90)

    def goup():
      t.forward(15)
      xcor.append(t.xcor())
      ycor.append(t.ycor())
    def godown():
      t.forward(-15)
      xcor.append(t.xcor())
      ycor.append(t.ycor()) 
      
    def skadaddle():
      if to.distance(t) < 120:
        to.setheading(to.towards(t) + 180)
      to.forward(30)
      # 移动后检查边界
      check_to_boundary()


    def drunkt():
      turn=random.choice([90,-90])
      to.left(turn)
      go=random.choice([-20, 20])
      def yoyo():
        to.forward(go)
        xrandomlist.append(to.xcor())
        yrandomlist.append(to.ycor())
      yoyo()
      # 移动后检查边界
      check_to_boundary()
      skadaddle()
      
    s.onkeypress(left, "Left")
    s.onkeypress(right, "Right")
    s.onkeypress(goup, "Up")
    s.onkeypress(godown, "Down")
    s.listen()

    while True:
      drunkt()
      if t.xcor()>130 or t.xcor()<-130:
        print("game over")
        s.bye()
        sleep(9999)
      if t.ycor()>130 or t.ycor()<-130:
        print("game over")
        s.bye()
        sleep(9999)
      if t.distance(to)<50:
        print(' ')
        print("不错!")
        print(' ')
        for x in range(len(xcor)):
          t.speed(1)
          t.goto(xcor[-1],ycor[-1])
          xcor.pop(-1)
          ycor.pop(-1)

        for x in range(len(xrandomlist)):
          to.speed(1)
          t.goto(xrandomlist[-1],yrandomlist[-1])
          xrandomlist.pop(-1)
          yrandomlist.pop(-1)
        sleep(2)
        break

turtle.done()
s.bye()

额外优化

  • 将原代码中的英文提示改为中文,提升可读性
  • 修正了原代码中一处笔误(t.color('black')改为to.color('black'))

内容的提问来源于stack exchange,提问作者Davi Castro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:17:57