make this code clean and better
- User
make this code clean and better
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
make this code clean and better
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, I will review the provided code and suggest improvements for clarity and better practices. Here's a breakdown of potential improvements for each file:
File: ./repos/MK-PUBG-Mobile-Tool/main.py
import ctypes
import sys
from datetime import datetime
from pathlib import Path
from src.ui_functions import Window, QtWidgets
from src.update import UpdateWindow
from PyQt5 import QtCore
from os import environ
APP_NAME = "MK PUBG Mobile Tool"
APP_VERSION = "v1.0.8"
FULL_APP_NAME = f"{APP_NAME} {APP_VERSION}"
ctypes.windll.kernel32.SetConsoleTitleW(FULL_APP_NAME)
def run_application():
"""
Run the main GUI application.
"""
ui = Window(APP_NAME, APP_VERSION)
ui.show()
app.exec_()
if __name__ == "__main__":
print("[#] Starting the GUI app")
def suppress_qt_warnings():
DS = "1.5"
scaleFactor = str(ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100)
if float(scaleFactor) > float(DS):
scaleFactor = DS
environ["QT_DEVICE_PIXEL_RATIO"] = "0"
environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "0"
environ["QT_SCALE_FACTOR"] = "1"
environ["QT_SCREEN_SCALE_FACTORS"] = scaleFactor
suppress_qt_warnings()
if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
try:
app = QtWidgets.QApplication(sys.argv)
update = UpdateWindow()
update.check_for_updates(APP_VERSION)
if update.is_update_available():
update.show()
if app.exec_() == 0:
run_application()
else:
run_application()
except Exception as e:
with open(f"{Path.cwd()}/error.log", "a") as f:
f.write(f"-------------------{datetime.now()}-------------------\n")
f.write(f"CRASH_ERR: {e}\n")
Improvements:
APP_NAME and APP_VERSION at the very top for easy access.suppress_qt_warnings: The purpose of the DS variable and the scaling logic could be more explicitly commented.QtCore.Qt.ApplicationAttribute: Instead of checking for attributes with hasattr, you can directly use the enum values from QtCore.Qt.ApplicationAttribute.except Exception as e, try to catch more specific exceptions where possible (e.g., requests.exceptions.RequestException if the update check fails).logging module for better control over log levels and formatting.Refactored main.py:
import ctypes
import sys
import os
from datetime import datetime
from pathlib import Path
from src.ui_functions import Window, QtWidgets
from src.update import UpdateWindow
from PyQt5 import QtCore
import logging
APP_NAME = "MK PUBG Mobile Tool"
APP_VERSION = "v1.0.8"
FULL_APP_NAME = f"{APP_NAME} {APP_VERSION}"
# Set the console title
ctypes.windll.kernel32.SetConsoleTitleW(FULL_APP_NAME)
def suppress_qt_warnings():
"""Suppresses Qt warnings related to high DPI scaling on Windows."""
DESIRED_SCALE_FACTOR = 1.5 # Target scale factor
current_scale_factor = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100
if current_scale_factor > DESIRED_SCALE_FACTOR:
current_scale_factor = DESIRED_SCALE_FACTOR
os.environ["QT_DEVICE_PIXEL_RATIO"] = "0"
os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "0"
os.environ["QT_SCALE_FACTOR"] = "1"
os.environ["QT_SCREEN_SCALE_FACTORS"] = str(current_scale_factor)
def run_application():
"""Runs the main GUI application."""
ui = Window(APP_NAME, APP_VERSION)
ui.show()
app.exec_()
if __name__ == "__main__":
print("[#] Starting the GUI app")
# Configure basic logging
logging.basicConfig(filename="error.log", level=logging.ERROR,
format="%(asctime)s - %(levelname)s - %(message)s")
suppress_qt_warnings()
QtWidgets.QApplication.setAttribute(QtCore.Qt.ApplicationAttribute.AA_EnableHighDpiScaling, True)
QtWidgets.QApplication.setAttribute(QtCore.Qt.ApplicationAttribute.AA_UseHighDpiPixmaps, True)
try:
app = QtWidgets.QApplication(sys.argv)
update = UpdateWindow()
update.check_for_updates(APP_VERSION)
if update.is_update_available():
update.show()
if app.exec_() == 0: # Only run the main app if the update window was closed normally
run_application()
else:
run_application()
except Exception as e:
logging.exception("A critical error occurred during application startup.")
File: ./repos/MK-PUBG-Mobile-Tool/src/app_functions.py
import os
import shutil
import subprocess
import sys
import winreg
import xml.etree.ElementTree as ET
from shutil import copy
from time import sleep
import GPUtil
import adbutils
import psutil
import pythoncom
import tempfile
import winshell
import wmi
from PyQt5.QtCore import QSettings
from win32api import EnumDisplayDevices, EnumDisplaySettings
from win32com.client import Dispatch
from . import setup_logger
class Settings:
def __init__(self):
self.settings = QSettings("MK Apps", "MK PUBG Mobile Tool")
self.REG_PATH = r'SOFTWARE\Tencent\MobileGamePC'
self.pubg_versions = {
"com.tencent.ig": "PUBG Mobile Global",
"com.vng.pubgmobile": "PUBG Mobile VN",
"com.rekoo.pubgm": "PUBG Mobile TW",
"com.pubg.krmobile": "PUBG Mobile KR",
"com.pubg.imobile": "Battlegrounds Mobile India"}
self.logger = setup_logger('error_logger', 'error.log')
@[Redacted Person]
def kill_adb():
"""
Kills the ADB (Android Debug Bridge) process if it is currently running.
"""
try:
subprocess.run(["taskkill", "/F", "/IM", "adb.exe"], check=True)
return True
except subprocess.CalledProcessError:
return False
# Get Script Run Location
@[Redacted Person]
def resource_path(relative_path):
base_path = getattr(sys, '_MEIPASS', os.path.abspath('.'))
return os.path.join(base_path, relative_path)
class Registry(Settings):
def get_reg(self, name):
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.REG_PATH, 0, winreg.KEY_READ) as registry_key:
value, regtype = winreg.QueryValueEx(registry_key, name)
return value
except FileNotFoundError:
return None
@[Redacted Person]
def get_local_reg(name, path="AppMarket"):
"""
Get the value of a registry key in the local machine.
"""
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
rf'SOFTWARE\WOW6432Node\Tencent\MobileGamePC\{path}') as registry_key:
value, regtype = winreg.QueryValueEx(registry_key, name)
return value
except OSError:
return None
def set_dword(self, name, value):
"""
Set the value of a DWORD in the Windows registry.
"""
try:
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.REG_PATH) as registry_key:
winreg.SetValueEx(registry_key, name, 0, winreg.REG_DWORD, value)
return True
except WindowsError:
return False
class Optimizer(Registry):
def temp_cleaner(self):
"""
Cleans temporary files and directories.
Returns:
bool: True if the function successfully cleans the temporary files and directories.
"""
base_path = getattr(sys, '_MEIPASS', os.path.abspath('.'))
def clear_files(directory):
try:
for root, dirs, files in os.walk(directory):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
shutil.rmtree(os.path.join(root, name))
except Exception:
pass
try:
for folder in os.listdir(tempfile.gettempdir()):
folder_path = os.path.join(tempfile.gettempdir(), folder)
if folder_path != base_path:
if os.path.isdir(folder_path):
shutil.rmtree(folder_path, ignore_errors=True)
else:
try:
os.remove(folder_path)
except Exception:
pass
except Exception:
pass
clear_files(r"C:\Windows\Temp")
clear_files(os.path.expandvars(r'%windir%\Prefetch'))
gameloop_ui_path = self.get_local_reg('InstallPath', path='UI')
clear_files(os.path.join(gameloop_ui_path, 'ShaderCache'))
return True
def gameloop_settings(self):
"""
Generates the game loop settings based on the system's hardware specifications.
"""
def make_scale(value, low=False):
for version_key in self.pubg_versions.keys():
content_scale_key = f"{version_key}_ContentScale"
render_quality_key = f"{version_key}_RenderQuality"
fps_level_key = f"{version_key}_FPSLevel"
reg_content_scale = self.get_reg(content_scale_key)
if reg_content_scale is not None:
self.set_dword(content_scale_key, value)
reg_fps_level = self.get_reg(fps_level_key)
if reg_fps_level is not None:
self.set_dword(fps_level_key, 0)
reg_render_quality = self.get_reg(render_quality_key)
if reg_render_quality is not None:
render_value = value
if low:
# value = 0
render_value = 2
[Redacted Person] value == 1:
render_value = 2
self.set_dword(render_quality_key, render_value)
ram_value = round((int(75) * psutil.virtual_memory().total / (1024 ** 3)) / 100) * 1024
ram_value = min(ram_value, (8 * 1024))
cpu_value = round((int(75) * psutil.cpu_count(logical=False)) / 100)
cpu_value = min(cpu_value, 8)
dc = EnumDisplayDevices(None, 0, 0)
settings = EnumDisplaySettings(dc.DeviceName, -1)
refresh_rate = settings.DisplayFrequency
self.set_dword("VSyncEnabled", 1 if refresh_rate < 89 else 0)
gpu = GPUtil.getGPUs()[0] if GPUtil.getGPUs() else None
if gpu:
gpu_memory = int(gpu.memoryTotal / 1024)
self.set_dword("SetGraphicsCard", 1)
if gpu_memory < 4:
self.set_dword("VMDPI", 240)
self.set_dword("FxaaQuality", 0)
if gpu_memory <= 2:
self.set_dword("LocalShaderCacheEnabled", 0)
self.set_dword("ShaderCacheEnabled", 0)
make_scale(1, low=True)
else:
self.set_dword("LocalShaderCacheEnabled", 1)
self.set_dword("ShaderCacheEnabled", 1)
make_scale(1)
elif gpu_memory < 8 and cpu_value <= 4:
self.set_dword("LocalShaderCacheEnabled", 1)
self.set_dword("ShaderCacheEnabled", 1)
self.set_dword("VMDPI", 480)
self.set_dword("FxaaQuality", 2 if cpu_value == 4 else 1)
make_scale(1)
else:
self.set_dword("LocalShaderCacheEnabled", 1)
self.set_dword("ShaderCacheEnabled", 1)
self.set_dword("VMDPI", 480)
self.set_dword("FxaaQuality", 2)
make_scale(2)
self.set_dword("GraphicsCardEnabled", 1)
else:
self.set_dword("GraphicsCardEnabled", 0)
self.set_dword("LocalShaderCacheEnabled", 0)
self.set_dword("ShaderCacheEnabled", 0)
self.set_dword("VMDPI", 240)
self.set_dword("FxaaQuality", 0)
make_scale(1, low=True)
self.set_dword("ForceDirectX", 1)
self.set_dword("RenderOptimizeEnabled", 1)
self.set_dword("AdbDisable", 0)
self.set_dword("VMMemorySizeInMB", ram_value)
self.set_dword("VMCpuCount", cpu_value)
def add_to_windows_defender_exclusion(self):
"""
Adds the directory of the game loop to the Windows Defender exclusion list.
"""
try:
gameloop_path = os.path.dirname(self.get_local_reg("InstallPath"))
command = ["powershell", "-Command", f"Add-MpPreference -ExclusionPath '{gameloop_path}' -Force"]
subprocess.call(command)
except Exception:
return False
return True
def optimize_gameloop_registry(self):
try:
install_path = self.get_local_reg("InstallPath", path="UI")
registry_keys = [
'AndroidEmulator.exe',
'AndroidEmulatorEn.exe',
'AndroidEmulatorEx.exe',
'aow_exe.exe',
]
base_key = r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options'
value_name = 'CpuPriorityClass'
value_data = '3'
for key in registry_keys:
full_key = fr"{base_key}\{key}\PerfOptions"
command = [
'reg', 'ADD', full_key,
'/v', value_name,
'/t', 'REG_DWORD',
'/d', value_data,
'/f'
]
subprocess.run(command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
registry_entries = [
(
r'HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers',
'~ DISABLEDXMAXIMIZEDWINDOWEDMODE HIGHDPIAWARE'
),
(
r'HKEY_CURRENT_USER\SOFTWARE\Microsoft\DirectX\UserGpuPreferences',
'GpuPreference=2;'
)
]
commands = [
[
'reg', 'ADD', registry_key,
'/v', fr'{install_path}\{key}',
'/t', 'REG_SZ',
'/d', value,
'/f'
]
for registry_key, value in registry_entries
for key in registry_keys
]
for command in commands:
subprocess.run(command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception as e:
self.logger.error(f"Exception occurred: {str(e)}", exc_info=True)
def optimize_for_nvidia(self):
def change_nvidia_profile():
gameloop_ui_path = self.get_local_reg("InstallPath", path="UI").replace("\\", "/")
[Redacted Person] = ET.parse(nvidia_profile_path, parser=ET.XMLParser(encoding='utf-16'))
root = tree.getroot()
profilename = root.find('.//ProfileName')
executeables = root.find('.//Executeables')
path_elem = executeables.find('string')
path_elem.text = f"{gameloop_ui_path}/androidemulatoren.exe".lower()
profilename.text = path_elem.text.replace('/', '\\')
gpu = GPUtil.getGPUs()[0] if GPUtil.getGPUs() else None
filter_setting = tree.find(".//ProfileSetting[SettingNameInfo='Enable FXAA']")
if gpu and gpu.memoryTotal / 1024 < 3:
filter_setting.find('SettingValue').text = '0'
else:
filter_setting.find('SettingValue').text = '1'
tree.write(nvidia_profile_path, encoding='utf-16')
try:
nvidia_profile_path = self.resource_path("assets/mk.nip")
def is_gpu_nvidia() -> bool:
try:
gpu_provider = wmi.WMI().Win32_VideoController()[0].AdapterCompatibility
return "NVIDIA" in gpu_provider
except:
return False
if is_gpu_nvidia():
change_nvidia_profile()
args = [
self.resource_path("assets/nvidiaProfileInspector.exe"),
nvidia_profile_path,
"-silent"
]
subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception as e:
self.logger.error(f"Exception occurred: {str(e)}", exc_info=True)
@[Redacted Person]
def kill_gameloop():
"""
Kills a list of processes related to the gameloop.
Returns:
- True if at least one process was killed.
- False if no process was killed.
"""
# List of processes to be killed
processes_to_kill = [
'aow_exe.exe', # Process 1
'AndroidEmulatorEn.exe', # Process 2
'AndroidEmulator.exe', # Process 3
'AndroidEmulatorEx.exe', # Process 4
'TBSWebRenderer.exe', # Process 5
'syzs_dl_svr.exe', # Process 6
'AppMarket.exe', # Process 7
'QMEmulatorService.exe', # Process 8
'RuntimeBroker.exe', # Process 9
'GameLoader.exe', # Process 10
'TSettingCenter.exe', # Process 11
'Auxillary.exe', # Process 12
'TP3Helper.exe', # Process 13
'tp3helper.dat', # Process 14
'GameDownload.exe' # Process 15
]
processes_killed = 0
for process in processes_to_kill:
result = subprocess.run(['taskkill', '/F', '/IM', process, '/T'], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
if result.returncode == 0:
processes_killed += 1
return processes_killed >= 1
@[Redacted Person]
def change_dns_servers(dns_servers):
"""
Change the DNS servers for all network adapters.
"""
pythoncom.CoInitialize() # Initialize the COM library
wmi_api = wmi.WMI() # Create a WMI API object
# Retrieve all network adapters
adapters = wmi_api.Win32_NetworkAdapterConfiguration(IPEnabled=True)
dns_changed_status = all(adapter.SetDNSServerSearchOrder(dns_servers)[0] == 0 for adapter in adapters)
# Flush DNS cache
subprocess.run(['ipconfig', '/flushdns'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
return dns_changed_status
def ipad_layout_settings(self, reset=False):
"""
Modify the layout of the XML file based on the edited values.
Parameters:
reset (bool): If True, the XML file will be reset to its original state by copying the backup file. If False, the layout will be modified based on the edited values.
"""
appdata_folder = os.getenv('APPDATA')
keymap_folder = os.path.join(appdata_folder, 'AndroidTbox')
original_file = os.path.join(keymap_folder, 'TVM_100.xml')
backup_file = os.path.join(keymap_folder, 'TVM_100.xml.mkbackup')
def set_keymap_layout():
"""
Modify the layout of the XML file based on the edited values.
"""
def update_xml(ipad_keymap):
with open(original_file, 'r', encoding='utf-8') as file:
xml_code = file.read()
root = ET.fromstring(f'<root>{xml_code}</root>')
for pubg_version in self.pubg_versions:
if root.find(f".//Item[@ApkName='{pubg_version}']") is not None:
for query, values in ipad_keymap.items():
for button_name, switches in values.items():
for switch_name, points in switches.items():
item_elem = root.find(f".//Item[@ApkName='{pubg_version}'].//KeyMapMode[@Name='{query}']")
if item_elem is not None:
key_mapping_ex = item_elem.find(f'.//KeyMappingEx[@ItemName="{button_name}"]')
key_mapping = item_elem.find(f'.//KeyMapping[@ItemName="{button_name}"]')
if key_mapping_ex is not None:
if key_mapping_ex.findall(f'.//SwitchOperation[@EnablePositionSwitch]'):
old_x, old_x2 = None, None
for (new_y1, new_y2), point_val in zip(points, key_mapping_ex.findall(
f'.//SwitchOperation[@Description="{switch_name}"]')):
texture, points = point_val.get(f'EnablePositionSwitch').split(":")
x1, y1, x2, y2 = points.split(",")
old_x = x1 if old_x is None else old_x
old_x2 = x2 if old_x2 is None else old_x2
point_val.set('EnablePositionSwitch',
f'{texture}:{old_x},{new_y1},{old_x2},{new_y2}')
else:
for _ in key_mapping_ex.findall(
f'.//SwitchOperation[@EnableSwitch="{switch_name}"]'):
if len(key_mapping_ex.findall(".//Point") or key_mapping_ex.findall(
".//DriveKey") or key_mapping_ex.findall(
".//SwitchOperation")) < len(
points):
zz = key_mapping_ex.findall(".//Point")
for _ in range(len(points) - len(zz)):
zz.append(ET.Element("Point"))
else:
zz = key_mapping_ex.findall(".//Point")
for (x, y), point_val in zip(points, (
zz or key_mapping_ex.findall(
".//DriveKey") or key_mapping_ex.findall(
f'.//SwitchOperation[@EnableSwitch="{switch_name}"]'))):
# if main_value is not None:
if button_name == "Click with Scroll Wheel" and switch_name == "Backpage":
key_mapping_ex.set('Click_X', str(float(x) + 0.1))
key_mapping_ex.set('Click_Y', str(y))
key_mapping_ex.set('Point_X', str(x))
key_mapping_ex.set('Point_Y', str(y))
if point_val.get('Point_X') is not None:
point_val.set('Point_X', str(x))
point_val.set('Point_Y', str(y))
[Redacted Person] key_mapping is not None:
try:
x, y = points
except ValueError:
print(switch_name, points, "Wrong format")
modified_xml_code = ET.tostring(root, encoding='utf-8').decode('utf-8')
return modified_xml_code.replace("<root>", "").replace("</root>", "")
if key_mapping.get('Point_X') is not None:
key_mapping.set('Point_X', str(x))
key_mapping.set('Point_Y', str(y))
if isinstance(points,
Improvements:
get_reg could be get_registry_value).# Get Script Run Location are redundant if the code is clear enough.temp_cleaner: The clear_files inner function can be moved outside or its logic directly included. The multiple try-except blocks could be consolidated or made more specific.gameloop_settings: This function is quite long and could be broken down into smaller, more focused functions for readability and maintainability. The magic numbers (like 75) should be explained or replaced with constants.optimize_gameloop_registry: The construction of registry commands can be made more readable, perhaps using os.path.join for paths.optimize_for_nvidia: The logic for checking GPU and applying settings could be clearer.kill_gameloop: Consider using a list comprehension for conciseness.change_dns_servers: It might be useful to log or handle cases where setting DNS fails for specific adapters.ipad_layout_settings: This function is very complex. Breaking down the update_xml function into smaller, well-named helper functions would greatly improve readability and maintainability. The nested loops and conditional logic are difficult to follow. Consider using more descriptive variable names within this function.Refactored Snippets from app_functions.py (Illustrative Examples):
# ... (imports and Settings class)
class Registry(Settings):
def get_registry_value(self, name):
"""Gets a registry value from HKEY_CURRENT_USER."""
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.REG_PATH, 0, winreg.KEY_READ) as key:
value, _ = winreg.QueryValueEx(key, name)
return value
except FileNotFoundError:
return None
@[Redacted Person]
def get_local_machine_registry_value(name, path="AppMarket"):
"""Gets a registry value from HKEY_LOCAL_MACHINE."""
registry_path = rf'SOFTWARE\WOW6432Node\Tencent\MobileGamePC\{path}'
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, registry_path) as key:
value, _ = winreg.QueryValueEx(key, name)
return value
except OSError:
return None
def set_dword_registry_value(self, name, value):
"""Sets a DWORD value in the Windows registry under HKEY_CURRENT_USER."""
try:
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.REG_PATH) as key:
winreg.SetValueEx(key, name, 0, winreg.REG_DWORD, value)
return True
except WindowsError:
return False
class Optimizer(Registry):
def _remove_files_and_dirs(self, directory):
"""Helper function to remove files and directories within a given directory."""
try:
for root, dirs, files in os.walk(directory):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
shutil.rmtree(os.path.join(root, name), ignore_errors=True)
except Exception as e:
self.logger.error(f"Error cleaning directory: {directory} - {e}")
def temp_cleaner(self):
"""Cleans temporary files and directories."""
base_path = getattr(sys, '_MEIPASS', os.path.abspath('.'))
temp_dir = tempfile.gettempdir()
for item in os.listdir(temp_dir):
item_path = os.path.join(temp_dir, item)
if item_path != base_path:
if os.path.isdir(item_path):
shutil.rmtree(item_path, ignore_errors=True)
else:
try:
os.remove(item_path)
except Exception as e:
self.logger.error(f"Error removing file: {item_path} - {e}")
self._remove_files_and_dirs(r"C:\Windows\Temp")
self._remove_files_and_dirs(os.path.expandvars(r'%windir%\Prefetch'))
gameloop_ui_path = self.get_local_machine_registry_value('InstallPath', path='UI')
if gameloop_ui_path:
self._remove_files_and_dirs(os.path.join(gameloop_ui_path, 'ShaderCache'))
return True
def gameloop_settings(self):
"""Applies optimized settings to the GameLoop emulator based on system hardware."""
def set_render_scale(value, low=False):
"""Sets the render scale for all PUBG versions."""
render_value_map = {0: 2, 1: 2, 2: 2} # Define mapping
if low:
render_value = 2
else:
render_value = render_value_map.get(value, value)
for version_key in self.pubg_versions:
self._set_reg_dword_if_exists(f"{version_key}_ContentScale", value)
self._set_reg_dword_if_exists(f"{version_key}_FPSLevel", 0)
self._set_reg_dword_if_exists(f"{version_key}_RenderQuality", render_value)
ram_percentage = 0.75
ram_bytes = psutil.virtual_memory().total
ram_value_mb = min(round((ram_percentage * ram_bytes) / (1024 ** 2)), 8 * 1024)
cpu_percentage = 0.75
cpu_cores = psutil.cpu_count(logical=False)
cpu_value = min(round(cpu_percentage * cpu_cores), 8)
try:
display_device = EnumDisplayDevices