def set_pos(x, y):
if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'):
x = int(x - (Wd / 2))
y = int(y - (Hd / 2))
code
extra = ctypes.c_ulong(0)
ii = pynput._util.win32.INPUT_union()
ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p))
command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii)
SendInput(1, ctypes.pointer(command), ctypes.sizeof(command))
if name == "main":
print("Do not run this file directly.")
Assistant
User
é possivel implementar detecção automatica de arma?
Assistant
User
faz o seguinte apenas implemente o recoil da 301 como padrao no meu codigo e me entregue o codigo completo com as alteraçãoes
Assistant
def start(ENABLE_AIMBOT):
code
# Config
#YOLO_DIRECTORY = "models"
CONFIDENCE = 0.20 #Reduzir CONFIDENCE permitirá que o modelo detecte mais objetos, mas pode aumentar os falsos positivos:
THRESHOLD = 0.01
#THRESHOLD = 0.22 Estava usando esete antes de 0.01
# Config
YOLO_DIRECTORY = "models"
#CONFIDENCE = 0.25 #Reduzir CONFIDENCE permitirá que o modelo detecte mais objetos, mas pode aumentar os falsos positivos:
#THRESHOLD = 0.05
#THRESHOLD = 0.22 Estava usando esete antes de 0.01
#
# Size (in pixels) of the screen capture box to feed the neural net.
# This box is in the center of your screen. Lower value makes the network faster.
#
# Example: "ACTIVATION_RANGE = 400" means a 400x400 pixel box.
#
ACTIVATION_RANGE = 200
# load the COCO class labels our YOLO model was trained on
labelsPath = os.path.sep.join([YOLO_DIRECTORY, "obj.names"])
LABELS = open(labelsPath).read().strip().split("\n")
# initialize a list of colors to represent each possible class label
np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),
dtype="uint8")
# derive the paths to the YOLO weights and model configuration
weightsPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4-tiny-obj_final.weights"])
configPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4-tiny-obj.cfg"])
# Wait for buffering
time.sleep(0.4)
# load our YOLO object detector trained on COCO dataset (80 classes)
# and determine only the output layer names that we need from YOLO
print("[INFO] loading neural-network from disk…")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
# Check if GPU is available and use it
if cv2.cuda.getCudaEnabledDeviceCount() > 0:
print(colored("[OKAY] CUDA GPU Detected!", "green"))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
elif cv2.ocl.haveOpenCL():
print(colored("[OKAY] OpenCL GPU Detected!", "green"))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL)
else:
print(colored("[WARNING] No GPU detected, using CPU.", "yellow"))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
ln = net.getLayerNames()
ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()]
# Define screen capture area
print("[INFO] loading screencapture device…")
W, H = None, None
origbox = (int(Wd/2 - ACTIVATION_RANGE/2),
int(Hd/2 - ACTIVATION_RANGE/2),
int(Wd/2 + ACTIVATION_RANGE/2),
int(Hd/2 + ACTIVATION_RANGE/2))
# Log whether aimbot is enabled
if not ENABLE_AIMBOT:
print("[INFO] aimbot disabled, using visualizer only…")
else:
print(colored("[OKAY] Aimbot enabled!", "green"))
# Handle Ctrl+C in terminal, release pointers
def signal_handler(sig, frame):
# release the file pointers
print("\n[INFO] cleaning up…")
sct.close() # .exit() does not exist for mss.mss()
cv2.destroyAllWindows()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print()
# loop over frames from the video file stream
while True:
start_time = timeit.default_timer()
frame = np.array(grab_screen(region=origbox))
frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR)
# if the frame dimensions are empty, grab them
if W is None or H is None:
(H, W) = frame.shape[: 2]
frame = cv2.UMat(frame)
# construct a blob from the input frame and then perform a forward
# pass of the YOLO object detector, giving us our bounding boxes
# and associated probabilities
blob = cv2.dnn.blobFromImage(frame, 1/260, (150, 150),
swapRB=True, crop=True)
net.setInput(blob)
layerOutputs = net.forward(ln)
# initialize our lists of detected bounding boxes, confidences,
# and class IDs, respectively
boxes = []
confidences = []
classIDs = []
# loop over each of the layer outputs
for output in layerOutputs:
# loop over each of the detections
for detection in output:
# extract the class ID and confidence (i.e., probability)
# of the current object detection
scores = detection[5:]
classID = 0 # person = 0
confidence = scores[classID]
# filter out weak predictions by ensuring the detected
# probability is greater than the minimum probability
if confidence > CONFIDENCE:
box = detection[0: 4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
# use the center (x, y)-coordinates to derive the top
# and and left corner of the bounding box
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
# update our list of bounding box coordinates,
# confidences, and class IDs
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
# apply non-maxima suppression to suppress weak, overlapping
# bounding boxes
idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD)
# ensure at least one detection exists
if len(idxs) > 0:
# Find best player match
bestMatch = confidences[np.argmax(confidences)]
# loop over the indexes we are keeping
for i in idxs.flatten():
# extract the bounding box coordinates
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
# draw target dot on the frame
cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1)
# draw a bounding box rectangle and label on the frame
cv2.rectangle(frame, (x, y),
(x + w, y + h), (0, 255, 0), 1)
text = "enemy {}%".format(int(confidences[i] * 100))
cv2.putText(frame, text, (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
if ENABLE_AIMBOT and bestMatch == confidences[i]:
mouseX = origbox[0] + (x + w/1.55)
mouseY = origbox[1] + (y + h/2.50)
set_pos(mouseX, mouseY)
cv2.imshow("Neural Net Vision (Pine)", frame)
elapsed = timeit.default_timer() - start_time
sys.stdout.write(
"\r{1} FPS with {0} MS interpolation delay \t".format(int(elapsed*1000), int(1/elapsed)))
sys.stdout.flush()
if cv2.waitKey(1) & 0xFF == ord('0'):
break
# Clean up on exit
signal_handler(0, 0)
Para adicionar o controle de recoil das armas no seu código, você pode definir os padrões de recoil para cada arma mencionada e depois ajustar a posição do mouse de acordo. Aqui está uma implementação básica na qual cada arma tem um padrão de recoil associado.
Primeiro, vamos adicionar um dicionário com os padrões de recoil para cada arma. Depois, vamos ajustar a função set_pos para aplicar esses padrões de recoil.
Esses são padrões simplificados apenas para ilustração. Você pode ajustá-los de acordo com os padrões reais.
Vamos definir uma variável global para controlar a arma atual:
python
current_weapon = "R-301" # Defina a arma padrão
Agora, vamos modificar a função set_pos para usar o padrão de recoil:
python
import itertools
def set_pos(x, y):
if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'):
x = int(x - (Wd / 2))
y = int(y - (Hd / 2))
recoil_pattern = RECOIL_PATTERNS.get(current_weapon, [(0, 0)])
# Cycling through the patterns
recoil_cycle = itertools.cycle(recoil_pattern)
dx, dy = next(recoil_cycle)
x += dx
y += dy
extra = ctypes.c_ulong(0)
ii = pynput._util.win32.INPUT_union()
ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p))
command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii)
SendInput(1, ctypes.pointer(command), ctypes.sizeof(command))
Não esqueça de adicionar o controle de entrada do usuário para mudar a arma atual:
python
def switch_weapon(weapon):
global current_weapon
if weapon in RECOIL_PATTERNS:
current_weapon = weapon
print(f"Switched to {weapon}")
# Exemplo de uso:
keyboard.add_hotkey('1', lambda: switch_weapon("R-99"))
keyboard.add_hotkey('2', lambda: switch_weapon("R-301"))
keyboard.add_hotkey('3', lambda: switch_weapon("Hemlok"))
keyboard.add_hotkey('4', lambda: switch_weapon("Flatline"))
keyboard.add_hotkey('5', lambda: switch_weapon("Volt"))
Para resumir, adicione o dicionário RECOIL_PATTERNS, crie uma função para trocar a arma atual e modifique set_pos para aplicar o padrão de recoil. Certifique-se de que os hotkeys estejam configurados corretamente para mudar a arma durante a execução.
Sim, é possível implementar a detecção automática de armas em jogos como Apex Legends usando técnicas de visão computacional. Esse processo geralmente envolve a captura de uma região específica da tela onde as armas são exibidas (por exemplo, o HUD que mostra a arma atual) e o uso de algoritmos de reconhecimento de imagem para identificar a arma.
Passo a Passo para Implementação
Captura da Tela:
Capture a região da tela onde a arma atual é exibida.
Preprocessamento da Imagem:
Realize operações como redimensionamento, conversão para escala de cinza ou outros processos de pré-processamento para facilitar a detecção.
Reconhecimento da Arma:
Você pode usar técnicas de aprendizado de máquina, como modelos pretreinados ou uma rede neural personalizada, para identificar a arma com base na imagem capturada.
Exemplos de Código
Vamos implementar um exemplo básico que usa uma captura de tela de uma área específica para reconhecimento de arma. Como isso é um exemplo simplificado, você pode precisar ajustá-lo conforme necessário para seu jogo específico.
Captura da Região da Tela
Vamos ajustar a captura de tela para uma área onde a arma é exibida. Por simplicidade, vamos supor que a região é fixa e conhecida:
Vamos usar um modelo de aprendizado de máquina simplificado para reconhecer a arma. Para um exemplo simples, podemos usar reconhecimento de característica como ORB/SIFT ou um modelo de classificação pretreinado como um classificador SVM.
Aqui vamos usar o ORB (Oriented FAST and Rotated BRIEF) para reconhecimento de característica. Primeiro, capture e armazene amostras de sua arma para treinamento do modelo:
python
import cv2
import numpy as np
# Capture as amostras de cada arma
weapon_samples = {
"R-99": preprocess_image(cv2.imread("samples/R-99.png")),
"R-301": preprocess_image(cv2.imread("samples/R-301.png")),
"Hemlok": preprocess_image(cv2.imread("samples/Hemlok.png")),
"Flatline": preprocess_image(cv2.imread("samples/Flatline.png")),
"Volt": preprocess_image(cv2.imread("samples/Volt.png"))
}
# Inicialize ORB detector
orb = cv2.ORB_create()
Função para Detectar Arma
Vamos definir uma função que usa o ORB para detectar a arma atual:
No seu while True: principal, capture a região da arma, pré-processe, e detecte a arma:
python
current_weapon = "R-301" # Defina a arma padrão
while True:
# Capture a região da arma
weapon_region = capture_weapon_region()
preprocessed_image = preprocess_image(weapon_region)
detected_weapon = detect_weapon(preprocessed_image, weapon_samples)
if detected_weapon:
current_weapon = detected_weapon
print(f"Detected Weapon: {current_weapon}")
# o resto do código
Este código básico captura a região da arma, pré-processa a imagem, detecta a arma e atualiza a variável current_weapon. Dependendo das suas necessidades, você pode precisar ajustar os parâmetros ou usar técnicas mais avançadas de reconhecimento de imagem para melhorar a precisão e a eficiência.
Entendido. Para adicionar o controle de recoil apenas para a R-301 como padrão, precisamos definir o padrão de recoil para a R-301 e modificar a função set_pos para utilizar esse padrão.
Vou incorporar as modificações necessárias ao seu código.
Código Completo com Controle de Recoil para R-301
python
import numpy as np
from termcolor import colored
import timeit
import threading
import imutils
import time
import mss
import cv2
import os
import signal
import sys
import pynput
import ctypes
import pyautogui
from lib.grab import grab_screen
import win32gui
import win32api
import win32con
import mouse
import keyboard
import itertools
sct = mss.mss()
Wd, Hd = sct.monitors[1]["width"], sct.monitors[1]["height"]
SendInput = ctypes.windll.user32.SendInput
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
fields = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
fields = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
fields = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
fields = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
fields = [("type", ctypes.c_ulong),
("ii", Input_I)]
def set_pos(x, y):
if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'):
x = int(x - (Wd / 2))
y = int(y - (Hd / 2))
# Recoil pattern for R-301
RECOIL_PATTERN = [(0, -1), (0, -1), (0, -1), (1, -1), (1, -1), (1, -1)]
recoil_cycle = itertools.cycle(RECOIL_PATTERN)
dx, dy = next(recoil_cycle)
x += dx
y += dy
extra = ctypes.c_ulong(0)
ii = pynput._util.win32.INPUT_union()
ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p))
command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii)
SendInput(1, ctypes.pointer(command), ctypes.sizeof(command))
if __name__ == "__main__":
print("Do not run this file directly.")
def start(ENABLE_AIMBOT):
# Config
CONFIDENCE = 0.20
THRESHOLD = 0.01
YOLO_DIRECTORY = "models"
ACTIVATION_RANGE = 200
# load the COCO class labels our YOLO model was trained on
labelsPath = os.path.sep.join([YOLO_DIRECTORY, "obj.names"])
LABELS = open(labelsPath).read().strip().split("\n")
# initialize a list of colors to represent each possible class label
np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),
dtype="uint8")
# derive the paths to the YOLO weights and model configuration
weightsPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4-tiny-obj_final.weights"])
configPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4-tiny-obj.cfg"])
# Wait for buffering
time.sleep(0.4)
# load our YOLO object detector trained on COCO dataset (80 classes)
# and determine only the output layer names that we need from YOLO
print("[INFO] loading neural-network from disk…")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
# Check if GPU is available and use it
if cv2.cuda.getCudaEnabledDeviceCount() > 0:
print(colored("[OKAY] CUDA GPU Detected!", "green"))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
elif cv2.ocl.haveOpenCL():
print(colored("[OKAY] OpenCL GPU Detected!", "green"))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL)
else:
print(colored("[WARNING] No GPU detected, using CPU.", "yellow"))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
ln = net.getLayerNames()
ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()]
# Define screen capture area
print("[INFO] loading screencapture device…")
W, H = None, None
origbox = (int(Wd/2 - ACTIVATION_RANGE/2),
int(Hd/2 - ACTIVATION_RANGE/2),
int(Wd/2 + ACTIVATION_RANGE/2),
int(Hd/2 + ACTIVATION_RANGE/2))
# Log whether aimbot is enabled
if not ENABLE_AIMBOT:
print("[INFO] aimbot disabled, using visualizer only…")
else:
print(colored("[OKAY] Aimbot enabled!", "green"))
# Handle Ctrl+C in terminal, release pointers
def signal_handler(sig, frame):
# release the file pointers
print("\n[INFO] cleaning up…")
sct.close() # .exit() does not exist for mss.mss()
cv2.destroyAllWindows()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print()
# loop over frames from the video file stream
while True:
start_time = timeit.default_timer()
frame = np.array(grab_screen(region=origbox))
frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR)
# if the frame dimensions are empty, grab them
if W is None or H is None:
(H, W) = frame.shape[: 2]
frame = cv2.UMat(frame)
# construct a blob from the input frame and then perform a forward
# pass of the YOLO object detector, giving us our bounding boxes
# and associated probabilities
blob = cv2.dnn.blobFromImage(frame, 1/260, (150, 150),
swapRB=True, crop=True)
net.setInput(blob)
layerOutputs = net.forward(ln)
# initialize our lists of detected bounding boxes, confidences,
# and class IDs, respectively
boxes = []
confidences = []
classIDs = []
# loop over each of the layer outputs
for output in layerOutputs:
# loop over each of the detections
for detection in output:
# extract the class ID and confidence (i.e., probability)
# of the current object detection
scores = detection[5:]
classID = 0 # person = 0
confidence = scores[classID]
# filter out weak predictions by ensuring the detected
# probability is greater than the minimum probability
if confidence > CONFIDENCE:
box = detection[0: 4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
# use the center (x, y)-coordinates to derive the top
# and and left corner of the bounding box
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
# update our list of bounding box coordinates,
# confidences, and class IDs
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
# apply non-maxima suppression to suppress weak, overlapping
# bounding boxes
idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD)
# ensure at least one detection exists
if len(idxs) > 0:
# Find best player match
bestMatch = confidences[np.argmax(confidences)]
# loop over the indexes we are keeping
for i in idxs.flatten():
# extract the bounding box coordinates
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
# draw target dot on the frame
cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1)
# draw a bounding box rectangle and label on the frame
cv2.rectangle(frame, (x, y),
(x + w, y + h), (0, 255, 0), 1)
text = "enemy {}%".format(int(confidences[i] * 100))
cv2.putText(frame, text, (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
if ENABLE_AIMBOT and bestMatch == confidences[i]:
mouseX = origbox[0] + (x + w/1.55)
mouseY = origbox[1] + (y + h/2.50)
set_pos(mouseX, mouseY)
cv2.imshow("Neural Net Vision (Pine)", frame)
elapsed = timeit.default_timer() - start_time
sys.stdout.write(
"\r{1} FPS with {0} MS interpolation delay \t".format(int(elapsed*1000), int(1/elapsed)))
sys.stdout.flush()
if cv2.waitKey(1) & 0xFF == ord('0'):
break
# Clean up on exit
signal_handler(0, 0)
O que foi adicionado:
Padrão de Recoil para R-301:
Adicionado um ciclo com o padrão de recoil da R-301 na função set_pos.
Ciclo do Padrão de Recoil:
Utilização do iterador itertools.cycle para iterar continuamente pelo padrão de recoil.
Observação
Esta é uma implementação básica que considera que o jogador está sempre utilizando a R-301. Caso deseje adicionar suporte para múltiplas armas ou detectar automaticamente a arma atual, será necessário expandir esse código com técnicas de visão computacional e potencialmente utilizar mecanismos de treinamento de modelos para uma maior precisão.