【问题标题】:How to detect if two turtles are near each other or touch each other如何检测两只乌龟是否彼此靠近或相互接触
【发布时间】:2021-06-20 15:28:03
【问题描述】:

所以我正在尝试用python制作一个蛇游戏,我达到了蛇必须吃掉水果/点才能成长的地步。所以我做了两只乌龟。一个是蛇头,一个是必须吃的果子。除了我不知道怎么做,所以当蛇头龟碰到水果时,水果会随机到另一个位置。 这是我到目前为止的代码:

import turtle
import random
import time

points = 0
game_over = False

# Create map
screen = turtle.Screen()
screen.bgcolor('black')

# Create turtles :)
snake = turtle.Turtle()
snake.color('white')
snake.penup()

point_master = turtle.Turtle()
point_master.color('white')
point_master.penup()


snake.penup()

# Code snake so it can move :D
snake_speed = 2

def travel():
    snake.forward(snake_speed)
    screen.ontimer(travel, 10)

screen.onkey(lambda: snake.setheading(90), 'Up')
screen.onkey(lambda: snake.setheading(180), 'Left')
screen.onkey(lambda: snake.setheading(0), 'Right')
screen.onkey(lambda: snake.setheading(270), 'Down')

# Here is where we code it so when the snake touches the fruit the fruit will relocate.



# Continues to make snake move :)
screen.listen()
travel()
screen.mainloop()

【问题讨论】:

  • 那么,你知道如何确定海龟的位置吗?你知道如何确定两点之间的距离吗?你真正的问题是什么?
  • 我可以确定乌龟的位置。我试过这样的东西:snake.distance(point_master)
  • "我尝试过这样的事情:snake.distance(point_master)
  • 当我运行它并检查水果时它什么也没做
  • 好的,你有没有试过检查snake.distance(point_master)返回的内容,在蛇离水果足够近的地方?你试过检查它是否真的被调用了吗?

标签: python python-3.x module


【解决方案1】:

在海龟中,我们有 xcor()ycor()setx()sety()

xcor() 查找 x 轴上的对象(在这种情况下它可以是你的蛇或食物)在哪里。

ycor() 是相同的,但它会在 y 轴上找到位置。

setx()你移动x轴

例子:

if .......: 
    turtle.setx(-20)

这意味着如果 .... 发生海龟将在 x 轴上移动 -20

sety() 相同,不同的是海龟会在 y 轴上移动

在你的情况下,你可以做这样的事情

xy=random.randint(0,100)
food = turtle.Turtle()
food.goto(10, 50)

#lets say that in first level it will start on 10,50 cordinates

if snake.xcor == food.xcor and snake.ycor == food.xcor:
    food.goto(xy, xy)

#xy was the random number between 0-100    
#for setx() and sety() you can use it on your key bindings

【讨论】:

  • 欢迎来到 SO!您可以用反引号 ` 包围代码(一个用于内联元素,或三个一组用于块)以格式化您的帖子中的代码,这将使其更清晰!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
相关资源
最近更新 更多