File size: 9,250 Bytes
3e9e3ce |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
import asyncio
import json
import websockets
import requests
import base64
import time
import mss
import numpy as np
from PIL import Image
from io import BytesIO
from datetime import datetime
import pyautogui
class Dino:
def __init__(self, class_name):
self.class_name = class_name
self.ws_url = self.get_ws_url()
self.websocket = None
self.command_id = 1
@staticmethod
def get_ws_url():
response = requests.get('http://localhost:1234/json')
data = response.json()
return data[0]['webSocketDebuggerUrl']
async def connect(self):
self.websocket = await websockets.connect(self.ws_url)
# Enable necessary domains
await self.send_command("DOM.enable", {})
await self.send_command("CSS.enable", {})
await self.send_command("Page.enable", {})
await self.send_command("Runtime.enable", {})
async def send_command(self, method, params):
command = {
"id": self.command_id,
"method": method,
"params": params
}
await self.websocket.send(json.dumps(command))
self.command_id += 1
while True:
response = await self.websocket.recv()
response_data = json.loads(response)
if response_data.get("id") == command["id"]:
return response_data
async def capture_screenshot(self):
try:
# Get document root
root = await self.send_command("DOM.getDocument", {"depth": -1})
root_node_id = root["result"]["root"]["nodeId"]
# Get the node ID of the element with the specified class name
search = await self.send_command("DOM.querySelector", {"nodeId": root_node_id, "selector": f".{self.class_name}"})
node_id = search["result"]["nodeId"]
# Get the box model of the element
box_model = await self.send_command("DOM.getBoxModel", {"nodeId": node_id})
content_box = box_model["result"]["model"]["content"]
# Capture screenshot of the area
screenshot = await self.send_command("Page.captureScreenshot", {
"clip": {
"x": content_box[0],
"y": content_box[1],
"width": content_box[2] - content_box[0],
"height": content_box[5] - content_box[1],
"scale": 1
}
})
# Decode the base64 screenshot data
screenshot_data = base64.b64decode(screenshot["result"]["data"])
image = Image.open(BytesIO(screenshot_data))
resized_image = image.resize((image.width//5, image.height//5))
# Get the current date and time
#current_time = datetime.now()
# Format the date and time as a string
#timestamp_string = current_time.strftime('%H:%M:%S')
cropped_image = resized_image.crop((52, 0, 82, resized_image.height))
final_image = cropped_image.resize((30, 92))
return final_image
except Exception as e:
print(f"An error occurred: {e}")
async def get_window_name(self):
try:
# Evaluate JavaScript to get the window name
response = await self.send_command("Runtime.evaluate", {
"expression": "window.name"
})
#print(response)
window_name = response["result"]["result"]["value"]
print(f"Window name: {window_name}")
return window_name
except Exception as e:
print(f"An error occurred while getting window name: {e}")
return None
async def enable_all_obstacles(self):
try:
# Evaluate JavaScript to get the window name
response = await self.send_command("Runtime.evaluate", {
"expression": "spriteDefinitionByType.original.OBSTACLES[2].minSpeed = 0"
})
print(f"Enabled all obstacles")
return True
except Exception as e:
print(f"An error occurred while enabling obstacles: {e}")
return None
async def open_dino(self):
try:
response = await self.send_command("Page.navigate", {
"url": "chrome://dino/"
})
return True
except Exception as e:
print(f"An error occurred while opening game: {e}")
return None
async def send_key_event(self, key, code, key_code):
try:
response1 = await self.send_command("Input.dispatchKeyEvent", {
"type": "rawKeyDown",
"key": key,
"code": code,
"keyCode": key_code,
"windowsVirtualKeyCode": key_code,
"nativeVirtualKeyCode": key_code,
"modifiers": 0
})
if key_code == 40: time.sleep(0.4)
response = await self.send_command("Input.dispatchKeyEvent", {
"type": "keyUp",
"key": key,
"code": code,
"keyCode": key_code,
"windowsVirtualKeyCode": key_code,
"nativeVirtualKeyCode": key_code,
"modifiers": 0
})
return True
except Exception as e:
print(f"An error occurred while sending key event: {e}")
return None
async def send_key_event2(self, key):
try:
pyautogui.press(key)
return True
except Exception as e:
print(f"An error occurred while sending key event: {e}")
return None
async def check_status(self):
try:
crashed = await self.send_command("Runtime.evaluate", {
"expression": "Runner.instance_.crashed"
})
score = 0.0
try:
score = await self.send_command("Runtime.evaluate", {
"expression": "Runner.instance_.distanceRan"
})
score = float(score['result']['result']['value']) // 10
except:
pass
return {
"crashed": crashed['result']['result']['value'],
"score": score
}
except Exception as e:
print(f"An error occurred while checking status: {e}")
return None
async def complete_action(self):
try:
crashed = await self.send_command("Runtime.evaluate", {
"expression": "Runner.instance_.crashed"
})
crashed = crashed['result']['result']['value']
while not crashed:
jumping = await self.send_command("Runtime.evaluate", {
"expression": "Runner.instance_.tRex.jumping"
})
jumping = jumping['result']['result']['value']
ducking = await self.send_command("Runtime.evaluate", {
"expression": "Runner.instance_.tRex.ducking"
})
ducking = ducking['result']['result']['value']
crashed = await self.send_command("Runtime.evaluate", {
"expression": "Runner.instance_.crashed"
})
crashed = crashed['result']['result']['value']
if (not jumping) and (not ducking): break
except Exception as e:
print(f"An error occurred while selecting action: {e}")
return None
async def capture_screenshot2(self):
try:
with mss.mss() as sct:
# Define the region to capture
monitor = {
"top": 245,
"left": 730,
"width": 200,
"height": 45,
}
# Capture the screenshot
screenshot = sct.grab(monitor)
# Convert the raw bytes data to a numpy array
img = np.array(screenshot)
# Convert the BGRA image to RGB
img = img[:, :, :3]
img = img[..., ::-1]
# Convert the numpy array to a PIL image
image = Image.fromarray(img)
#resized_image = image.resize((100, 80))
# Get the current date and time
#current_time = datetime.now()
# Format the date and time as a string
#timestamp_string = current_time.strftime('%H:%M:%S')
#resized_image.save(timestamp_string + 'resized_image.png')
return image
except Exception as e:
print(f"An error occurred while opening game: {e}")
return None
async def start(self):
await self.connect()
# Get the window name once
#await self.get_window_name()
#await self.capture_screenshot()
|