简体   繁体   中英

How do I calculate the distance between a set x, y coordinate and location variables?

For context im trying to convert this code in python that takes a location on a minecraft map of the earth, takes multiple warps from around the map and sends the user an image on discord with the nearest warp with a line going between the inputed location and the warp location


import discord
import os
from discord.ext import commands
import math
from PIL import Image, ImageDraw
from io import BytesIO
import time


eco = []


NearestLand = ''
NearestCoords = []
sa = 0
side = ''

spawnPoints = {
    "Oceania Spawn": [16801, 2761],
    "Antartica Spawn": [8178, 8661],
    "Europe Spawn": [-386, -4782],
    "Asia Spawn": [12808, -3192],
    "Africa Spawn": [2420, 3738],
    "North America Spawn": [-10288, -4852],
    "South America Spawn": [-6487, 1360],
    "Soviet Nexus": [16507,-6595],
    "Ryvendor Warp-Pad":[9640,-2390],
    "Gulag Warp-Pad":[11741,-4596],
    "Soviet-Serbia Base Warp-Pad":[-10137,-5374],
    "KGB HQ Warp-Pad":[12958,-5627],
}

client = commands.Bot(command_prefix = '!')

@client.event
async def on_ready():
    print('Bot Started.')
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="For Intruders"))
    
@client.command()
async def test(ctx):
    await ctx.send('All systems functioninal comrade!')

@client.command()
async def envoy(ctx, x, y):

    await ctx.send("Calculating Comrade!")
    
    time.sleep(2)

    lowest = 1000000000
    eco = [x, y]
    for i in range(0, 2):
        eco[i] = int(eco[i])
    print("Crate's Coordinates at X = {x}, Y = {y}".format(x=eco[0], y=eco[1]))
    # print(eco)
    # print(spawnPoints.get('Oceania'))
    for i in spawnPoints:
        z = math.dist(spawnPoints[i], eco)
        # print("From {spawn}, ".format(spawn = str(i)) + str(z) + " blocks away.")
        if lowest >= z:
            lowest = z
            # print("The lowest distance is at: " + str(lowest) + ", at "+ i)
            NearestLand = i
            NearestCoords = spawnPoints[i]
            print("newNearDist: " + str(math.dist(spawnPoints[i], eco)))

    await ctx.send("The nearest warp point is on {nl}, and the distance is {z}.".format
    (nl=NearestLand, z=round(lowest, 2)))
    print(NearestCoords)

    xmap = Image.open("map.jpg")
    draw = ImageDraw.Draw(xmap)
    draw.line(
        ((int(NearestCoords[0]) + 21472) / 10,
        (int(NearestCoords[1]) + 10735) / 10,
        (int(x) + 21472) / 10,
        (int(y) + 10735) / 10),
        fill = (255, 0, 0),
        width = 10)
    draw.ellipse(

    ((((int(x) + 21472) / 10) - 25),

    (((int(y) + 10735) / 10) - 25),

    (((int(x) + 21472) / 10) + 25),

    (((int(y) + 10735) / 10) + 25)),
    fill = (255, 0, 0),
    width = 25)



    #draw.line(((42975 - x)/10), ((21471 - y)/10))
    xmap.save("xmap.jpg")
    print("Saved! Uploading...")
    await ctx.send(file = discord.File("xmap.jpg"))
    print("Uploaded!")

@client.command()
async def envoys(ctx, x, y):

    await ctx.send("Calculating...")
    
    time.sleep(2)

    lowest = 1000000000
    eco = [x, y]
    for i in range(0, 2):
        eco[i] = int(eco[i])
    print("Crate's Coordinates at X = {x}, Y = {y}".format(x=eco[0], y=eco[1]))
    # print(eco)
    # print(spawnPoints.get('Oceania'))
    for i in spawnPoints:
        z = math.dist(spawnPoints[i], eco)
        # print("From {spawn}, ".format(spawn = str(i)) + str(z) + " blocks away.")
        if lowest >= z:
            lowest = z
            # print("The lowest distance is at: " + str(lowest) + ", at "+ i)
            NearestLand = i
            NearestCoords = spawnPoints[i]
            print("newNearDist: " + str(math.dist(spawnPoints[i], eco)))

    await ctx.send("The nearest warp point is on {nl}, and the distance is {z}.".format
    (nl=NearestLand, z=round(lowest, 2)))
    print(NearestCoords)

    xmap = Image.open("map.jpg")
    draw = ImageDraw.Draw(xmap)
    draw.line(
        ((int(NearestCoords[0]) + 21472) / 10,
        (int(NearestCoords[1]) + 10735) / 10,
        (int(x) + 21472) / 10,
        (int(y) + 10735) / 10),
        fill = (255, 0, 0),
        width = 10)
    draw.ellipse(

    ((((int(x) + 21472) / 10) - 25),

    (((int(y) + 10735) / 10) - 25),

    (((int(x) + 21472) / 10) + 25),

    (((int(y) + 10735) / 10) + 25)),
    fill = (255, 0, 0),
    width = 25)



    #draw.line(((42975 - x)/10), ((21471 - y)/10))
    xmap.save("xmap.jpg")
    print("Saved! Uploading...")
    await ctx.send(file = discord.File("xmap.jpg"))
    print("Uploaded!")



client.run(os.getenv('TOKEN'))

Into node, This is what I have so far:

const Discord = require('discord.js');
const fs = require('file-system');
require('dotenv').config();
const client = new Discord.Client();
const { prefix } = require('config.json');
client.commands = new Discord.Collection();

client.on('ready', () => console.log('The Bot is ready!'));

client.user.setActivity("For Intruders", { type: "WATCHING" });

const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  client.commands.set(command.name, command);
}



client.login(process.env.TOKEN)

What im stumpted on is how to calculate the distance between the locations and the inputted location heres my config.json.

{
  "prefix": "!",
  "spawnPoints": {
    "Oceania Spawn": "16801, 2761",
    "Antartica Spawn": "8178, 8661",
    "Europe Spawn": "-386, -4782",
    "Asia Spawn": "12808, -3192",
    "Africa Spawn": "2420, 3738",
    "North America Spawn": "-10288, -4852",
    "South America Spawn": "-6487, 1360",
    "Soviet Nexus": "16507,-6595",
    "Ryvendor Warp-Pad": "9640,-2390",
    "Gulag Warp-Pad": "11741,-4596",
    "Soviet-Serbia Base Warp-Pad": "-10137,-5374",
    "KGB HQ Warp-Pad": "12958,-5627",
  },
}

Thanks in advance!

Use the distance formula, and make it into a function.

For example, here is my interpretation:

import math

def distanceFormula(x1,y1,x2,y2):
  distance = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
  return distance

In the case that it is a 3 dimensional space, with z, do the same thing, except add another z1 and z2, like so:

import math

def distanceFormula(x1,y1,x2,y2, z1,z2):
  distance = math.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2)
  return distance

Or for a generalized N-dimensional space, you could pass two lists or tuples containing N values and get the distance between them with:

import math

def distanceFormula(p1, p2):
  distance = math.sqrt(sum((x - y)**2 for x, y in zip(p1, p2)))
  return distance

If you want to use modules, then do:

import numpy as np

point_a = np.array((x,y,z))
point_b = np.array((x2,y2,z2))

print(np.linalg.norm(point_a - point_b))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM