Files
julius_baer_onboarding/services/player.py

82 lines
2.6 KiB
Python
Raw Normal View History

2025-04-12 11:58:01 +02:00
import logging
import threading
import time
2025-04-12 11:58:01 +02:00
from typing import Literal, Dict, Any
import config
from dto.requests import GameStartRequestDTO, GameDecisionRequestDTO
from services.julius_baer_api_client import JuliusBaerApiClient
from utils.storage.game_files_manager import store_game_round_data, store_decision
2025-04-12 11:58:01 +02:00
2025-04-12 13:59:59 +02:00
log = logging.getLogger(__name__)
2025-04-12 11:58:01 +02:00
class Player:
def __init__(self):
self.client = JuliusBaerApiClient()
self._thread = None
2025-04-12 11:58:01 +02:00
def start(self):
self.play()
def play_on_separate_thread(self):
if self._thread and self._thread.is_alive():
2025-04-12 13:59:59 +02:00
log.warning('Game loop already running.')
return self._thread
self._thread = threading.Thread(target=self.play, daemon=True)
self._thread.start()
return self._thread
2025-04-12 11:58:01 +02:00
def play(self):
2025-04-12 13:59:59 +02:00
log.info('playing')
2025-04-12 11:58:01 +02:00
payload = GameStartRequestDTO(player_name=config.API_TEAM)
start_response = self.client.start_game(payload)
2025-04-12 13:59:59 +02:00
log.info('game started, session id: %s', start_response.session_id)
2025-04-12 11:58:01 +02:00
decision = self.make_decision(start_response.client_data)
2025-04-12 13:40:51 +02:00
decision_counter = 0
client_id = start_response.client_id
2025-04-12 13:40:51 +02:00
is_game_running = True
while is_game_running:
2025-04-12 11:58:01 +02:00
payload = GameDecisionRequestDTO(
decision=decision,
session_id=start_response.session_id,
client_id=client_id,
2025-04-12 11:58:01 +02:00
)
log.info('client id: %s', client_id)
decision_response = self.client.send_decision(payload)
2025-04-12 13:59:59 +02:00
log.info(f'decision: {decision}, response status: {decision_response.status}, score: {decision_response.score}')
2025-04-12 11:58:01 +02:00
status = decision_response.status
is_game_running = status not in ['gameover', 'complete']
if is_game_running:
store_decision(str(client_id), decision)
client_id = decision_response.client_id
2025-04-12 11:58:01 +02:00
decision = self.make_decision(decision_response.client_data)
2025-04-12 13:40:51 +02:00
2025-04-12 14:00:11 +02:00
# Handle first response from game initialization logic
if decision_counter == 0:
# Store start response
store_game_round_data(decision, start_response, decision_counter, str(start_response.session_id) ,status)
else:
# store ongoing decision response
store_game_round_data(decision, decision_response, decision_counter, str(start_response.session_id), status)
2025-04-12 13:40:51 +02:00
decision_counter += 1
time.sleep(1)
2025-04-12 14:00:11 +02:00
2025-04-12 11:58:01 +02:00
def make_decision(self, client_data: Dict[str, Any]) -> Literal["Accept", "Reject"]:
# Do your magic!
return 'Accept' # Replace me!!
2025-04-12 11:58:01 +02:00