簡體   English   中英

如何計算一組 x、y 坐標和位置變量之間的距離?

[英]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經線位置


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

進入節點,這是我到目前為止所擁有的:

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)

我難過的是如何計算位置和輸入位置之間的距離,這是我的 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",
  },
}

提前致謝!

使用距離公式,將其變為 function。

例如,這是我的解釋:

import math

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

在它是一個 3 維空間的情況下,使用 z,做同樣的事情,除了添加另一個 z1 和 z2,如下所示:

import math

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

或者對於廣義的 N 維空間,您可以傳遞兩個包含 N 個值的列表或元組,並通過以下方式獲取它們之間的距離:

import math

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

如果要使用模塊,請執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM