【问题标题】:How to set screen boundaries python turtle如何设置屏幕边界蟒蛇
【发布时间】:2017-11-29 01:26:45
【问题描述】:

如何设置屏幕边界,以便当海龟到达边缘时它会停止或转身

import turtle
t=turtle.Turtle()
s=turtle.Screen()
p=t.xcor()
p1=t.ycor()

x=300
y=300
s.setup(x,y)

t.color("white")
s.bgcolor("black")

def up():
  player=False
  while player==False:
    t.speed(1)
    t.fd(10)

def right():
  t.speed(0)
  t.right(90)

def left():
  t.speed(0)
  t.left(90)

s.onkey(up,"up")
s.onkey(right,"right")  
s.onkey(left,"left")
s.listen()

我认为这会将它停在屏幕边缘
下面的代码还没有完全完成,但我不知道要改成什么

while p and p1 != x and y:
  t.right(90)
  if p and p1 == x and y:
    t.speed(0)
    t.right(180)

【问题讨论】:

  • 在其他图形系统/模块中,当您必须移动 100 像素时,您会这样做:移动几个像素(即 2 个像素),检查碰撞(即与屏幕边框),再次移动几个像素,检查再次发生碰撞,等等 - 所以你循环运行它。

标签: python-3.x turtle-graphics


【解决方案1】:

我很惊讶你的代码在我的海龟系统上没有被识别为有效的键符 - 它必须大写:'Up'。也许这是 Unix / Windows 的分裂。

与其一次移动一个或两个像素来测试您是否越过边界,这是另一种方法。向前移动合理的距离,检测您何时越过边界,撤消向前移动,转身,重新向前移动:

from turtle import Turtle, Screen

WIDTH, HEIGHT = 500, 500

DISTANCE = 10

screen = Screen()
screen.setup(WIDTH, HEIGHT)
screen.bgcolor('black')

turtle = Turtle()
turtle.speed('fastest')
turtle.color('white')

def up():
    turtle.forward(DISTANCE)  # try first and undo on error

    x, y = turtle.position()

    if not -WIDTH / 2 < x < WIDTH / 2 or not -HEIGHT / 2 < y < HEIGHT / 2:
        turtle.undo()  # undo error
        turtle.left(180)  # turn around
        turtle.forward(10)  # redo movement but in new direction

def right():
    turtle.right(90)

def left():
    turtle.left(90)

screen.onkey(up, 'Up')
screen.onkey(right, 'Right')
screen.onkey(left, 'Left')

screen.listen()
screen.mainloop()

如果您添加任何其他移动功能,例如Down 用于向后移动,然后将越界逻辑移动到自己的函数中,并与所有移动命令共享。

【讨论】:

    【解决方案2】:

    就像 furas 所说,您需要在循环中一次移动几个像素并检查碰撞。我最近需要一个类似的功能,如果你想试试的话,这里就是。我从未使用过 python turtle.screen,但我相信你可以在列表中定义边缘,因为我在 for 循环中使用了这段代码,它不应该触及。

    def online(point,edge):
      first = edge[0]
      second = edge[1]
      firstx = first[0]
      firsty = first[1]
      secondx = second[0]
      secondy = second[1]
      if firstx <= point[0] <= secondx and firsty >= point[1] >= secondy:
        return(True)
      elif firstx <= point[0] <= secondx and firsty <= point[1] <= secondy:
        return(True)
      elif firstx >= point[0] >= secondx and firsty >= point[1] >= secondy:
        return(True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-08
      • 2019-01-08
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多