Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找距离X1和Y1_Python_Python Turtle - Fatal编程技术网

Python 查找距离X1和Y1

Python 查找距离X1和Y1,python,python-turtle,Python,Python Turtle,我正在制作一个游戏,海龟是猎物,箭是猎人。它们位于屏幕中心的500 X 500“围栏”中。当猎人到达猎物一定距离内时,游戏结束。意思是距离有误 import turtle import random import math def difficulty(): global easy , medium , hard level= input("Select your Difficulty") easy=100 medium=50 har

我正在制作一个游戏,海龟是猎物,箭是猎人。它们位于屏幕中心的500 X 500“围栏”中。当猎人到达猎物一定距离内时,游戏结束。意思是距离有误

import turtle
import random
import math

def difficulty():
    global easy , medium , hard
    level= input("Select your Difficulty")
    easy=100
    medium=50
    hard=25
    
def position_prey():
    prey.penup()
    prey.forward(random.randint(50,100))
    prey.shape("turtle")
    

def create_fence():
    fence=turtle.Turtle()
    fence.penup()
    fence.goto(-250,-250)
    fence.pendown()
    fence.forward(500)
    fence.left(90)
    fence.forward(500)
    fence.left(90)
    fence.forward(500)
    fence.left(90)
    fence.forward(500)
    fence.hideturtle()   
    

def find_distance(hunter,prey):
    prey = x1
    hunter = x2
    distance=((x2-x1)**2 + (y1-y2)**2)**0.5
    

def move_hunter(x,y):
    hunter.penup()
    hunter.goto(x,y)
    find_distance(hunter,prey)
    
    
def move_prey():
    prey.forward(random.randint(100,100))
    find_distance(hunter,prey)
    

def Main():
    global hunter, prey
    hunter = turtle.Turtle()
    prey = turtle.Turtle()
    
    playground=turtle.Screen()
    playground.onclick(move_hunter)

    find_distance(hunter,prey)
    
    difficulty()

    position_prey()

    create_fence()

    move_prey()
Main()

根据文件:

为了获得“猎人”和“猎物”的位置,您需要使用
turtle.pos()
,它将返回一个包含x和y位置的元组

因此,您的
find_distance
函数应该如下所示:

def find_distance(hunter, prey):
    xHunter, yHunter = hunter.pos()
    xPrey, yPrey = prey.pos()
    distance=((xPrey-xHunter)**2 + (yPrey-yHunter)**2)**0.5

您最初的问题是x和y位置在该方法中设置不正确。祝你好运

除了@AaronBerger指出的参数问题外,我还看到了
find_distance()
函数的两个问题:

def find_distance(hunter,prey):
    prey = x1
    hunter = x2
    distance=((x2-x1)**2 + (y1-y2)**2)**0.5
首先,它实际上没有任何作用。由于
distance
未声明为全局变量,因此它只是一个局部变量。所以这计算了一个距离,但不做任何处理

其次,您正在(重新)定义已经内置到turtle中的功能,即
distance()
方法。我会这样做:

if hunter.distance(prey) < CERTAIN_DISTANCE:
    # do something
如果猎人距离(猎物)<特定距离:
#做点什么

find_distance
中,您正在将
prey
hunter
(您的函数参数)设置为
x1
x2
,可能您的意思是根据参数设置
x1
x2
。但是您也缺少了
y1
y2