Skip to content

Commit

Permalink
Merge pull request #27 from latorc/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
latorc committed Apr 24, 2024
2 parents d0f5b1d + 8636cb4 commit 1a4e981
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 24 deletions.
12 changes: 6 additions & 6 deletions bot_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def __init__(self, setting:Settings) -> None:
self.game_flow_id = None # websocket flow that corresponds to the game/match

self.bot_need_update:bool = True # set this True to update bot in main thread
self.mitm_proxinject_need_update:bool = True # set this True to update mitm and prox inject in main thread
self.mitm_proxinject_need_update:bool = False # set this True to update mitm and prox inject in main thread
self.is_loading_bot:bool = False # is bot being loaded
self.main_thread_exception:Exception = None # Exception that had stopped the main thread
self.game_exception:Exception = None # game run time error (but does not break main thread)
Expand Down Expand Up @@ -137,10 +137,10 @@ def is_browser_zoom_off(self):
return True
return False


def set_mitm_proxinject_update(self):
""" restart mitm proxy server"""
self.mitm_proxinject_need_update = True
# mitm restart not working for now. disable this.
# def set_mitm_proxinject_update(self):
# """ restart mitm proxy server"""
# self.mitm_proxinject_need_update = True


def set_bot_update(self):
Expand Down Expand Up @@ -254,7 +254,7 @@ def _create_mitm_and_proxinject(self):
def _run(self):
""" Keep running the main loop (blocking)"""
try:
# self._create_mitm_and_proxinject()
self._create_mitm_and_proxinject()
if self.st.auto_launch_browser:
self.start_browser()

Expand Down
5 changes: 3 additions & 2 deletions common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,11 +206,12 @@ def install_root_cert(cert_file:str):
# f"exit $LASTEXITCODE"
# ]
p=subprocess.run(full_command, **sub_run_args())
stdout, stderr = p.stdout, p.stderr
stdout, stderr = p.stdout, p.stderr
elif sys.platform == "darwin":
# TODO Test on MAC system
result = subprocess.run(['sudo', 'security', 'add-trusted-cert', '-d', '-r', 'trustRoot', '-k', '/Library/Keychains/System.keychain', cert_file],
p = subprocess.run(['sudo', 'security', 'add-trusted-cert', '-d', '-r', 'trustRoot', '-k', '/Library/Keychains/System.keychain', cert_file],
capture_output=True, text=True, check=False)
stdout, stderr = p.stdout, p.stderr
else:
print("Unknown Platform. Please manually install MITM certificate:", cert_file)
return False, ""
Expand Down
19 changes: 12 additions & 7 deletions game/automation.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,14 +340,14 @@ def get_delay(self, mjai_action:dict, gi:GameInfo):

# more time for 19 < 28 < others
pai = mjai_action['pai']
if pai in MJAI_TILES_19:
if pai in MJAI_TILES_19 or pai == gi.my_tsumohai :
extra_time += 0.0
elif pai in MJAI_TILES_28:
extra_time += 0.5
else:
extra_time += random.uniform(0.75, 1.0)
if gi.n_other_reach() > 0: # extra time for other reach
extra_time += random.uniform(0.25, 0.75)
extra_time += random.uniform(0.20, 0.30) * gi.n_other_reach()
extra_time = min(extra_time, 3.0) # cap extra time
delay += extra_time

Expand All @@ -357,6 +357,10 @@ def get_delay(self, mjai_action:dict, gi:GameInfo):
delay += 0.0
elif mjai_type == MjaiType.NUKIDORA:
delay += 0.0
elif mjai_type == MjaiType.RYUKYOKU: # more time for RYUKYOKU
if gi.jikaze == 'E':
delay += 1.5
delay += 2.0
else: # chi/pon/kan/others
delay += 0.5

Expand Down Expand Up @@ -498,9 +502,10 @@ def automate_send_emoji(self):
if roll > self.st.auto_reply_emoji_rate: # send when roll < rate
return


idx = random.randint(0, 8)
x,y = Positions.EMOJI_BUTTON
steps = [ActionStepDelay(random.uniform(1.0,2.5)), ActionStepMove(x*self.scaler, y*self.scaler)]
steps = [ActionStepDelay(random.uniform(1.5, 3.0)), ActionStepMove(x*self.scaler, y*self.scaler)]
steps.append(ActionStepDelay(random.uniform(0.1, 0.2)))
steps.append(ActionStepClick())
x,y = Positions.EMOJIS[idx]
Expand Down Expand Up @@ -736,12 +741,12 @@ def steps_random_wheels(self, total_dx:float, total_dy:float) -> list[ActionStep
total_dx, total_dy: total distance to wheel move"""
# break the wheel action into several steps
steps = []
times = random.randint(2, 5)
times = random.randint(3, 6)
for _i in range(times):
dx = total_dx / times
dy = total_dy / times
steps.append(ActionStepWheel(dx, dy))
steps.append(ActionStepDelay(random.uniform(0.05, 0.11)))
steps.append(ActionStepDelay(random.uniform(0.05, 0.10)))
return steps

def on_lobby_login(self, _liqimsg:dict):
Expand Down Expand Up @@ -827,8 +832,8 @@ def _join_game_iter(self) -> Iterator[ActionStep]:
wx,wy = Positions.LEVELS[1] # wheel at this position
for step in self.steps_randomized_move(wx,wy):
yield step
yield ActionStepDelay(random.uniform(0.5, 1))
for step in self.steps_random_wheels(0, 800):
yield ActionStepDelay(random.uniform(0.5, 0.9))
for step in self.steps_random_wheels(0, 1000):
yield step
yield ActionStepDelay(random.uniform(0.5, 1))
x,y = Positions.LEVELS[self.st.auto_join_level]
Expand Down
16 changes: 8 additions & 8 deletions game/game_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def _input_inner(self, liqi_msg: dict) -> dict | None:
liqi_data = liqi_msg['data']

# SyncGame
if liqi_method == LiqiMethod.syncGame or liqi_method == LiqiMethod.enterGame:
if (liqi_method == LiqiMethod.syncGame or liqi_method == LiqiMethod.enterGame) and liqi_type == MsgType.RES:
# syncGame: disconnect and reconnect
# enterGame: enter game late, while others have started
return self.ms_sync_game(liqi_data)
Expand All @@ -151,14 +151,13 @@ def _input_inner(self, liqi_msg: dict) -> dict | None:
# All players are ready
elif liqi_method == LiqiMethod.fetchGamePlayerState:
if liqi_type == MsgType.RES:
# liqi_data['stateList'] should be ['READY', 'READY', 'READY', 'READY']:
# seems it's always all ready: 'data': {'stateList': ['READY', 'READY', 'READY', 'READY']}
return None

# Game Start
elif liqi_method == LiqiMethod.authGame:
if liqi_type == MsgType.REQ:
# request game info (first entering game)
# self.__init__()
# request entering game. account id for seat index
self.account_id = liqi_data['accountId']
return None
elif liqi_type == MsgType.RES:
Expand All @@ -168,7 +167,7 @@ def _input_inner(self, liqi_msg: dict) -> dict | None:
raise RuntimeError(f'Unexpected liqi message, method={liqi_method}, type={liqi_type}')

# Actions
elif liqi_method == LiqiMethod.ActionPrototype:
elif liqi_method == LiqiMethod.ActionPrototype: # assert all ActionPrototype are notify type
# We assume here, when there is new action, last reaction has done/expired
self.last_reaction_pending = False

Expand All @@ -183,16 +182,16 @@ def _input_inner(self, liqi_msg: dict) -> dict | None:
LOGGER.warning("operation seat %s != self.seat %s", liqi_data['data']['operation']['seat'], self.seat)
if 'operationList' not in liqi_data['data']['operation']:
LOGGER.warning("No operation List: %s", liqi_data['data']['operation'])
else:
LOGGER.warning("No data in liqi_data: %s", liqi_data)

if liqi_data['name'] == LiqiAction.NewRound:
self.kyoku_state.first_round = True
return self.ms_new_round(liqi_data)

else: # other rounds
self.kyoku_state.first_round = False # not first round
return self.ms_action_prototype(liqi_data)


return self.ms_action_prototype(liqi_data)

# end_game
elif liqi_method == LiqiMethod.NotifyGameEndResult:
Expand Down Expand Up @@ -236,6 +235,7 @@ def ms_auth_game(self, liqi_data:dict) -> dict:
try:
self.mode_id = liqi_data['gameConfig']['meta']['modeId']
except Exception:
LOGGER.warning("No modeId in liqi_data['gameConfig']['meta']['modeId']")
self.mode_id = -1

seatList:list = liqi_data['seatList']
Expand Down
2 changes: 1 addition & 1 deletion updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def task_update():
LOGGER.info("Loading help html from %s", url)
html_text = self.get_html(url)
if html_text is None:
self.help_html = f"""Help Information: <a href="{url}">{url}</a><br>Error loading help.<br>{self.help_exception}"""
self.help_html = f"""Error loading <a href="{url}">{url}help</a><br>{self.help_exception}"""
LOGGER.warning(self.help_html)
else:
self.help_html = html_text
Expand Down

0 comments on commit 1a4e981

Please sign in to comment.