如何检查两只海龟在海龟图形上的 x、y 坐标是否相同?

How to check if two turtles have the same x, y coordinates on turtle graphics?

作为我的第一个乌龟项目,我开始编写“贪吃蛇”游戏的代码,但它不是一条蛇,而是一只吃随机搭配食物的乌龟。

我在吃食物的时候遇到了问题。我的意思是,必须有一个 if 语句来检查蛇(即乌龟)和食物(也是乌龟)是否在相同的 XY 坐标中。如果是的话,先把乌龟变大,然后把食物藏起来,再给它取一个随机坐标,然后显示在屏幕上。

这是我的代码:

from turtle import *
from random import *


def go():
    # the main walking function for the turtle
    turtle.forward(2)


def rotate():
    # to rotate the turtle 90 degrees to the left
    turtle.left(90)


def getfood():
    # get random coordinates for the food
    x = randint(-280, 280)
    y = randint(-280, 280)
    # set the food to the random position
    food.hideturtle()
    food.up()
    food.goto(x, y)
    food.showturtle()


turtle = Turtle()
screen = Screen()
screensize(600, 600)
food = Turtle()
food.shape('circle')
turtle.shape('turtle')
turtle.shapesize(3)
turtleSize = 3
getfood()
while True:
    turtle.up()
    go()
    #  check if the turtle has eaten the food.
    if food.xcor == turtle.xcor and food.ycor() == turtle.ycor():
        turtleSize += 1
        turtle.shapesize(turtleSize)
        getfood()
    # let the player rotate pressing the "a" key
    screen.listen()
    screen.onkeypress(rotate, 'a')

问题就在那里,在 if 语句中检查乌龟是否吃过食物。执行甚至没有进入它。一定是因为那些 xcor()ycor() 方法,但我不知道应该使用什么。你能帮我吗? :)

如果turtle1.pos() == turtle2.pos(): 打印('Two turtles are together')

你可以做的是以半径的形式定义乌龟和食物的碰撞边界,并检查两个半径的总和是否大于从一只乌龟到另一只乌龟的distance。以下代码应该可以工作。

turtle.radius = 10
food.radius = 5
while True:
    turtle.up()
    go()
    #  check if the turtle has eaten the food.
    if (turtle.radius+food.radius)>=food.distance(turtle):
        turtleSize += 1
        turtle.shapesize(turtleSize)
        getfood()
    # let the player rotate pressing the "a" key
    screen.listen()
    screen.onkeypress(rotate, 'a')

ps:您可以根据需要设置半径值。我只是使用了两个随机值。

以下是我想解决的几件事:

  1. 当你只需要从一个模块导入一到两个函数时, 不要使用星号来导入 所有 函数。

  2. 而不是在你的海龟对象上使用未绑定的函数, 创建一个 class。您可以在那里安全地存储动态属性,例如,海龟进食时的大小。

  3. while循环内部调用screen.onkeypress很浪费效率;在循环之前调用它一次就足够了。

这里重写了你的代码,实现了吃东西的动作:

from turtle import Turtle, Screen
from random import randint
from time import sleep

class Eater(Turtle):
    def __init__(self, size):
        Turtle.__init__(self)
        self.shapesize(size)
        self.shape('turtle')
        self.penup()
        self.turtleSize = size

    def touched(self, food):
        return self.turtleSize * 10 >= food.distance(self)

    def eat(self, food):
        self.turtleSize += 1
        self.shapesize(self.turtleSize)
        x = randint(-280, 280)
        y = randint(-280, 280)
        food.goto(x, y)

    def go(self):
        self.forward(2)

    def rotate(self):
        self.left(90)

screen = Screen()
screen.setup(600, 600)
screen.tracer(0)

food = Turtle('circle')
food.penup()

turtle = Eater(3)

screen.listen()
screen.onkeypress(turtle.rotate, 'a')

while True:
    sleep(0.01)
    turtle.go()
    if turtle.touched(food):
        turtle.eat(food)
    screen.update()

输出: