[英]Is there a way to check if a turtle is touching a color?
您可以在屏幕上检查海龟的坐标,看看它们是否位于或超过墙壁的坐标。
方法如下:
if -350 < turtle.xcor() < 350 and -325 < turtle.ycor() < 325: # For A
if turtle.xcor() >= 350:
turtle.setx(349)
if turtle.xcor() <= -350 and (25 < turtle.ycor() < 325 or -25 > turtle.ycor() > -325):
turtle.setx(-349)
if turtle.ycor() >= 325:
turtle.sety(324)
if turtle.ycor() <= -325:
turtle.sety(-324)
if -25 < turtle.ycor() < 25 and -425 < turtle.xcor() < -350: # For B
if turtle.ycor() > 25:
turtle.sety(24)
if turtle.ycor() < -25:
turtle.sety(-24)
我更喜欢一种最初比已经建议的答案具有更高开销的方法,但从长远来看会更简单,因为重新配置墙壁会更容易,而无需重做所有计算。
方法是用印章制作墙壁,即定义一个基本砖,它是一只乌龟,然后通过冲压砖并跟踪它们的位置来构建你的墙壁。 然后我们可以使用坐标比较碰撞检测来确保我们在 window 内部,但是对于内墙和外墙,我们可以使用海龟的distance()
方法:
from turtle import Screen, Turtle, Vec2D
from random import randrange
BRICK_SIZE = 75
WIDTH, HEIGHT = BRICK_SIZE * 9, BRICK_SIZE * 9
CURSOR_SIZE = 20
EXPLORER_COUNT = 10
EXPLORER_SIZE = BRICK_SIZE / 3.75
CHROME = 14 # window overhead, e.g. borders
def draw_wall(brick):
wall = []
brick.goto(-WIDTH/2 + 3 * BRICK_SIZE/2, -HEIGHT/2 + 3 * BRICK_SIZE/2)
for delta in [Vec2D(1, 0), Vec2D(0, 1), Vec2D(-1, 0), Vec2D(0, -1)]:
for index in range(6):
if not (index == 3 and delta == (0, -1)):
brick.stamp()
wall.append(brick.position())
brick.goto(brick.position() + delta * BRICK_SIZE)
return wall # a list of brick positions
def collision(t):
if any(t.distance(brick) < BRICK_SIZE * 2**0.5/2 for brick in wall):
return True
x, y = t.position()
width = screen.window_width()
if not EXPLORER_SIZE/2 - width/2 < x < width/2 - EXPLORER_SIZE/2:
return True
height = screen.window_height()
if not EXPLORER_SIZE/2 - height/2 < y < height/2 - EXPLORER_SIZE/2:
return True
return False
def move():
for explorer in explorers:
while True:
explorer.forward(1)
if not collision(explorer):
break
explorer.undo()
explorer.setheading(randrange(360))
screen.update()
screen.ontimer(move, 10)
screen = Screen()
screen.setup(WIDTH + CHROME, HEIGHT + CHROME)
screen.screensize(100, 100) # just to accommodate smaller windows
screen.tracer(False)
brick = Turtle()
brick.hideturtle()
brick.shape('square')
brick.shapesize(BRICK_SIZE / CURSOR_SIZE)
brick.color('green')
brick.penup()
wall = draw_wall(brick)
explorers = []
for _ in range(EXPLORER_COUNT):
explorer = Turtle()
explorer.shape('turtle')
explorer.shapesize(BRICK_SIZE / 3.75 / CURSOR_SIZE)
explorer.color('red', 'pink')
explorer.setheading(randrange(360))
explorer.penup()
explorers.append(explorer)
move()
screen.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.