Skip to content

Ai Warzone #1320

@Rosachelrazafindrakoto-cmyk

Description

#!/usr/bin/env python3

Warzone AI Bot - Version Plug & Play

Installation: pip install numpy opencv-python mss keyboard pydirectinput vgamepad

import cv2
import numpy as np
import mss
import time
import json
import threading
import keyboard
import pydirectinput
import vgamepad as vg
import os
from collections import deque
import random
import win32gui
import win32con

============================== CONFIGURATION ==============================

CONFIG = {
# Capture écran
"screen_region": (0, 0, 1920, 1080), # Région à capturer
"fps": 60, # FPS cible
"show_preview": True, # Afficher la fenêtre de preview

# Détection
"enemy_color_lower": [100, 100, 50],  # BGR min pour ennemis
"enemy_color_upper": [140, 255, 255], # BGR max pour ennemis
"min_contour_area": 100,              # Taille min des contours
"detection_confidence": 0.7,          # Confiance min

# Aim Assist
"aim_smoothness": 0.85,               # Lissage de la visée (0-1)
"aim_speed": 1.2,                     # Vitesse de visée
"aim_fov": 300,                       # Champ de vision (pixels)
"auto_shoot": True,                   # Tir automatique
"shoot_delay": 0.1,                   # Délai entre les tirs

# Mouvement
"movement_patterns": [
    {"key": "w", "duration": 2.0, "pause": 0.5},
    {"key": "a", "duration": 1.0, "pause": 0.3},
    {"key": "d", "duration": 1.0, "pause": 0.3},
    {"key": "ctrl", "duration": 0.5, "pause": 1.0},
    {"key": "space", "duration": 0.1, "pause": 0.5}
],
"random_movement": True,              # Mouvement aléatoire

# Contrôleur DS4
"use_ds4": True,                      # Utiliser contrôleur virtuel
"controller_sensitivity": 0.8,        # Sensibilité du stick

# Sécurité
"random_delays": True,                # Ajouter des délais aléatoires
"human_like": True,                   # Comportement humain
"max_play_time": 1800,                # Temps max (30 min)

# Touches
"toggle_key": "f8",                   # Activer/Désactiver
"exit_key": "f12"                     # Quitter

}

============================== CLASSE PRINCIPALE ==============================

class WarzoneAIBot:
def init(self):
print("""
╔══════════════════════════════════════╗
║ WARZONE AI BOT - DS4 MODE ║
║ ║
║ Contrôles: ║
║ F8 = Activer/Désactiver ║
║ F12 = Quitter ║
║ ║
║ Status: [ARRÊTÉ] ║
╚══════════════════════════════════════╝
""")

    # États
    self.running = False
    self.enabled = False
    self.last_target = None
    
    # Initialiser capture d'écran
    self.sct = mss.mss()
    self.monitor = {
        "top": CONFIG["screen_region"][1],
        "left": CONFIG["screen_region"][0],
        "width": CONFIG["screen_region"][2],
        "height": CONFIG["screen_region"][3]
    }
    
    # Initialiser contrôleur DS4
    self.controller = None
    if CONFIG["use_ds4"]:
        self._init_controller()
    
    # Historiques pour lissage
    self.aim_history = deque(maxlen=5)
    self.detection_history = deque(maxlen=10)
    
    # Threads
    self.main_thread = None
    self.input_thread = None
    
    # Statistiques
    self.stats = {
        "detections": 0,
        "shots_fired": 0,
        "running_time": 0,
        "targets_locked": 0
    }
    
    # Trouver la fenêtre Warzone
    self.game_window = self._find_game_window()
    
    print("[✓] AI initialisée. Appuyez sur F8 pour commencer.")

def _find_game_window(self):
    """Trouver la fenêtre de Warzone"""
    def callback(hwnd, windows):
        if win32gui.IsWindowVisible(hwnd):
            title = win32gui.GetWindowText(hwnd)
            if "Call of Duty" in title or "Warzone" in title:
                windows.append(hwnd)
    
    windows = []
    win32gui.EnumWindows(callback, windows)
    
    if windows:
        print(f"[✓] Fenêtre Warzone trouvée: {win32gui.GetWindowText(windows[0])}")
        return windows[0]
    
    print("[!] Fenêtre Warzone non trouvée, utilisation de la capture plein écran")
    return None

def _init_controller(self):
    """Initialiser le contrôleur DS4 virtuel"""
    try:
        self.controller = vg.VDS4Gamepad()
        print("[✓] Contrôleur DS4 virtuel initialisé")
    except Exception as e:
        print(f"[!] Erreur contrôleur: {e}. Utilisation souris/clavier.")
        CONFIG["use_ds4"] = False

def start(self):
    """Démarrer le bot"""
    if self.running:
        return
    
    self.running = True
    
    # Focus sur la fenêtre du jeu
    if self.game_window:
        try:
            win32gui.ShowWindow(self.game_window, win32con.SW_RESTORE)
            win32gui.SetForegroundWindow(self.game_window)
            time.sleep(0.5)
        except:
            pass
    
    # Démarrer les threads
    self.main_thread = threading.Thread(target=self._main_loop)
    self.input_thread = threading.Thread(target=self._input_handler)
    
    self.main_thread.start()
    self.input_thread.start()
    
    print("[✓] Bot démarré. Appuyez sur F8 pour activer/désactiver.")

def stop(self):
    """Arrêter le bot"""
    self.running = False
    self.enabled = False
    
    # Relâcher tous les inputs
    self._release_all_inputs()
    
    if self.main_thread:
        self.main_thread.join(timeout=2)
    if self.input_thread:
        self.input_thread.join(timeout=2)
    
    print("[✓] Bot arrêté.")
    print(f"\n=== STATISTIQUES ===")
    print(f"Détections: {self.stats['detections']}")
    print(f"Tirs: {self.stats['shots_fired']}")
    print(f"Cibles verrouillées: {self.stats['targets_locked']}")
    print(f"Temps: {self.stats['running_time']}s")

def _main_loop(self):
    """Boucle principale"""
    last_time = time.time()
    frame_count = 0
    
    while self.running:
        try:
            # Capture d'écran
            frame = self._capture_screen()
            if frame is None:
                time.sleep(0.01)
                continue
            
            # Détection si activé
            if self.enabled:
                targets = self._detect_enemies(frame)
                
                if targets:
                    self._process_targets(targets, frame)
                
                # Mouvement aléatoire
                if CONFIG["random_movement"] and random.random() < 0.01:
                    self._random_movement()
            
            # Affichage preview
            if CONFIG["show_preview"]:
                self._show_preview(frame)
            
            # Contrôle FPS
            frame_count += 1
            if frame_count % 60 == 0:
                current_time = time.time()
                fps = 60 / (current_time - last_time)
                last_time = current_time
                if frame_count % 300 == 0:
                    print(f"[INFO] FPS: {fps:.1f} | Activé: {self.enabled}")
            
            # Petit délai
            time.sleep(1 / CONFIG["fps"])
            
        except Exception as e:
            print(f"[ERREUR] {e}")
            time.sleep(1)

def _capture_screen(self):
    """Capturer l'écran"""
    try:
        screenshot = self.sct.grab(self.monitor)
        frame = np.array(screenshot)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
        return frame
    except:
        return None

def _detect_enemies(self, frame):
    """Détecter les ennemis par couleur"""
    try:
        # Convertir en HSV pour meilleure détection
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        
        # Créer un masque pour les couleurs d'ennemis
        lower = np.array(CONFIG["enemy_color_lower"])
        upper = np.array(CONFIG["enemy_color_upper"])
        mask = cv2.inRange(hsv, lower, upper)
        
        # Nettoyer le masque
        kernel = np.ones((3,3), np.uint8)
        mask = cv2.erode(mask, kernel, iterations=1)
        mask = cv2.dilate(mask, kernel, iterations=2)
        
        # Trouver les contours
        contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        targets = []
        for contour in contours:
            area = cv2.contourArea(contour)
            if area > CONFIG["min_contour_area"]:
                # Calculer le centre
                M = cv2.moments(contour)
                if M["m00"] != 0:
                    cX = int(M["m10"] / M["m00"])
                    cY = int(M["m01"] / M["m00"])
                    
                    # Vérifier si dans le FOV
                    screen_center_x = frame.shape[1] // 2
                    screen_center_y = frame.shape[0] // 2
                    distance = np.sqrt((cX - screen_center_x)**2 + (cY - screen_center_y)**2)
                    
                    if distance < CONFIG["aim_fov"]:
                        targets.append({
                            "x": cX,
                            "y": cY,
                            "area": area,
                            "distance": distance
                        })
        
        self.stats["detections"] += len(targets)
        return targets
        
    except Exception as e:
        print(f"[DETECTION] Erreur: {e}")
        return []

def _process_targets(self, targets, frame):
    """Traiter les cibles détectées"""
    if not targets:
        return
    
    # Trier par distance au centre
    screen_center_x = frame.shape[1] // 2
    screen_center_y = frame.shape[0] // 2
    
    closest_target = min(targets, key=lambda t: t["distance"])
    
    # Calculer le décalage
    offset_x = closest_target["x"] - screen_center_x
    offset_y = closest_target["y"] - screen_center_y
    
    # Appliquer un lissage
    self.aim_history.append((offset_x, offset_y))
    
    # Moyenne sur l'historique
    if len(self.aim_history) > 0:
        avg_x = sum(h[0] for h in self.aim_history) / len(self.aim_history)
        avg_y = sum(h[1] for h in self.aim_history) / len(self.aim_history)
        
        # Appliquer le lissage configuré
        smoothed_x = avg_x * CONFIG["aim_smoothness"]
        smoothed_y = avg_y * CONFIG["aim_smoothness"]
        
        # Convertir en mouvement de contrôleur ou souris
        self._aim_at(smoothed_x, smoothed_y)
        
        # Tir automatique
        if CONFIG["auto_shoot"] and abs(smoothed_x) < 50 and abs(smoothed_y) < 50:
            self._shoot()
        
        self.stats["targets_locked"] += 1
        self.last_target = closest_target

def _aim_at(self, offset_x, offset_y):
    """Visée vers la cible"""
    try:
        # Normaliser l'offset
        norm_x = offset_x / (CONFIG["screen_region"][2] / 2)
        norm_y = offset_y / (CONFIG["screen_region"][3] / 2)
        
        # Appliquer sensibilité
        norm_x = max(-1.0, min(1.0, norm_x * CONFIG["aim_speed"]))
        norm_y = max(-1.0, min(1.0, norm_y * CONFIG["aim_speed"]))
        
        if CONFIG["use_ds4"] and self.controller:
            # Utiliser contrôleur DS4
            self.controller.right_joystick_float(
                x_value_float=norm_x,
                y_value_float=norm_y
            )
            self.controller.update()
        else:
            # Utiliser souris (fallback)
            mouse_x = norm_x * 10
            mouse_y = norm_y * 10
            
            if abs(mouse_x) > 1 or abs(mouse_y) > 1:
                pydirectinput.moveRel(int(mouse_x), int(mouse_y), relative=True)
        
    except Exception as e:
        print(f"[AIM] Erreur: {e}")

def _shoot(self):
    """Tirer"""
    try:
        if CONFIG["use_ds4"] and self.controller:
            # Gâchette droite du DS4
            self.controller.right_trigger_float(1.0)
            self.controller.update()
            
            # Relâcher après délai
            threading.Timer(CONFIG["shoot_delay"], self._release_trigger).start()
        else:
            # Clic souris
            pydirectinput.mouseDown(button='left')
            time.sleep(0.05)
            pydirectinput.mouseUp(button='left')
        
        self.stats["shots_fired"] += 1
        
    except Exception as e:
        print(f"[SHOOT] Erreur: {e}")

def _release_trigger(self):
    """Relâcher la gâchette"""
    if CONFIG["use_ds4"] and self.controller:
        self.controller.right_trigger_float(0.0)
        self.controller.update()

def _random_movement(self):
    """Mouvement aléatoire"""
    try:
        pattern = random.choice(CONFIG["movement_patterns"])
        
        if CONFIG["use_ds4"] and self.controller:
            # Stick gauche pour mouvement
            if pattern["key"] == "w":
                self.controller.left_joystick_float(0.0, 1.0)
            elif pattern["key"] == "s":
                self.controller.left_joystick_float(0.0, -1.0)
            elif pattern["key"] == "a":
                self.controller.left_joystick_float(-1.0, 0.0)
            elif pattern["key"] == "d":
                self.controller.left_joystick_float(1.0, 0.0)
            elif pattern["key"] == "ctrl":
                self.controller.press_button(vg.DS4_BUTTONS.DS4_BUTTON_THUMB_LEFT)
            elif pattern["key"] == "space":
                self.controller.press_button(vg.DS4_BUTTONS.DS4_BUTTON_CROSS)
            
            self.controller.update()
            
            # Relâcher après durée
            threading.Timer(pattern["duration"], self._reset_movement).start()
            
        else:
            # Clavier pour mouvement
            pydirectinput.keyDown(pattern["key"])
            time.sleep(pattern["duration"])
            pydirectinput.keyUp(pattern["key"])
        
        # Pause configurée
        if CONFIG["random_delays"]:
            time.sleep(pattern["pause"] + random.uniform(0, 0.3))
            
    except Exception as e:
        print(f"[MOVE] Erreur: {e}")

def _reset_movement(self):
    """Réinitialiser le mouvement"""
    if CONFIG["use_ds4"] and self.controller:
        self.controller.left_joystick_float(0.0, 0.0)
        self.controller.release_button(vg.DS4_BUTTONS.DS4_BUTTON_THUMB_LEFT)
        self.controller.release_button(vg.DS4_BUTTONS.DS4_BUTTON_CROSS)
        self.controller.update()

def _release_all_inputs(self):
    """Relâcher tous les inputs"""
    try:
        if CONFIG["use_ds4"] and self.controller:
            # Réinitialiser contrôleur
            self.controller.reset()
            self.controller.update()
        else:
            # Relâcher touches clavier
            for key in ['w', 'a', 's', 'd', 'ctrl', 'space', 'shift']:
                pydirectinput.keyUp(key)
            # Relâcher souris
            pydirectinput.mouseUp(button='left')
            pydirectinput.mouseUp(button='right')
    except:
        pass

def _show_preview(self, frame):
    """Afficher la fenêtre de preview"""
    try:
        # Ajouter des informations
        info_text = f"AI: {'ON' if self.enabled else 'OFF'} | Targets: {self.stats['detections']}"
        cv2.putText(frame, info_text, (10, 30), 
                   cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
        
        # Dessiner le FOV
        center_x, center_y = frame.shape[1] // 2, frame.shape[0] // 2
        cv2.circle(frame, (center_x, center_y), 
                  CONFIG["aim_fov"], (0, 255, 255), 2)
        cv2.circle(frame, (center_x, center_y), 
                  5, (0, 0, 255), -1)
        
        # Afficher
        cv2.imshow('Warzone AI Preview', frame)
        cv2.waitKey(1)
        
    except Exception as e:
        pass

def _input_handler(self):
    """Gérer les inputs clavier"""
    while self.running:
        try:
            # Toggle AI
            if keyboard.is_pressed(CONFIG["toggle_key"]):
                self.enabled = not self.enabled
                status = "ACTIVÉ" if self.enabled else "DÉSACTIVÉ"
                print(f"\n[STATUS] AI {status}")
                time.sleep(0.5)  # Anti-rebond
            
            # Quitter
            if keyboard.is_pressed(CONFIG["exit_key"]):
                print("\n[INFO] Arrêt demandé...")
                self.running = False
                break
            
            time.sleep(0.1)
            
        except Exception as e:
            print(f"[INPUT] Erreur: {e}")
            time.sleep(1)

============================== INSTALLATION AUTOMATIQUE ==============================

def install_dependencies():
"""Installer automatiquement les dépendances"""
import subprocess
import sys

print("\n[INSTALLATION] Vérification des dépendances...")

required = [
    "numpy",
    "opencv-python",
    "mss",
    "keyboard",
    "pydirectinput",
    "vgamepad",
    "pywin32"
]

for package in required:
    try:
        __import__(package.replace('-', '_'))
        print(f"  [✓] {package}")
    except ImportError:
        print(f"  [ ] Installation de {package}...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        print(f"  [✓] {package} installé")

print("\n[✓] Toutes les dépendances sont installées!")

============================== SCRIPT BAT ==============================

def create_bat_file():
"""Créer le fichier .bat pour lancer facilement"""
bat_content = """@echo off
chcp 65001 > nul
title Warzone AI Bot - DS4 Version

echo =========================================
echo WARZONE AI BOT - AUTOMATIQUE
echo =========================================
echo.

REM Vérifier Python
python --version >nul 2>&1
if errorlevel 1 (
echo [ERREUR] Python non installé!
echo Téléchargez Python 3.8+ : https://python.org
pause
exit
)

REM Vérifier les droits admin
net session >nul 2>&1
if %errorLevel% neq 0 (
echo [AVERTISSEMENT] Lancez en administrateur pour de meilleures performances
echo.
)

REM Installer dépendances
echo [INFO] Installation des dépendances...
pip install numpy opencv-python mss keyboard pydirectinput vgamepad pywin32 --quiet

REM Lancer l'AI
echo [INFO] Lancement du bot Warzone AI...
echo.
echo [CONTROLES]
echo F8 = Activer/Desactiver l'AI
echo F12 = Quitter
echo.
echo [CONFIGURATION]
echo Ajustez les couleurs dans CONFIG si besoin
echo Placez Warzone en plein ecran fenetre
echo.

python "%~dp0warzone_ai.py"

if errorlevel 1 (
echo.
echo [ERREUR] Le programme a rencontre une erreur
pause
)

exit
"""

with open("launch_ai.bat", "w", encoding="utf-8") as f:
    f.write(bat_content)

print("[✓] Fichier 'launch_ai.bat' créé")
print("[INFO] Double-cliquez sur 'launch_ai.bat' pour lancer l'AI")

============================== GUIDE UTILISATEUR ==============================

def show_guide():
"""Afficher le guide d'utilisation"""
print("""
========================================
GUIDE D'UTILISATION - WARZONE AI BOT
========================================

1. INSTALLATION:
   - Exécutez ce script une fois pour installer les dépendances
   - Un fichier 'launch_ai.bat' sera créé

2. CONFIGURATION WARZONE:
   - Lancez Warzone en mode "Plein écran fenêtré"
   - Résolution recommandée: 1920x1080
   - Assurez-vous que DS4Windows est installé (optionnel)

3. LANCEMENT:
   - Double-cliquez sur 'launch_ai.bat'
   - Acceptez les permissions admin si demandé

4. CALIBRATION:
   - L'AI va détecter automatiquement Warzone
   - Ajustez CONFIG['enemy_color_lower/upper'] si besoin
     * Appuyez sur F8 pour activer/désactiver l'AI
     * Utilisez la fenêtre preview pour voir la détection

5. OPTIMISATION:
   - Pour meilleure détection, ajustez les couleurs:
     * enemy_color_lower: [B_min, G_min, R_min]
     * enemy_color_upper: [B_max, G_max, R_max]
   - Augmentez aim_smoothness pour visée plus fluide
   - Réduisez aim_speed pour plus de précision

6. SÉCURITÉ:
   - Utilisez sur un compte secondaire
   - Limitez les sessions à 30 minutes
   - Variez votre gameplay

========================================
CONFIGURATION ACTUELLE:
""")

for key, value in CONFIG.items():
    print(f"    {key}: {value}")

print("\n    Appuyez sur ENTREE pour commencer...")
input()

============================== POINT D'ENTRÉE ==============================

if name == "main":
import sys

print("Warzone AI Bot - Version Plug & Play")
print("====================================\n")

# Demander l'installation
response = input("Voulez-vous installer les dépendances automatiquement? (o/n): ")
if response.lower() in ['o', 'oui', 'y', 'yes']:
    install_dependencies()

# Créer le fichier .bat
create_bat_file()

# Afficher le guide
show_guide()

# Lancer l'AI
try:
    bot = WarzoneAIBot()
    bot.start()
    
    # Garder le programme actif
    while bot.running:
        time.sleep(1)
        bot.stats["running_time"] += 1
        
        # Arrêt automatique après temps max
        if bot.stats["running_time"] >= CONFIG["max_play_time"]:
            print(f"\n[INFO] Temps max atteint ({CONFIG['max_play_time']}s)")
            bot.stop()
            break
    
    # Nettoyage
    cv2.destroyAllWindows()
    print("\n[✓] Programme terminé proprement")
    
except KeyboardInterrupt:
    print("\n[INFO] Arrêt par l'utilisateur (Ctrl+C)")
    if 'bot' in locals():
        bot.stop()

except Exception as e:
    print(f"\n[ERREUR CRITIQUE] {e}")
    import traceback
    traceback.print_exc()
    print("\n[INFO] Redémarrez le programme")

finally:
    # Attendre avant de fermer
    time.sleep(2)
    input("\nAppuyez sur ENTREE pour quitter...")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions