Game Master
Game Master

Reputation: 1

Find distance X1 and Y1

I'm creating a game where The turtle is the prey, and the arrow is the hunter. They are positioned in a 500 X 500 “fence” that is centered on the screen. The game ends when the hunter gets within a certain distance of the prey.it's saying there's an error with the distance

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()

Upvotes: 0

Views: 80

Answers (2)

cdlane
cdlane

Reputation: 41872

Besides the argument issues that @AaronBerger points out, I see two more problems with your find_distance() function:

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

First, it effectively doesn't do anything. Since distance isn't declared global, it's just a local variable. So this calculates a distance and does nothing with it.

Second, you're (re)defining functionality that's already built into turtle, i.e. the distance() method. I would have done:

if hunter.distance(prey) < CERTAIN_DISTANCE:
    # do something

Upvotes: 1

Aaron Berger
Aaron Berger

Reputation: 73

According to the documentation HERE:

In order to get the positions of the "hunter" and "prey", you'll need to use turtle.pos(), which will return a tuple containing the x and y positions.

So, your find_distance function should look something like this:

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

Your original problem was that the x and y positions were not set correctly in that method. Good luck!

Upvotes: 0

Related Questions